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