spec-driven-docs 0.10.2

Spec-driven documentation: current specs, immutable decision records, and executable gates kept coherent for people and coding agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! Every control path this tool names, declared once.
//!
//! Two kinds of path meet here and stay apart. A control path is this
//! tool's own: the instance directory, the declaration, the debt files, the
//! hook configuration, the agent digest, the state and cache roots, and the
//! agent skill roots. A destination is what a release projects into a
//! target, and it is versioned data rather than a constant, so it stays
//! with the projection and reaches this module only as a resolved value.
//!
//! The module is otherwise pure. It reads no filesystem. It reads the
//! process environment in exactly one place, [`UserEnv::from_process`], so
//! every resolver below takes the environment as an argument and a test
//! constructs one instead of mutating the process.

use std::collections::BTreeMap;

use camino::{Utf8Path, Utf8PathBuf};
use serde::Serialize;

use crate::domain::manifest::PlanZone;
use crate::domain::profile::{DocsRoot, ProfileId};

/// The variable naming the invoking user's home directory.
pub const HOME_VAR: &str = "HOME";
/// The variable relocating Claude Code's whole configuration directory.
pub const CLAUDE_CONFIG_DIR_VAR: &str = "CLAUDE_CONFIG_DIR";
/// The variable naming the XDG state base directory.
pub const XDG_STATE_HOME_VAR: &str = "XDG_STATE_HOME";
/// The variable naming the XDG cache base directory.
pub const XDG_CACHE_HOME_VAR: &str = "XDG_CACHE_HOME";
/// The variable that tells this tool to reach no network.
pub const OFFLINE_VAR: &str = "SDD_OFFLINE";
/// The variable that names the plan zone.
pub const PLAN_ZONE_VAR: &str = "SDD_PLAN_ZONE";
/// The variable that names the docs scratch.
pub const DOCS_SCRATCH_VAR: &str = "SDD_DOCS_SCRATCH";

/// This tool's directory name under a base directory.
pub const TOOL_DIR: &str = "spec-driven-docs";

/// The instance directory, relative to the instance root.
pub const INSTANCE_DIR: &str = ".spec-driven-docs";
/// The manifest path, relative to the instance root.
pub const MANIFEST_PATH: &str = ".spec-driven-docs/manifest.json";
/// Where an instance keeps its declaration.
pub const CONFIG_PATH: &str = ".spec-driven-docs/config.yaml";
/// Where an instance keeps its debt.
pub const DEBT_PATH: &str = ".spec-driven-docs/debt.yaml";
/// The flat list of exempt chapters an older instance carries.
pub const LEGACY_DEBT_PATH: &str = ".spec-driven-docs/chapter-size-debt.txt";
/// Where a pre-commit configuration lives in a target.
pub const HOOKS_CONFIG_PATH: &str = ".pre-commit-config.yaml";
/// Where the documentation block lives in a target.
pub const AGENTS_DIGEST_PATH: &str = "AGENTS.md";

/// The only roots an upgrade may remove dropped managed files from.
pub const PRUNABLE_ROOTS: &[&str] = &[".spec-driven-docs/", ".claude/skills/", ".agents/skills/"];

/// The state root, relative to the home directory, where no variable moves it.
pub const STATE_ROOT: &str = ".local/state/spec-driven-docs";
/// The cache root, relative to the home directory, where no variable moves it.
pub const CACHE_ROOT: &str = ".cache/spec-driven-docs";
/// The user-scope skill receipt, relative to the state root.
pub const SKILL_RECEIPT_FILE: &str = "skills.json";
/// The one file every skill package must carry.
pub const SKILL_FILE: &str = "SKILL.md";
/// Where a skill package holds what the shared source materialized into it.
pub const SKILL_REFERENCES_DIR: &str = "references";

/// The user-scope lock, relative to the state root.
pub const SKILL_LOCK_FILE: &str = "skills.lock";
/// The user-scope journal, relative to the state root.
pub const SKILL_JOURNAL_FILE: &str = "skills.journal";
/// Where a transaction copies what it is about to replace.
pub const BACKUPS_DIR: &str = "backups";
/// The plan store, relative to the state root.
pub const PLAN_STORE_DIR: &str = "plans";
/// The verified release bundles, relative to the cache root.
pub const BUNDLE_CACHE_DIR: &str = "bundles";

/// The user-scope skill receipt at the home-relative path, read once.
///
/// A home installed before the state root followed `XDG_STATE_HOME` holds
/// its receipt here. The next apply reads it, then writes only the resolved
/// path.
pub const LEGACY_SKILL_RECEIPT_PATH: &str = ".local/state/spec-driven-docs/skills.json";
/// The retired root that once held what every skill shares.
///
/// A skill package now carries its own copy under `references/`, so this
/// root is swept rather than written. A file there the receipt vouches for
/// is the tool's and goes; anything else is the user's and stays.
pub const LEGACY_SHARED_ROOT: &str = ".local/state/spec-driven-docs/skills/shared";
/// The skill root Claude Code reads, relative to the home directory.
pub const CLAUDE_ROOT: &str = ".claude/skills";
/// The skill root every other agent reads, relative to the home directory.
pub const AGENTS_ROOT: &str = ".agents/skills";

/// Which agent family a skill root serves.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum AgentId {
    /// Claude Code, which reads its own configuration directory.
    Claude,
    /// The shared root Codex, `OpenCode`, and Pi each document that they read.
    Agents,
}

impl AgentId {
    /// The kebab-case name used on the command line and in the report.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Claude => "claude",
            Self::Agents => "agents",
        }
    }
}

impl std::fmt::Display for AgentId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One agent skill root, and what relocates it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AgentRoot {
    /// The family this root serves.
    pub id: AgentId,
    /// The root, relative to the home directory, where no variable moves it.
    pub default: &'static str,
    /// The variable relocating the agent's whole configuration directory.
    pub config_env: Option<&'static str>,
    /// The root, relative to that variable's value.
    pub relocated: &'static str,
}

/// The root Claude Code reads, and the variable that relocates it.
const CLAUDE: AgentRoot = AgentRoot {
    id: AgentId::Claude,
    default: CLAUDE_ROOT,
    config_env: Some(CLAUDE_CONFIG_DIR_VAR),
    relocated: "skills",
};

/// The root every other agent reads. No variable relocates it.
const AGENTS: AgentRoot = AgentRoot {
    id: AgentId::Agents,
    default: AGENTS_ROOT,
    config_env: None,
    relocated: "skills",
};

/// Every agent skill root this tool writes, in report order.
///
/// Two rows, and no third. Codex, `OpenCode`, and Pi each document that they
/// read the shared root, checked 2026-09-12, so a row per host would be
/// three names for one directory. A host with a root of its own is one more
/// row and one more test on the day it needs one.
pub const AGENT_ROOTS: &[AgentRoot] = &[CLAUDE, AGENTS];

/// The agent root one identifier names.
#[must_use]
pub const fn agent_root(id: AgentId) -> &'static AgentRoot {
    match id {
        AgentId::Claude => &CLAUDE,
        AgentId::Agents => &AGENTS,
    }
}

/// What decided a path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum PathSource {
    /// The instance manifest records it.
    Recorded,
    /// Nothing moved it, so it is the declared default.
    Default,
    /// A variable carries it.
    Env,
    /// The profile's documentation root derives it.
    Profile,
    /// The target's own shape suggests it, and nothing recorded it.
    Proposal,
}

/// One resolved path, and what decided it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PathEntry {
    /// The resolved path.
    pub path: Utf8PathBuf,
    /// What decided it.
    pub source: PathSource,
}

impl PathEntry {
    /// A path nothing moved.
    #[must_use]
    pub fn default_at(path: impl Into<Utf8PathBuf>) -> Self {
        Self {
            path: path.into(),
            source: PathSource::Default,
        }
    }

    /// A path a variable carried.
    #[must_use]
    pub fn from_env(path: impl Into<Utf8PathBuf>) -> Self {
        Self {
            path: path.into(),
            source: PathSource::Env,
        }
    }
}

/// One resolved agent skill root.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AgentRootEntry {
    /// The family this root serves.
    pub id: AgentId,
    /// The absolute root.
    pub path: Utf8PathBuf,
    /// What decided it.
    pub source: PathSource,
    /// The variable that relocated it, where one did.
    pub variable: Option<&'static str>,
}

/// Where a location the project owns actually sits.
///
/// The four absent-looking cases are not one case. A repository-relative
/// directory is checkable from a fresh clone. A directory outside the
/// repository is not, and neither is one a variable resolves at run time,
/// and a project that keeps none promises nothing at all.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ProjectLocation {
    /// A repository-relative directory under version control.
    Tracked {
        /// Where it sits, relative to the instance root.
        path: Utf8PathBuf,
        /// What decided it.
        source: PathSource,
    },
    /// A repository-relative directory version control does not carry.
    Untracked {
        /// Where it sits, relative to the instance root.
        path: Utf8PathBuf,
        /// What decided it.
        source: PathSource,
    },
    /// A directory outside the repository.
    External {
        /// Where it sits, as the record carries it.
        path: Utf8PathBuf,
        /// What decided it.
        source: PathSource,
    },
    /// Wherever a variable resolves at run time.
    Env {
        /// The variable that carries it.
        variable: &'static str,
        /// What that variable carries here, when it is set.
        value: Option<String>,
    },
    /// The project keeps none.
    None,
}

/// One answer the operator can give for a location the project owns.
///
/// A choice carries a path only where the target already holds that
/// directory. Inventing one would put a path this tool made up in front of
/// an operator as though the repository had suggested it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum LocationChoice {
    /// A repository-relative directory the target already carries.
    Observed {
        /// Where it sits, relative to the target root.
        path: Utf8PathBuf,
    },
    /// Wherever a variable resolves at run time.
    Env {
        /// The variable that would carry it.
        variable: &'static str,
        /// What that variable carries here, when it is set.
        value: Option<String>,
    },
    /// A path the operator types.
    Operator,
    /// The project keeps none.
    None,
}

/// The choices this target offers for the two locations it owns.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Proposals {
    /// What the plan zone can be here.
    pub plan_zone: Vec<LocationChoice>,
    /// What the docs scratch can be here.
    pub docs_scratch: Vec<LocationChoice>,
}

/// Every user-scope path, resolved.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct UserPaths {
    /// Where this tool keeps state that outlives a command.
    pub state_root: PathEntry,
    /// Where this tool keeps what it can fetch again.
    pub cache_root: PathEntry,
    /// The receipt vouching for every user-scope file this tool wrote.
    pub skill_receipt: PathEntry,
    /// Where computed plans are stored.
    pub plan_store: PathEntry,
    /// Where verified release bundles are cached.
    pub bundle_cache: PathEntry,
    /// The agent skill roots, deduplicated by resolved path.
    pub agent_roots: Vec<AgentRootEntry>,
}

/// Every control and documentation destination inside one target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstancePaths {
    /// The instance directory.
    pub instance_dir: PathEntry,
    /// The instance manifest.
    pub manifest: PathEntry,
    /// What the project declares about the files its gates judge.
    pub declaration: PathEntry,
    /// The inherited violations the budget gates read.
    pub debt: PathEntry,
    /// The flat list an instance older than the debt file carries.
    pub legacy_debt: PathEntry,
    /// The pre-commit configuration carrying the managed block.
    pub hooks_config: PathEntry,
    /// The root agent digest carrying the documentation block.
    pub agents_digest: PathEntry,
    /// The documentation root.
    pub docs_root: PathEntry,
    /// Where the specifications sit.
    pub specs: PathEntry,
    /// Where the decision records sit.
    pub decisions: PathEntry,
    /// Where the reference material sits.
    pub reference: PathEntry,
    /// Where the step-by-step guides sit.
    pub guides: PathEntry,
}

/// One landed instance's paths, as the record and the environment leave them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ActivePaths {
    /// The recorded profile.
    pub profile: ProfileId,
    /// Every destination the record implies.
    pub destinations: InstancePaths,
    /// Where the planning tool writes its entry documents.
    pub plan_zone: ProjectLocation,
    /// Where material that is not a statement yet is staged.
    pub docs_scratch: ProjectLocation,
}

/// One profile's destinations, derived and recorded nowhere.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CandidatePaths {
    /// The profile these destinations belong to.
    pub profile: ProfileId,
    /// Every destination that profile implies.
    pub destinations: InstancePaths,
}

/// Every path this binary can name for one target and one user.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Paths {
    /// What resolves under the invoking user's home directory, or `null`
    /// where the home variable is unset and nothing under it resolves.
    pub user: Option<UserPaths>,
    /// What the target records, or `null` where it carries no instance.
    pub active: Option<ActivePaths>,
    /// What each profile would imply, whether or not one is recorded.
    pub candidates: BTreeMap<String, CandidatePaths>,
    /// What this target offers for the two locations the project owns.
    pub proposals: Proposals,
}

/// What the process environment carries, read once and passed down.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UserEnv {
    /// The invoking user's home directory.
    pub home: Option<Utf8PathBuf>,
    /// Where Claude Code's configuration directory was moved to.
    pub claude_config_dir: Option<Utf8PathBuf>,
    /// The XDG state base directory.
    pub xdg_state_home: Option<Utf8PathBuf>,
    /// The XDG cache base directory.
    pub xdg_cache_home: Option<Utf8PathBuf>,
    /// What the plan-zone variable carries.
    pub plan_zone: Option<String>,
    /// What the docs-scratch variable carries.
    pub docs_scratch: Option<String>,
}

/// What one variable carries, or `None` where it is unset or blank.
///
/// A variable set to the empty string is a variable the shell exported and
/// nothing filled in. Treating it as a path would resolve every root to the
/// filesystem root.
#[must_use]
pub fn variable(name: &str) -> Option<String> {
    std::env::var(name)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

impl UserEnv {
    /// Read every variable this module resolves from, once.
    #[must_use]
    pub fn from_process() -> Self {
        let path = |name: &str| variable(name).map(Utf8PathBuf::from);
        Self {
            home: path(HOME_VAR),
            claude_config_dir: path(CLAUDE_CONFIG_DIR_VAR),
            xdg_state_home: path(XDG_STATE_HOME_VAR),
            xdg_cache_home: path(XDG_CACHE_HOME_VAR),
            plan_zone: variable(PLAN_ZONE_VAR),
            docs_scratch: variable(DOCS_SCRATCH_VAR),
        }
    }

    /// The state root, through the XDG variable or its default.
    #[must_use]
    pub fn state_root(&self) -> Option<PathEntry> {
        if let Some(base) = self.xdg_state_home.as_ref() {
            return Some(PathEntry::from_env(base.join(TOOL_DIR)));
        }
        self.home
            .as_ref()
            .map(|home| PathEntry::default_at(home.join(STATE_ROOT)))
    }

    /// The home-relative state root, whatever the variable says.
    ///
    /// One fallback read lives here: a receipt written before the state root
    /// followed `XDG_STATE_HOME`, and the two gate files that release left
    /// under the retired shared root.
    #[must_use]
    pub fn legacy_state_root(&self) -> Option<Utf8PathBuf> {
        self.home.as_ref().map(|home| home.join(STATE_ROOT))
    }

    /// The cache root, through the XDG variable or its default.
    #[must_use]
    pub fn cache_root(&self) -> Option<PathEntry> {
        if let Some(base) = self.xdg_cache_home.as_ref() {
            return Some(PathEntry::from_env(base.join(TOOL_DIR)));
        }
        self.home
            .as_ref()
            .map(|home| PathEntry::default_at(home.join(CACHE_ROOT)))
    }

    /// One agent skill root, resolved with what decided it.
    #[must_use]
    pub fn agent_root(&self, id: AgentId) -> Option<AgentRootEntry> {
        let row = agent_root(id);
        let home = self.home.as_ref()?;
        let relocated = match row.id {
            AgentId::Claude => self.claude_config_dir.as_ref(),
            AgentId::Agents => None,
        };
        Some(relocated.map_or_else(
            || AgentRootEntry {
                id: row.id,
                path: home.join(row.default),
                source: PathSource::Default,
                variable: None,
            },
            |base| AgentRootEntry {
                id: row.id,
                path: base.join(row.relocated),
                source: PathSource::Env,
                variable: row.config_env,
            },
        ))
    }

    /// Every selected agent root, in table order, deduplicated by path.
    ///
    /// Two selected roots that resolve to one directory are one destination.
    /// Planning it twice would list every file twice and make an install
    /// compare a write against itself.
    #[must_use]
    pub fn agent_roots(&self, selected: &[AgentId]) -> Vec<AgentRootEntry> {
        let mut resolved: Vec<AgentRootEntry> = Vec::new();
        for row in AGENT_ROOTS {
            if !selected.contains(&row.id) {
                continue;
            }
            let Some(entry) = self.agent_root(row.id) else {
                continue;
            };
            if resolved.iter().any(|held| held.path == entry.path) {
                continue;
            }
            resolved.push(entry);
        }
        resolved
    }

    /// Every user-scope path, with every agent root selected.
    #[must_use]
    pub fn user_paths(&self) -> Option<UserPaths> {
        let state = self.state_root()?;
        let cache = self.cache_root()?;
        Some(UserPaths {
            skill_receipt: PathEntry {
                path: state.path.join(SKILL_RECEIPT_FILE),
                source: state.source,
            },
            plan_store: PathEntry {
                path: state.path.join(PLAN_STORE_DIR),
                source: state.source,
            },
            bundle_cache: PathEntry {
                path: cache.path.join(BUNDLE_CACHE_DIR),
                source: cache.source,
            },
            agent_roots: self.agent_roots(&[AgentId::Claude, AgentId::Agents]),
            state_root: state,
            cache_root: cache,
        })
    }
}

/// Every destination one documentation root implies.
#[must_use]
pub fn instance_paths(docs_root: DocsRoot) -> InstancePaths {
    let docs = Utf8PathBuf::from(docs_root.as_str());
    let under = |leaf: &str| PathEntry {
        path: docs.join(leaf),
        source: PathSource::Profile,
    };
    InstancePaths {
        instance_dir: PathEntry::default_at(INSTANCE_DIR),
        manifest: PathEntry::default_at(MANIFEST_PATH),
        declaration: PathEntry::default_at(CONFIG_PATH),
        debt: PathEntry::default_at(DEBT_PATH),
        legacy_debt: PathEntry::default_at(LEGACY_DEBT_PATH),
        hooks_config: PathEntry::default_at(HOOKS_CONFIG_PATH),
        agents_digest: PathEntry::default_at(AGENTS_DIGEST_PATH),
        docs_root: PathEntry {
            path: docs.clone(),
            source: PathSource::Profile,
        },
        specs: under("specs"),
        decisions: under("decisions"),
        reference: under("reference"),
        guides: under("guides"),
    }
}

/// The same destinations, marked as the record's rather than a profile's.
#[must_use]
pub fn recorded_paths(docs_root: DocsRoot) -> InstancePaths {
    let mut paths = instance_paths(docs_root);
    for entry in [
        &mut paths.docs_root,
        &mut paths.specs,
        &mut paths.decisions,
        &mut paths.reference,
        &mut paths.guides,
    ] {
        entry.source = PathSource::Recorded;
    }
    paths
}

/// One profile's derived destinations, per profile, keyed by its name.
#[must_use]
pub fn candidates() -> BTreeMap<String, CandidatePaths> {
    ProfileId::every()
        .map(|profile| {
            (
                profile.as_str().to_string(),
                CandidatePaths {
                    profile,
                    destinations: instance_paths(profile.profile().docs_root),
                },
            )
        })
        .collect()
}

/// Where the record says the plan zone sits.
#[must_use]
pub fn plan_zone_location(zone: &PlanZone, env: &UserEnv) -> ProjectLocation {
    match zone {
        PlanZone::Tracked { path } => ProjectLocation::Tracked {
            path: path.clone(),
            source: PathSource::Recorded,
        },
        PlanZone::Untracked { path } => ProjectLocation::Untracked {
            path: path.clone(),
            source: PathSource::Recorded,
        },
        PlanZone::Env => ProjectLocation::Env {
            variable: PLAN_ZONE_VAR,
            value: env.plan_zone.clone(),
        },
        PlanZone::None => ProjectLocation::None,
    }
}

/// Where the record says the docs scratch sits.
///
/// A recorded scratch may leave the repository, because staging beside the
/// checkout is one of the offered answers, so the leading component decides
/// which kind it is. The variable overrides the record, and the report says
/// so by naming the variable rather than the recorded path.
#[must_use]
pub fn docs_scratch_location(recorded: Option<&Utf8Path>, env: &UserEnv) -> ProjectLocation {
    if env.docs_scratch.is_some() {
        return ProjectLocation::Env {
            variable: DOCS_SCRATCH_VAR,
            value: env.docs_scratch.clone(),
        };
    }
    let Some(path) = recorded else {
        return ProjectLocation::None;
    };
    if path.is_absolute() || path.starts_with("..") {
        return ProjectLocation::External {
            path: path.to_owned(),
            source: PathSource::Recorded,
        };
    }
    ProjectLocation::Untracked {
        path: path.to_owned(),
        source: PathSource::Recorded,
    }
}

/// The directories a target already carries that a plan zone could be.
///
/// Read from the target rather than declared, because a repository that
/// already writes plans somewhere has answered the question and the
/// operator only has to confirm it.
pub const PLAN_ZONE_LEAVES: &[&str] = &["plan", "plans"];

/// The directories a target already carries that a docs scratch could be.
pub const DOCS_SCRATCH_LEAVES: &[&str] = &[".docs-scratch", ".scratch"];

/// What this target offers for the two locations the project owns.
///
/// `held` answers whether the target carries a repository-relative
/// directory, so the pure derivation stays testable and the caller owns the
/// one filesystem read.
pub fn proposals(env: &UserEnv, held: impl Fn(&Utf8Path) -> bool) -> Proposals {
    let mut plan_zone: Vec<LocationChoice> = Vec::new();
    for profile in ProfileId::every() {
        let docs = Utf8PathBuf::from(profile.profile().docs_root.as_str());
        for leaf in PLAN_ZONE_LEAVES {
            let candidate = docs.join(leaf);
            if held(&candidate) && !plan_zone.iter().any(|choice| names(choice, &candidate)) {
                plan_zone.push(LocationChoice::Observed { path: candidate });
            }
        }
    }
    plan_zone.push(LocationChoice::Env {
        variable: PLAN_ZONE_VAR,
        value: env.plan_zone.clone(),
    });
    plan_zone.push(LocationChoice::Operator);
    plan_zone.push(LocationChoice::None);

    let mut docs_scratch: Vec<LocationChoice> = Vec::new();
    for leaf in DOCS_SCRATCH_LEAVES {
        let candidate = Utf8PathBuf::from(*leaf);
        if held(&candidate) {
            docs_scratch.push(LocationChoice::Observed { path: candidate });
        }
    }
    docs_scratch.push(LocationChoice::Env {
        variable: DOCS_SCRATCH_VAR,
        value: env.docs_scratch.clone(),
    });
    docs_scratch.push(LocationChoice::Operator);
    docs_scratch.push(LocationChoice::None);

    Proposals {
        plan_zone,
        docs_scratch,
    }
}

fn names(choice: &LocationChoice, path: &Utf8Path) -> bool {
    matches!(choice, LocationChoice::Observed { path: held } if held == path)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn env(home: &str) -> UserEnv {
        UserEnv {
            home: Some(Utf8PathBuf::from(home)),
            ..UserEnv::default()
        }
    }

    #[test]
    fn the_agent_root_table_has_two_rows_and_resolves_each_with_its_source() {
        assert_eq!(AGENT_ROOTS.len(), 2);
        let resolved = env("/h").agent_roots(&[AgentId::Claude, AgentId::Agents]);
        assert_eq!(resolved.len(), 2);
        assert_eq!(resolved[0].path, "/h/.claude/skills");
        assert_eq!(resolved[0].source, PathSource::Default);
        assert_eq!(resolved[0].variable, None);
        assert_eq!(resolved[1].path, "/h/.agents/skills");
        assert_eq!(resolved[1].id, AgentId::Agents);
    }

    #[test]
    fn claude_config_dir_relocates_the_claude_root_and_nothing_else() {
        let moved = UserEnv {
            claude_config_dir: Some(Utf8PathBuf::from("/elsewhere/claude")),
            ..env("/h")
        };
        let resolved = moved.agent_roots(&[AgentId::Claude, AgentId::Agents]);
        assert_eq!(resolved[0].path, "/elsewhere/claude/skills");
        assert_eq!(resolved[0].source, PathSource::Env);
        assert_eq!(resolved[0].variable, Some(CLAUDE_CONFIG_DIR_VAR));
        assert_eq!(resolved[1].path, "/h/.agents/skills");
        assert_eq!(resolved[1].source, PathSource::Default);
    }

    #[test]
    fn an_empty_claude_config_dir_is_treated_as_unset() {
        // `variable` is what strips it, so the resolver never sees a blank.
        let blank = UserEnv {
            claude_config_dir: None,
            ..env("/h")
        };
        assert_eq!(
            blank.agent_root(AgentId::Claude).map(|root| root.path),
            Some(Utf8PathBuf::from("/h/.claude/skills"))
        );
    }

    #[test]
    fn two_selected_roots_that_resolve_to_one_path_are_returned_once() {
        let collided = UserEnv {
            claude_config_dir: Some(Utf8PathBuf::from("/h/.agents")),
            ..env("/h")
        };
        let resolved = collided.agent_roots(&[AgentId::Claude, AgentId::Agents]);
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].path, "/h/.agents/skills");
        assert_eq!(resolved[0].id, AgentId::Claude);
    }

    #[test]
    fn the_cache_root_follows_xdg_cache_home_and_its_default() {
        assert_eq!(
            env("/h").cache_root(),
            Some(PathEntry::default_at("/h/.cache/spec-driven-docs"))
        );
        let moved = UserEnv {
            xdg_cache_home: Some(Utf8PathBuf::from("/c")),
            ..env("/h")
        };
        assert_eq!(
            moved.cache_root(),
            Some(PathEntry::from_env("/c/spec-driven-docs"))
        );
    }

    #[test]
    fn the_state_root_follows_xdg_state_home_and_its_default() {
        assert_eq!(
            env("/h").state_root(),
            Some(PathEntry::default_at("/h/.local/state/spec-driven-docs"))
        );
        let moved = UserEnv {
            xdg_state_home: Some(Utf8PathBuf::from("/s")),
            ..env("/h")
        };
        assert_eq!(
            moved.state_root(),
            Some(PathEntry::from_env("/s/spec-driven-docs"))
        );
        assert_eq!(
            moved.legacy_state_root(),
            Some(Utf8PathBuf::from("/h/.local/state/spec-driven-docs"))
        );
    }

    #[test]
    fn the_user_paths_hang_off_the_two_roots() {
        let paths = env("/h").user_paths().unwrap();
        assert_eq!(
            paths.skill_receipt.path,
            "/h/.local/state/spec-driven-docs/skills.json"
        );
        assert_eq!(
            paths.plan_store.path,
            "/h/.local/state/spec-driven-docs/plans"
        );
        assert_eq!(
            paths.bundle_cache.path,
            "/h/.cache/spec-driven-docs/bundles"
        );
    }

    #[test]
    fn the_home_relative_constants_agree_with_the_resolved_roots() {
        let paths = env("/h").user_paths().unwrap();
        assert_eq!(
            paths.skill_receipt.path,
            Utf8Path::new("/h").join(LEGACY_SKILL_RECEIPT_PATH)
        );
    }

    #[test]
    fn a_candidate_set_exists_for_every_profile() {
        let candidates = candidates();
        assert_eq!(candidates.len(), 2);
        assert_eq!(candidates["codebase"].destinations.specs.path, "docs/specs");
        assert_eq!(
            candidates["knowledge-base"].destinations.specs.path,
            "_docs/specs"
        );
        assert_eq!(
            candidates["codebase"].destinations.declaration.source,
            PathSource::Default
        );
        assert_eq!(
            candidates["codebase"].destinations.specs.source,
            PathSource::Profile
        );
    }

    #[test]
    fn a_recorded_location_reports_as_recorded_and_an_override_as_env() {
        let plain = env("/h");
        assert_eq!(
            plan_zone_location(
                &PlanZone::Tracked {
                    path: Utf8PathBuf::from("docs/plan")
                },
                &plain
            ),
            ProjectLocation::Tracked {
                path: Utf8PathBuf::from("docs/plan"),
                source: PathSource::Recorded,
            }
        );
        let overridden = UserEnv {
            plan_zone: Some("elsewhere".to_string()),
            ..env("/h")
        };
        assert_eq!(
            plan_zone_location(&PlanZone::Env, &overridden),
            ProjectLocation::Env {
                variable: PLAN_ZONE_VAR,
                value: Some("elsewhere".to_string()),
            }
        );
    }

    #[test]
    fn a_scratch_beside_the_checkout_reports_as_external() {
        let plain = env("/h");
        assert_eq!(
            docs_scratch_location(Some(Utf8Path::new("../x.docs-scratch")), &plain),
            ProjectLocation::External {
                path: Utf8PathBuf::from("../x.docs-scratch"),
                source: PathSource::Recorded,
            }
        );
        assert_eq!(
            docs_scratch_location(Some(Utf8Path::new(".docs-scratch")), &plain),
            ProjectLocation::Untracked {
                path: Utf8PathBuf::from(".docs-scratch"),
                source: PathSource::Recorded,
            }
        );
        assert_eq!(docs_scratch_location(None, &plain), ProjectLocation::None);
    }

    #[test]
    fn a_proposal_carries_a_path_only_where_the_target_holds_one() {
        let plain = env("/h");
        let bare = proposals(&plain, |_| false);
        assert!(
            !bare
                .plan_zone
                .iter()
                .any(|choice| matches!(choice, LocationChoice::Observed { .. }))
        );
        assert_eq!(bare.plan_zone.last(), Some(&LocationChoice::None));

        let observed = proposals(&plain, |path| path == Utf8Path::new("docs/plan"));
        assert_eq!(
            observed.plan_zone.first(),
            Some(&LocationChoice::Observed {
                path: Utf8PathBuf::from("docs/plan")
            })
        );
    }
}