1use std::collections::BTreeMap;
16
17use camino::{Utf8Path, Utf8PathBuf};
18use serde::Serialize;
19
20use crate::domain::markdownlint;
21use crate::domain::profile::{DocsRoot, ProfileId};
22
23pub const HOME_VAR: &str = "HOME";
25pub const CLAUDE_CONFIG_DIR_VAR: &str = "CLAUDE_CONFIG_DIR";
27pub const XDG_STATE_HOME_VAR: &str = "XDG_STATE_HOME";
29pub const XDG_CACHE_HOME_VAR: &str = "XDG_CACHE_HOME";
31pub const OFFLINE_VAR: &str = "SDD_OFFLINE";
33pub const DOCS_SCRATCH_VAR: &str = "SDD_DOCS_SCRATCH";
35pub const SELF_DEPEND_OFF_VAR: &str = "SDD_SELF_DEPEND_OFF";
37pub const CI_VAR: &str = "CI";
40
41pub const TOOL_DIR: &str = "spec-driven-docs";
43
44pub const INSTANCE_DIR: &str = ".spec-driven-docs";
46pub const MANIFEST_PATH: &str = ".spec-driven-docs/manifest.json";
48pub const CONFIG_PATH: &str = ".spec-driven-docs/config.yaml";
50pub const DEBT_PATH: &str = ".spec-driven-docs/debt.yaml";
52pub const LEGACY_DEBT_PATH: &str = ".spec-driven-docs/chapter-size-debt.txt";
54pub const HOOKS_CONFIG_PATH: &str = ".pre-commit-config.yaml";
56pub const AGENTS_DIGEST_PATH: &str = "AGENTS.md";
58
59pub const PRUNABLE_ROOTS: &[&str] = &[".spec-driven-docs/", ".claude/skills/", ".agents/skills/"];
61
62pub const STATE_ROOT: &str = ".local/state/spec-driven-docs";
64pub const CACHE_ROOT: &str = ".cache/spec-driven-docs";
66pub const SKILL_RECEIPT_FILE: &str = "skills.json";
68pub const SKILL_FILE: &str = "SKILL.md";
70pub const SKILL_REFERENCES_DIR: &str = "references";
72
73pub const SKILL_LOCK_FILE: &str = "skills.lock";
75pub const SELF_DEPEND_STAMP_DIR: &str = "self-depend";
77pub const LEGACY_SKILL_RECEIPT_PATH: &str = ".local/state/spec-driven-docs/skills.json";
83pub const LEGACY_SHARED_ROOT: &str = ".local/state/spec-driven-docs/skills/shared";
89pub const CLAUDE_ROOT: &str = ".claude/skills";
91pub const AGENTS_ROOT: &str = ".agents/skills";
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
96#[serde(rename_all = "kebab-case")]
97pub enum AgentId {
98 Claude,
100 Agents,
102}
103
104impl AgentId {
105 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct AgentRoot {
124 pub id: AgentId,
126 pub default: &'static str,
128 pub config_env: Option<&'static str>,
130 pub relocated: &'static str,
132}
133
134const CLAUDE: AgentRoot = AgentRoot {
136 id: AgentId::Claude,
137 default: CLAUDE_ROOT,
138 config_env: Some(CLAUDE_CONFIG_DIR_VAR),
139 relocated: "skills",
140};
141
142const AGENTS: AgentRoot = AgentRoot {
144 id: AgentId::Agents,
145 default: AGENTS_ROOT,
146 config_env: None,
147 relocated: "skills",
148};
149
150pub const AGENT_ROOTS: &[AgentRoot] = &[CLAUDE, AGENTS];
157
158#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
169#[serde(rename_all = "kebab-case")]
170pub enum PathSource {
171 Recorded,
173 Default,
175 Env,
177 Profile,
179 Proposal,
181}
182
183#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
185pub struct PathEntry {
186 pub path: Utf8PathBuf,
188 pub source: PathSource,
190}
191
192impl PathEntry {
193 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
214pub struct AgentRootEntry {
215 pub id: AgentId,
217 pub path: Utf8PathBuf,
219 pub source: PathSource,
221 pub variable: Option<&'static str>,
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
232#[serde(tag = "kind", rename_all = "kebab-case")]
233pub enum ProjectLocation {
234 Tracked {
236 path: Utf8PathBuf,
238 source: PathSource,
240 },
241 Untracked {
243 path: Utf8PathBuf,
245 source: PathSource,
247 },
248 External {
250 path: Utf8PathBuf,
252 source: PathSource,
254 },
255 Env {
257 variable: &'static str,
259 value: Option<String>,
261 },
262 None,
264}
265
266#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
272#[serde(tag = "kind", rename_all = "kebab-case")]
273pub enum LocationChoice {
274 Observed {
276 path: Utf8PathBuf,
278 },
279 Env {
281 variable: &'static str,
283 value: Option<String>,
285 },
286 Operator,
288 None,
290}
291
292#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
294pub struct Proposals {
295 pub docs_scratch: Vec<LocationChoice>,
297}
298
299#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
301pub struct UserPaths {
302 pub state_root: PathEntry,
304 pub cache_root: PathEntry,
306 pub skill_receipt: PathEntry,
308 pub agent_roots: Vec<AgentRootEntry>,
310}
311
312#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
314pub struct InstancePaths {
315 pub instance_dir: PathEntry,
317 pub manifest: PathEntry,
319 pub declaration: PathEntry,
321 pub debt: PathEntry,
323 pub legacy_debt: PathEntry,
325 pub hooks_config: PathEntry,
327 pub agents_digest: PathEntry,
329 pub docs_root: PathEntry,
331 pub specs: PathEntry,
333 pub decisions: PathEntry,
335 pub reference: PathEntry,
337 pub guides: PathEntry,
339 pub lint_config: PathEntry,
342 pub lint_discovery: LintDiscovery,
345}
346
347#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
353pub struct LintDiscovery {
354 pub repository_root: Vec<PathEntry>,
358 pub refused_at_docs_root: Vec<PathEntry>,
361 pub refused_beneath: Vec<PathEntry>,
364}
365
366#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
368pub struct ActivePaths {
369 pub profile: ProfileId,
371 pub destinations: InstancePaths,
373 pub docs_scratch: ProjectLocation,
375}
376
377#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
379pub struct CandidatePaths {
380 pub profile: ProfileId,
382 pub destinations: InstancePaths,
384}
385
386#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
388pub struct Paths {
389 pub user: Option<UserPaths>,
392 pub active: Option<ActivePaths>,
394 pub candidates: BTreeMap<String, CandidatePaths>,
396 pub proposals: Proposals,
398}
399
400#[derive(Debug, Clone, Default, PartialEq, Eq)]
402pub struct UserEnv {
403 pub home: Option<Utf8PathBuf>,
405 pub claude_config_dir: Option<Utf8PathBuf>,
407 pub xdg_state_home: Option<Utf8PathBuf>,
409 pub xdg_cache_home: Option<Utf8PathBuf>,
411 pub docs_scratch: Option<String>,
413}
414
415#[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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#[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#[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#[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#[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
643pub const DOCS_SCRATCH_LEAVES: &[&str] = &[".docs-scratch", ".scratch"];
649
650pub 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 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}