Skip to main content

spec_driven_docs/domain/
paths.rs

1//! Every control path this tool names, declared once.
2//!
3//! Two kinds of path meet here and stay apart. A control path is this
4//! tool's own: the instance directory, the declaration, the debt files, the
5//! hook configuration, the agent digest, the state and cache roots, and the
6//! agent skill roots. A destination is what a release projects into a
7//! target, and it is versioned data rather than a constant, so it stays
8//! with the projection and reaches this module only as a resolved value.
9//!
10//! The module is otherwise pure. It reads no filesystem. It reads the
11//! process environment in exactly one place, [`UserEnv::from_process`], so
12//! every resolver below takes the environment as an argument and a test
13//! constructs one instead of mutating the process.
14
15use std::collections::BTreeMap;
16
17use camino::{Utf8Path, Utf8PathBuf};
18use serde::Serialize;
19
20use crate::domain::markdownlint;
21use crate::domain::profile::{DocsRoot, ProfileId};
22
23/// The variable naming the invoking user's home directory.
24pub const HOME_VAR: &str = "HOME";
25/// The variable relocating Claude Code's whole configuration directory.
26pub const CLAUDE_CONFIG_DIR_VAR: &str = "CLAUDE_CONFIG_DIR";
27/// The variable naming the XDG state base directory.
28pub const XDG_STATE_HOME_VAR: &str = "XDG_STATE_HOME";
29/// The variable naming the XDG cache base directory.
30pub const XDG_CACHE_HOME_VAR: &str = "XDG_CACHE_HOME";
31/// The variable that tells this tool to reach no network.
32pub const OFFLINE_VAR: &str = "SDD_OFFLINE";
33/// The variable that names the docs scratch.
34pub const DOCS_SCRATCH_VAR: &str = "SDD_DOCS_SCRATCH";
35/// The variable an operator sets to hold the consumer pin where it is.
36pub const SELF_DEPEND_OFF_VAR: &str = "SDD_SELF_DEPEND_OFF";
37/// The command `sdd lint prove` runs in place of the delivered hook, as
38/// whitespace-separated words, for a host that runs the hook another way.
39pub const LINT_PROVE_RUNNER_VAR: &str = "SDD_LINT_PROVE_RUNNER";
40/// The variable a continuous-integration environment sets, where the pin
41/// is whatever the checkout carries.
42pub const CI_VAR: &str = "CI";
43/// The variable direnv exports while it evaluates an `.envrc`.
44///
45/// direnv 2.38.2 sets it in its embedded stdlib (`export DIRENV_IN_ENVRC=1`),
46/// so a command that sees it runs from a shell loader, not from a person.
47pub const DIRENV_IN_ENVRC_VAR: &str = "DIRENV_IN_ENVRC";
48/// The loopback origin a test serves the registry index from, in place of
49/// the public index.
50pub const HTTP_ORIGIN_VAR: &str = "SDD_HTTP_ORIGIN";
51
52/// This tool's directory name under a base directory.
53pub const TOOL_DIR: &str = "spec-driven-docs";
54
55/// The instance directory, relative to the instance root.
56pub const INSTANCE_DIR: &str = ".spec-driven-docs";
57/// The manifest path, relative to the instance root.
58pub const MANIFEST_PATH: &str = ".spec-driven-docs/manifest.json";
59/// Where an instance keeps its declaration.
60pub const CONFIG_PATH: &str = ".spec-driven-docs/config.yaml";
61/// Where an instance keeps its debt.
62pub const DEBT_PATH: &str = ".spec-driven-docs/debt.yaml";
63/// The flat list of exempt chapters an older instance carries.
64pub const LEGACY_DEBT_PATH: &str = ".spec-driven-docs/chapter-size-debt.txt";
65/// Where a pre-commit configuration lives in a target.
66pub const HOOKS_CONFIG_PATH: &str = ".pre-commit-config.yaml";
67/// Where the documentation block lives in a target.
68pub const AGENTS_DIGEST_PATH: &str = "AGENTS.md";
69
70/// The roots this tool owns whole, where a landing also removes a directory
71/// that a deletion emptied.
72pub const PRUNABLE_ROOTS: &[&str] = &[".spec-driven-docs/", ".claude/skills/", ".agents/skills/"];
73
74/// The state root, relative to the home directory, where no variable moves it.
75pub const STATE_ROOT: &str = ".local/state/spec-driven-docs";
76/// The cache root, relative to the home directory, where no variable moves it.
77pub const CACHE_ROOT: &str = ".cache/spec-driven-docs";
78/// The user-scope skill receipt, relative to the state root.
79pub const SKILL_RECEIPT_FILE: &str = "skills.json";
80/// The one file every skill package must carry.
81pub const SKILL_FILE: &str = "SKILL.md";
82/// Where a skill package holds what the shared source materialized into it.
83pub const SKILL_REFERENCES_DIR: &str = "references";
84
85/// The user-scope lock, relative to the state root.
86pub const SKILL_LOCK_FILE: &str = "skills.lock";
87/// The retired per-checkout sync stamps, relative to the state root.
88pub const SELF_DEPEND_STAMP_DIR: &str = "self-depend";
89/// The per-checkout version-check caches, relative to the cache root.
90pub const SELF_DEPEND_CACHE_DIR: &str = "self-depend";
91/// The user-scope skill receipt at the home-relative path, read once.
92///
93/// A home installed before the state root followed `XDG_STATE_HOME` holds
94/// its receipt here. The next apply reads it, then writes only the resolved
95/// path.
96pub const LEGACY_SKILL_RECEIPT_PATH: &str = ".local/state/spec-driven-docs/skills.json";
97/// The retired root that once held what every skill shares.
98///
99/// A skill package now carries its own copy under `references/`, so this
100/// root is swept rather than written. A file there the receipt vouches for
101/// is the tool's and goes; anything else is the user's and stays.
102pub const LEGACY_SHARED_ROOT: &str = ".local/state/spec-driven-docs/skills/shared";
103/// The skill root Claude Code reads, relative to the home directory.
104pub const CLAUDE_ROOT: &str = ".claude/skills";
105/// The skill root every other agent reads, relative to the home directory.
106pub const AGENTS_ROOT: &str = ".agents/skills";
107
108/// Which agent family a skill root serves.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
110#[serde(rename_all = "kebab-case")]
111pub enum AgentId {
112    /// Claude Code, which reads its own configuration directory.
113    Claude,
114    /// The shared root Codex, `OpenCode`, and Pi each document that they read.
115    Agents,
116}
117
118impl AgentId {
119    /// The kebab-case name used on the command line and in the report.
120    #[must_use]
121    pub const fn as_str(self) -> &'static str {
122        match self {
123            Self::Claude => "claude",
124            Self::Agents => "agents",
125        }
126    }
127}
128
129impl std::fmt::Display for AgentId {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        f.write_str(self.as_str())
132    }
133}
134
135/// One agent skill root, and what relocates it.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub struct AgentRoot {
138    /// The family this root serves.
139    pub id: AgentId,
140    /// The root, relative to the home directory, where no variable moves it.
141    pub default: &'static str,
142    /// The variable relocating the agent's whole configuration directory.
143    pub config_env: Option<&'static str>,
144    /// The root, relative to that variable's value.
145    pub relocated: &'static str,
146}
147
148/// The root Claude Code reads, and the variable that relocates it.
149const CLAUDE: AgentRoot = AgentRoot {
150    id: AgentId::Claude,
151    default: CLAUDE_ROOT,
152    config_env: Some(CLAUDE_CONFIG_DIR_VAR),
153    relocated: "skills",
154};
155
156/// The root every other agent reads. No variable relocates it.
157const AGENTS: AgentRoot = AgentRoot {
158    id: AgentId::Agents,
159    default: AGENTS_ROOT,
160    config_env: None,
161    relocated: "skills",
162};
163
164/// Every agent skill root this tool writes, in report order.
165///
166/// Two rows, and no third. Codex, `OpenCode`, and Pi each document that they
167/// read the shared root, checked 2026-09-12, so a row per host would be
168/// three names for one directory. A host with a root of its own is one more
169/// row and one more test on the day it needs one.
170pub const AGENT_ROOTS: &[AgentRoot] = &[CLAUDE, AGENTS];
171
172/// The agent root one identifier names.
173#[must_use]
174pub const fn agent_root(id: AgentId) -> &'static AgentRoot {
175    match id {
176        AgentId::Claude => &CLAUDE,
177        AgentId::Agents => &AGENTS,
178    }
179}
180
181/// What decided a path.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
183#[serde(rename_all = "kebab-case")]
184pub enum PathSource {
185    /// The instance manifest records it.
186    Recorded,
187    /// Nothing moved it, so it is the declared default.
188    Default,
189    /// A variable carries it.
190    Env,
191    /// The profile's documentation root derives it.
192    Profile,
193    /// The target's own shape suggests it, and nothing recorded it.
194    Proposal,
195}
196
197/// One resolved path, and what decided it.
198#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
199pub struct PathEntry {
200    /// The resolved path.
201    pub path: Utf8PathBuf,
202    /// What decided it.
203    pub source: PathSource,
204}
205
206impl PathEntry {
207    /// A path nothing moved.
208    #[must_use]
209    pub fn default_at(path: impl Into<Utf8PathBuf>) -> Self {
210        Self {
211            path: path.into(),
212            source: PathSource::Default,
213        }
214    }
215
216    /// A path a variable carried.
217    #[must_use]
218    pub fn from_env(path: impl Into<Utf8PathBuf>) -> Self {
219        Self {
220            path: path.into(),
221            source: PathSource::Env,
222        }
223    }
224}
225
226/// One resolved agent skill root.
227#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
228pub struct AgentRootEntry {
229    /// The family this root serves.
230    pub id: AgentId,
231    /// The absolute root.
232    pub path: Utf8PathBuf,
233    /// What decided it.
234    pub source: PathSource,
235    /// The variable that relocated it, where one did.
236    pub variable: Option<&'static str>,
237}
238
239/// Where a location the project owns actually sits.
240///
241/// The four absent-looking cases are not one case. A repository-relative
242/// directory is checkable from a fresh clone. A directory outside the
243/// repository is not, and neither is one a variable resolves at run time,
244/// and a project that keeps none promises nothing at all.
245#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
246#[serde(tag = "kind", rename_all = "kebab-case")]
247pub enum ProjectLocation {
248    /// A repository-relative directory under version control.
249    Tracked {
250        /// Where it sits, relative to the instance root.
251        path: Utf8PathBuf,
252        /// What decided it.
253        source: PathSource,
254    },
255    /// A repository-relative directory version control does not carry.
256    Untracked {
257        /// Where it sits, relative to the instance root.
258        path: Utf8PathBuf,
259        /// What decided it.
260        source: PathSource,
261    },
262    /// A directory outside the repository.
263    External {
264        /// Where it sits, as the record carries it.
265        path: Utf8PathBuf,
266        /// What decided it.
267        source: PathSource,
268    },
269    /// Wherever a variable resolves at run time.
270    Env {
271        /// The variable that carries it.
272        variable: &'static str,
273        /// What that variable carries here, when it is set.
274        value: Option<String>,
275    },
276    /// The project keeps none.
277    None,
278}
279
280/// One answer the operator can give for a location the project owns.
281///
282/// A choice carries a path only where the target already holds that
283/// directory. Inventing one would put a path this tool made up in front of
284/// an operator as though the repository had suggested it.
285#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
286#[serde(tag = "kind", rename_all = "kebab-case")]
287pub enum LocationChoice {
288    /// A repository-relative directory the target already carries.
289    Observed {
290        /// Where it sits, relative to the target root.
291        path: Utf8PathBuf,
292    },
293    /// Wherever a variable resolves at run time.
294    Env {
295        /// The variable that would carry it.
296        variable: &'static str,
297        /// What that variable carries here, when it is set.
298        value: Option<String>,
299    },
300    /// A path the operator types.
301    Operator,
302    /// The project keeps none.
303    None,
304}
305
306/// The choices this target offers for the docs scratch.
307#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
308pub struct Proposals {
309    /// What the docs scratch can be here.
310    pub docs_scratch: Vec<LocationChoice>,
311}
312
313/// Every user-scope path, resolved.
314#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
315pub struct UserPaths {
316    /// Where this tool keeps state that outlives a command.
317    pub state_root: PathEntry,
318    /// Where this tool keeps what it can fetch again.
319    pub cache_root: PathEntry,
320    /// The receipt of the skill copies an earlier release installed under
321    /// the home, reported only while one exists.
322    #[serde(skip_serializing_if = "Option::is_none")]
323    pub skill_receipt: Option<PathEntry>,
324    /// The agent skill roots an earlier release installed into, deduplicated
325    /// by resolved path, reported only while a receipt exists.
326    #[serde(skip_serializing_if = "Vec::is_empty")]
327    pub agent_roots: Vec<AgentRootEntry>,
328}
329
330impl UserPaths {
331    /// The same paths, with the skill entries kept only while a receipt of
332    /// an earlier install exists, at the resolved path or the legacy one.
333    #[must_use]
334    pub fn with_skill_entries_while_a_receipt_exists(mut self, legacy: Option<&Utf8Path>) -> Self {
335        let held = self
336            .skill_receipt
337            .as_ref()
338            .is_some_and(|receipt| receipt.path.is_file())
339            || legacy.is_some_and(Utf8Path::is_file);
340        if !held {
341            self.skill_receipt = None;
342            self.agent_roots.clear();
343        }
344        self
345    }
346}
347
348/// Every control and documentation destination inside one target.
349#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
350pub struct InstancePaths {
351    /// The instance directory.
352    pub instance_dir: PathEntry,
353    /// The instance manifest.
354    pub manifest: PathEntry,
355    /// What the project declares about the files its gates judge.
356    pub declaration: PathEntry,
357    /// The inherited violations the budget gates read.
358    pub debt: PathEntry,
359    /// The flat list an instance older than the debt file carries.
360    pub legacy_debt: PathEntry,
361    /// The pre-commit configuration carrying the managed block.
362    pub hooks_config: PathEntry,
363    /// The root agent digest carrying the documentation block.
364    pub agents_digest: PathEntry,
365    /// The documentation root.
366    pub docs_root: PathEntry,
367    /// Where the specifications sit.
368    pub specs: PathEntry,
369    /// Where the decision records sit.
370    pub decisions: PathEntry,
371    /// Where the reference material sits.
372    pub reference: PathEntry,
373    /// Where the step-by-step guides sit.
374    pub guides: PathEntry,
375    /// The documentation root's lint configuration, which the landing
376    /// manages.
377    pub lint_config: PathEntry,
378    /// Where the Markdown linter discovers configuration, and which of those
379    /// locations would replace the managed one.
380    pub lint_discovery: LintDiscovery,
381}
382
383/// The locations the Markdown linter discovers configuration in, sorted by
384/// what a project may keep there.
385///
386/// The names come from [`crate::domain::markdownlint`], so a caller that
387/// needs one reads it here rather than spelling it.
388#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
389pub struct LintDiscovery {
390    /// Every configuration name of both families at the repository root.
391    /// The project keeps whatever it holds here, and the first name is where
392    /// the landing seeds one where the root holds none.
393    pub repository_root: Vec<PathEntry>,
394    /// Every file at the documentation root that would replace the managed
395    /// configuration's settings.
396    pub refused_at_docs_root: Vec<PathEntry>,
397    /// The directories beneath which a configuration of either family, at
398    /// any depth, would replace the managed heading shapes.
399    pub refused_beneath: Vec<PathEntry>,
400}
401
402/// One landed instance's paths, as the record and the environment leave them.
403#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
404pub struct ActivePaths {
405    /// The recorded profile.
406    pub profile: ProfileId,
407    /// Every destination the record implies.
408    pub destinations: InstancePaths,
409    /// Where material that is not a statement yet is staged.
410    pub docs_scratch: ProjectLocation,
411}
412
413/// One profile's destinations, derived and recorded nowhere.
414#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
415pub struct CandidatePaths {
416    /// The profile these destinations belong to.
417    pub profile: ProfileId,
418    /// Every destination that profile implies.
419    pub destinations: InstancePaths,
420}
421
422/// Every path this binary can name for one target and one user.
423#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
424pub struct Paths {
425    /// What resolves under the invoking user's home directory, or `null`
426    /// where the home variable is unset and nothing under it resolves.
427    pub user: Option<UserPaths>,
428    /// What the target records, or `null` where it carries no instance.
429    pub active: Option<ActivePaths>,
430    /// What each profile would imply, whether or not one is recorded.
431    pub candidates: BTreeMap<String, CandidatePaths>,
432    /// What this target offers for the docs scratch.
433    pub proposals: Proposals,
434}
435
436/// What the process environment carries, read once and passed down.
437#[derive(Debug, Clone, Default, PartialEq, Eq)]
438pub struct UserEnv {
439    /// The invoking user's home directory.
440    pub home: Option<Utf8PathBuf>,
441    /// Where Claude Code's configuration directory was moved to.
442    pub claude_config_dir: Option<Utf8PathBuf>,
443    /// The XDG state base directory.
444    pub xdg_state_home: Option<Utf8PathBuf>,
445    /// The XDG cache base directory.
446    pub xdg_cache_home: Option<Utf8PathBuf>,
447    /// What the docs-scratch variable carries.
448    pub docs_scratch: Option<String>,
449}
450
451/// What one variable carries, or `None` where it is unset or blank.
452///
453/// A variable set to the empty string is a variable the shell exported and
454/// nothing filled in. Treating it as a path would resolve every root to the
455/// filesystem root.
456#[must_use]
457pub fn variable(name: &str) -> Option<String> {
458    std::env::var(name)
459        .ok()
460        .map(|value| value.trim().to_string())
461        .filter(|value| !value.is_empty())
462}
463
464impl UserEnv {
465    /// Read every variable this module resolves from, once.
466    #[must_use]
467    pub fn from_process() -> Self {
468        let path = |name: &str| variable(name).map(Utf8PathBuf::from);
469        Self {
470            home: path(HOME_VAR),
471            claude_config_dir: path(CLAUDE_CONFIG_DIR_VAR),
472            xdg_state_home: path(XDG_STATE_HOME_VAR),
473            xdg_cache_home: path(XDG_CACHE_HOME_VAR),
474            docs_scratch: variable(DOCS_SCRATCH_VAR),
475        }
476    }
477
478    /// The state root, through the XDG variable or its default.
479    #[must_use]
480    pub fn state_root(&self) -> Option<PathEntry> {
481        if let Some(base) = self.xdg_state_home.as_ref() {
482            return Some(PathEntry::from_env(base.join(TOOL_DIR)));
483        }
484        self.home
485            .as_ref()
486            .map(|home| PathEntry::default_at(home.join(STATE_ROOT)))
487    }
488
489    /// The home-relative state root, whatever the variable says.
490    ///
491    /// One fallback read lives here: a receipt written before the state root
492    /// followed `XDG_STATE_HOME`, and the two gate files that release left
493    /// under the retired shared root.
494    #[must_use]
495    pub fn legacy_state_root(&self) -> Option<Utf8PathBuf> {
496        self.home.as_ref().map(|home| home.join(STATE_ROOT))
497    }
498
499    /// The cache root, through the XDG variable or its default.
500    #[must_use]
501    pub fn cache_root(&self) -> Option<PathEntry> {
502        if let Some(base) = self.xdg_cache_home.as_ref() {
503            return Some(PathEntry::from_env(base.join(TOOL_DIR)));
504        }
505        self.home
506            .as_ref()
507            .map(|home| PathEntry::default_at(home.join(CACHE_ROOT)))
508    }
509
510    /// One agent skill root, resolved with what decided it.
511    #[must_use]
512    pub fn agent_root(&self, id: AgentId) -> Option<AgentRootEntry> {
513        let row = agent_root(id);
514        let home = self.home.as_ref()?;
515        let relocated = match row.id {
516            AgentId::Claude => self.claude_config_dir.as_ref(),
517            AgentId::Agents => None,
518        };
519        Some(relocated.map_or_else(
520            || AgentRootEntry {
521                id: row.id,
522                path: home.join(row.default),
523                source: PathSource::Default,
524                variable: None,
525            },
526            |base| AgentRootEntry {
527                id: row.id,
528                path: base.join(row.relocated),
529                source: PathSource::Env,
530                variable: row.config_env,
531            },
532        ))
533    }
534
535    /// Every selected agent root, in table order, deduplicated by the
536    /// directory each one reaches.
537    ///
538    /// Two selected roots that resolve to one directory are one destination.
539    /// Planning it twice would list every file twice and make an install
540    /// compare a write against itself.
541    #[must_use]
542    pub fn agent_roots(&self, selected: &[AgentId]) -> Vec<AgentRootEntry> {
543        let mut resolved: Vec<AgentRootEntry> = Vec::new();
544        for row in AGENT_ROOTS {
545            if !selected.contains(&row.id) {
546                continue;
547            }
548            let Some(entry) = self.agent_root(row.id) else {
549                continue;
550            };
551            // Two spellings of one directory, such as a configuration
552            // directory whose skill root links to the user's own, are one.
553            let reached = |path: &Utf8Path| {
554                std::fs::canonicalize(path).unwrap_or_else(|_| path.as_std_path().to_path_buf())
555            };
556            if resolved
557                .iter()
558                .any(|held| reached(&held.path) == reached(&entry.path))
559            {
560                continue;
561            }
562            resolved.push(entry);
563        }
564        resolved
565    }
566
567    /// Every user-scope path, with every agent root selected.
568    #[must_use]
569    pub fn user_paths(&self) -> Option<UserPaths> {
570        let state = self.state_root()?;
571        let cache = self.cache_root()?;
572        Some(UserPaths {
573            skill_receipt: Some(PathEntry {
574                path: state.path.join(SKILL_RECEIPT_FILE),
575                source: state.source,
576            }),
577            agent_roots: self.agent_roots(&[AgentId::Claude, AgentId::Agents]),
578            state_root: state,
579            cache_root: cache,
580        })
581    }
582}
583
584/// Every destination one documentation root implies.
585#[must_use]
586pub fn instance_paths(docs_root: DocsRoot) -> InstancePaths {
587    let docs = Utf8PathBuf::from(docs_root.as_str());
588    let under = |leaf: &str| PathEntry {
589        path: docs.join(leaf),
590        source: PathSource::Profile,
591    };
592    InstancePaths {
593        instance_dir: PathEntry::default_at(INSTANCE_DIR),
594        manifest: PathEntry::default_at(MANIFEST_PATH),
595        declaration: PathEntry::default_at(CONFIG_PATH),
596        debt: PathEntry::default_at(DEBT_PATH),
597        legacy_debt: PathEntry::default_at(LEGACY_DEBT_PATH),
598        hooks_config: PathEntry::default_at(HOOKS_CONFIG_PATH),
599        agents_digest: PathEntry::default_at(AGENTS_DIGEST_PATH),
600        docs_root: PathEntry {
601            path: docs.clone(),
602            source: PathSource::Profile,
603        },
604        specs: under("specs"),
605        decisions: under("decisions"),
606        reference: under("reference"),
607        guides: under("guides"),
608        lint_config: under(markdownlint::CLI2_NAMES[0]),
609        lint_discovery: LintDiscovery {
610            repository_root: markdownlint::discovery_names()
611                .map(PathEntry::default_at)
612                .collect(),
613            refused_at_docs_root: markdownlint::LIBRARY_NAMES
614                .iter()
615                .map(|name| under(name))
616                .collect(),
617            refused_beneath: vec![under("specs"), under("decisions")],
618        },
619    }
620}
621
622/// The same destinations, marked as the record's rather than a profile's.
623#[must_use]
624pub fn recorded_paths(docs_root: DocsRoot) -> InstancePaths {
625    let mut paths = instance_paths(docs_root);
626    for entry in [
627        &mut paths.docs_root,
628        &mut paths.specs,
629        &mut paths.decisions,
630        &mut paths.reference,
631        &mut paths.guides,
632        &mut paths.lint_config,
633    ]
634    .into_iter()
635    .chain(&mut paths.lint_discovery.refused_at_docs_root)
636    .chain(&mut paths.lint_discovery.refused_beneath)
637    {
638        entry.source = PathSource::Recorded;
639    }
640    paths
641}
642
643/// One profile's derived destinations, per profile, keyed by its name.
644#[must_use]
645pub fn candidates() -> BTreeMap<String, CandidatePaths> {
646    ProfileId::every()
647        .map(|profile| {
648            (
649                profile.as_str().to_string(),
650                CandidatePaths {
651                    profile,
652                    destinations: instance_paths(profile.profile().docs_root),
653                },
654            )
655        })
656        .collect()
657}
658
659/// Where the record says the docs scratch sits.
660///
661/// A recorded scratch may leave the repository, because staging beside the
662/// checkout is one of the offered answers, so the leading component decides
663/// which kind it is. The variable overrides the record, and the report says
664/// so by naming the variable rather than the recorded path.
665#[must_use]
666pub fn docs_scratch_location(recorded: Option<&Utf8Path>, env: &UserEnv) -> ProjectLocation {
667    if env.docs_scratch.is_some() {
668        return ProjectLocation::Env {
669            variable: DOCS_SCRATCH_VAR,
670            value: env.docs_scratch.clone(),
671        };
672    }
673    let Some(path) = recorded else {
674        return ProjectLocation::None;
675    };
676    if path.is_absolute() || path.starts_with("..") {
677        return ProjectLocation::External {
678            path: path.to_owned(),
679            source: PathSource::Recorded,
680        };
681    }
682    ProjectLocation::Untracked {
683        path: path.to_owned(),
684        source: PathSource::Recorded,
685    }
686}
687
688/// The directories a target already carries that a docs scratch could be.
689///
690/// Read from the target rather than declared, because a repository that
691/// already stages material somewhere has answered the question and the
692/// operator only has to confirm it.
693pub const DOCS_SCRATCH_LEAVES: &[&str] = &[".docs-scratch", ".scratch"];
694
695/// What this target offers for the docs scratch.
696///
697/// `held` answers whether the target carries a repository-relative
698/// directory, so the pure derivation stays testable and the caller owns the
699/// one filesystem read.
700pub fn proposals(env: &UserEnv, held: impl Fn(&Utf8Path) -> bool) -> Proposals {
701    let mut docs_scratch: Vec<LocationChoice> = Vec::new();
702    for leaf in DOCS_SCRATCH_LEAVES {
703        let candidate = Utf8PathBuf::from(*leaf);
704        if held(&candidate) {
705            docs_scratch.push(LocationChoice::Observed { path: candidate });
706        }
707    }
708    docs_scratch.push(LocationChoice::Env {
709        variable: DOCS_SCRATCH_VAR,
710        value: env.docs_scratch.clone(),
711    });
712    docs_scratch.push(LocationChoice::Operator);
713    docs_scratch.push(LocationChoice::None);
714
715    Proposals { docs_scratch }
716}
717
718#[cfg(test)]
719mod tests {
720    use super::*;
721
722    fn env(home: &str) -> UserEnv {
723        UserEnv {
724            home: Some(Utf8PathBuf::from(home)),
725            ..UserEnv::default()
726        }
727    }
728
729    #[test]
730    fn the_agent_root_table_has_two_rows_and_resolves_each_with_its_source() {
731        assert_eq!(AGENT_ROOTS.len(), 2);
732        let resolved = env("/h").agent_roots(&[AgentId::Claude, AgentId::Agents]);
733        assert_eq!(resolved.len(), 2);
734        assert_eq!(resolved[0].path, "/h/.claude/skills");
735        assert_eq!(resolved[0].source, PathSource::Default);
736        assert_eq!(resolved[0].variable, None);
737        assert_eq!(resolved[1].path, "/h/.agents/skills");
738        assert_eq!(resolved[1].id, AgentId::Agents);
739    }
740
741    #[test]
742    fn claude_config_dir_relocates_the_claude_root_and_nothing_else() {
743        let moved = UserEnv {
744            claude_config_dir: Some(Utf8PathBuf::from("/elsewhere/claude")),
745            ..env("/h")
746        };
747        let resolved = moved.agent_roots(&[AgentId::Claude, AgentId::Agents]);
748        assert_eq!(resolved[0].path, "/elsewhere/claude/skills");
749        assert_eq!(resolved[0].source, PathSource::Env);
750        assert_eq!(resolved[0].variable, Some(CLAUDE_CONFIG_DIR_VAR));
751        assert_eq!(resolved[1].path, "/h/.agents/skills");
752        assert_eq!(resolved[1].source, PathSource::Default);
753    }
754
755    #[test]
756    fn an_empty_claude_config_dir_is_treated_as_unset() {
757        // `variable` is what strips it, so the resolver never sees a blank.
758        let blank = UserEnv {
759            claude_config_dir: None,
760            ..env("/h")
761        };
762        assert_eq!(
763            blank.agent_root(AgentId::Claude).map(|root| root.path),
764            Some(Utf8PathBuf::from("/h/.claude/skills"))
765        );
766    }
767
768    #[test]
769    fn two_selected_roots_that_resolve_to_one_path_are_returned_once() {
770        let collided = UserEnv {
771            claude_config_dir: Some(Utf8PathBuf::from("/h/.agents")),
772            ..env("/h")
773        };
774        let resolved = collided.agent_roots(&[AgentId::Claude, AgentId::Agents]);
775        assert_eq!(resolved.len(), 1);
776        assert_eq!(resolved[0].path, "/h/.agents/skills");
777        assert_eq!(resolved[0].id, AgentId::Claude);
778    }
779
780    #[test]
781    fn the_cache_root_follows_xdg_cache_home_and_its_default() {
782        assert_eq!(
783            env("/h").cache_root(),
784            Some(PathEntry::default_at("/h/.cache/spec-driven-docs"))
785        );
786        let moved = UserEnv {
787            xdg_cache_home: Some(Utf8PathBuf::from("/c")),
788            ..env("/h")
789        };
790        assert_eq!(
791            moved.cache_root(),
792            Some(PathEntry::from_env("/c/spec-driven-docs"))
793        );
794    }
795
796    #[test]
797    fn the_state_root_follows_xdg_state_home_and_its_default() {
798        assert_eq!(
799            env("/h").state_root(),
800            Some(PathEntry::default_at("/h/.local/state/spec-driven-docs"))
801        );
802        let moved = UserEnv {
803            xdg_state_home: Some(Utf8PathBuf::from("/s")),
804            ..env("/h")
805        };
806        assert_eq!(
807            moved.state_root(),
808            Some(PathEntry::from_env("/s/spec-driven-docs"))
809        );
810        assert_eq!(
811            moved.legacy_state_root(),
812            Some(Utf8PathBuf::from("/h/.local/state/spec-driven-docs"))
813        );
814    }
815
816    #[test]
817    fn the_user_paths_hang_off_the_two_roots() {
818        let paths = env("/h").user_paths().unwrap();
819        assert_eq!(
820            paths.skill_receipt.unwrap().path,
821            "/h/.local/state/spec-driven-docs/skills.json"
822        );
823    }
824
825    #[test]
826    fn the_home_relative_constants_agree_with_the_resolved_roots() {
827        let paths = env("/h").user_paths().unwrap();
828        assert_eq!(
829            paths.skill_receipt.unwrap().path,
830            Utf8Path::new("/h").join(LEGACY_SKILL_RECEIPT_PATH)
831        );
832    }
833
834    #[test]
835    fn a_candidate_set_exists_for_every_profile() {
836        let candidates = candidates();
837        assert_eq!(candidates.len(), 2);
838        assert_eq!(candidates["codebase"].destinations.specs.path, "docs/specs");
839        assert_eq!(
840            candidates["knowledge-base"].destinations.specs.path,
841            "_docs/specs"
842        );
843        assert_eq!(
844            candidates["codebase"].destinations.declaration.source,
845            PathSource::Default
846        );
847        assert_eq!(
848            candidates["codebase"].destinations.specs.source,
849            PathSource::Profile
850        );
851    }
852
853    #[test]
854    fn a_recorded_location_reports_as_recorded_and_an_override_as_env() {
855        let overridden = UserEnv {
856            docs_scratch: Some("elsewhere".to_string()),
857            ..env("/h")
858        };
859        assert_eq!(
860            docs_scratch_location(Some(Utf8Path::new(".docs-scratch")), &overridden),
861            ProjectLocation::Env {
862                variable: DOCS_SCRATCH_VAR,
863                value: Some("elsewhere".to_string()),
864            }
865        );
866    }
867
868    #[test]
869    fn a_scratch_beside_the_checkout_reports_as_external() {
870        let plain = env("/h");
871        assert_eq!(
872            docs_scratch_location(Some(Utf8Path::new("../x.docs-scratch")), &plain),
873            ProjectLocation::External {
874                path: Utf8PathBuf::from("../x.docs-scratch"),
875                source: PathSource::Recorded,
876            }
877        );
878        assert_eq!(
879            docs_scratch_location(Some(Utf8Path::new(".docs-scratch")), &plain),
880            ProjectLocation::Untracked {
881                path: Utf8PathBuf::from(".docs-scratch"),
882                source: PathSource::Recorded,
883            }
884        );
885        assert_eq!(docs_scratch_location(None, &plain), ProjectLocation::None);
886    }
887
888    #[test]
889    fn a_proposal_carries_a_path_only_where_the_target_holds_one() {
890        let plain = env("/h");
891        let bare = proposals(&plain, |_| false);
892        assert!(
893            !bare
894                .docs_scratch
895                .iter()
896                .any(|choice| matches!(choice, LocationChoice::Observed { .. }))
897        );
898        assert_eq!(bare.docs_scratch.last(), Some(&LocationChoice::None));
899
900        let observed = proposals(&plain, |path| path == Utf8Path::new(".docs-scratch"));
901        assert_eq!(
902            observed.docs_scratch.first(),
903            Some(&LocationChoice::Observed {
904                path: Utf8PathBuf::from(".docs-scratch")
905            })
906        );
907    }
908}