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