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