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 LINT_PROVE_RUNNER_VAR: &str = "SDD_LINT_PROVE_RUNNER";
40pub const CI_VAR: &str = "CI";
43
44pub const TOOL_DIR: &str = "spec-driven-docs";
46
47pub const INSTANCE_DIR: &str = ".spec-driven-docs";
49pub const MANIFEST_PATH: &str = ".spec-driven-docs/manifest.json";
51pub const CONFIG_PATH: &str = ".spec-driven-docs/config.yaml";
53pub const DEBT_PATH: &str = ".spec-driven-docs/debt.yaml";
55pub const LEGACY_DEBT_PATH: &str = ".spec-driven-docs/chapter-size-debt.txt";
57pub const HOOKS_CONFIG_PATH: &str = ".pre-commit-config.yaml";
59pub const AGENTS_DIGEST_PATH: &str = "AGENTS.md";
61
62pub const PRUNABLE_ROOTS: &[&str] = &[".spec-driven-docs/", ".claude/skills/", ".agents/skills/"];
64
65pub const STATE_ROOT: &str = ".local/state/spec-driven-docs";
67pub const CACHE_ROOT: &str = ".cache/spec-driven-docs";
69pub const SKILL_RECEIPT_FILE: &str = "skills.json";
71pub const SKILL_FILE: &str = "SKILL.md";
73pub const SKILL_REFERENCES_DIR: &str = "references";
75
76pub const SKILL_LOCK_FILE: &str = "skills.lock";
78pub const SELF_DEPEND_STAMP_DIR: &str = "self-depend";
80pub const LEGACY_SKILL_RECEIPT_PATH: &str = ".local/state/spec-driven-docs/skills.json";
86pub const LEGACY_SHARED_ROOT: &str = ".local/state/spec-driven-docs/skills/shared";
92pub const CLAUDE_ROOT: &str = ".claude/skills";
94pub const AGENTS_ROOT: &str = ".agents/skills";
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
99#[serde(rename_all = "kebab-case")]
100pub enum AgentId {
101 Claude,
103 Agents,
105}
106
107impl AgentId {
108 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub struct AgentRoot {
127 pub id: AgentId,
129 pub default: &'static str,
131 pub config_env: Option<&'static str>,
133 pub relocated: &'static str,
135}
136
137const CLAUDE: AgentRoot = AgentRoot {
139 id: AgentId::Claude,
140 default: CLAUDE_ROOT,
141 config_env: Some(CLAUDE_CONFIG_DIR_VAR),
142 relocated: "skills",
143};
144
145const AGENTS: AgentRoot = AgentRoot {
147 id: AgentId::Agents,
148 default: AGENTS_ROOT,
149 config_env: None,
150 relocated: "skills",
151};
152
153pub const AGENT_ROOTS: &[AgentRoot] = &[CLAUDE, AGENTS];
160
161#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
172#[serde(rename_all = "kebab-case")]
173pub enum PathSource {
174 Recorded,
176 Default,
178 Env,
180 Profile,
182 Proposal,
184}
185
186#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
188pub struct PathEntry {
189 pub path: Utf8PathBuf,
191 pub source: PathSource,
193}
194
195impl PathEntry {
196 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
217pub struct AgentRootEntry {
218 pub id: AgentId,
220 pub path: Utf8PathBuf,
222 pub source: PathSource,
224 pub variable: Option<&'static str>,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
235#[serde(tag = "kind", rename_all = "kebab-case")]
236pub enum ProjectLocation {
237 Tracked {
239 path: Utf8PathBuf,
241 source: PathSource,
243 },
244 Untracked {
246 path: Utf8PathBuf,
248 source: PathSource,
250 },
251 External {
253 path: Utf8PathBuf,
255 source: PathSource,
257 },
258 Env {
260 variable: &'static str,
262 value: Option<String>,
264 },
265 None,
267}
268
269#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
275#[serde(tag = "kind", rename_all = "kebab-case")]
276pub enum LocationChoice {
277 Observed {
279 path: Utf8PathBuf,
281 },
282 Env {
284 variable: &'static str,
286 value: Option<String>,
288 },
289 Operator,
291 None,
293}
294
295#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
297pub struct Proposals {
298 pub docs_scratch: Vec<LocationChoice>,
300}
301
302#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
304pub struct UserPaths {
305 pub state_root: PathEntry,
307 pub cache_root: PathEntry,
309 pub skill_receipt: PathEntry,
311 pub agent_roots: Vec<AgentRootEntry>,
313}
314
315#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
317pub struct InstancePaths {
318 pub instance_dir: PathEntry,
320 pub manifest: PathEntry,
322 pub declaration: PathEntry,
324 pub debt: PathEntry,
326 pub legacy_debt: PathEntry,
328 pub hooks_config: PathEntry,
330 pub agents_digest: PathEntry,
332 pub docs_root: PathEntry,
334 pub specs: PathEntry,
336 pub decisions: PathEntry,
338 pub reference: PathEntry,
340 pub guides: PathEntry,
342 pub lint_config: PathEntry,
345 pub lint_discovery: LintDiscovery,
348}
349
350#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
356pub struct LintDiscovery {
357 pub repository_root: Vec<PathEntry>,
361 pub refused_at_docs_root: Vec<PathEntry>,
364 pub refused_beneath: Vec<PathEntry>,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
371pub struct ActivePaths {
372 pub profile: ProfileId,
374 pub destinations: InstancePaths,
376 pub docs_scratch: ProjectLocation,
378}
379
380#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
382pub struct CandidatePaths {
383 pub profile: ProfileId,
385 pub destinations: InstancePaths,
387}
388
389#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
391pub struct Paths {
392 pub user: Option<UserPaths>,
395 pub active: Option<ActivePaths>,
397 pub candidates: BTreeMap<String, CandidatePaths>,
399 pub proposals: Proposals,
401}
402
403#[derive(Debug, Clone, Default, PartialEq, Eq)]
405pub struct UserEnv {
406 pub home: Option<Utf8PathBuf>,
408 pub claude_config_dir: Option<Utf8PathBuf>,
410 pub xdg_state_home: Option<Utf8PathBuf>,
412 pub xdg_cache_home: Option<Utf8PathBuf>,
414 pub docs_scratch: Option<String>,
416}
417
418#[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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#[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#[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#[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#[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
646pub const DOCS_SCRATCH_LEAVES: &[&str] = &[".docs-scratch", ".scratch"];
652
653pub 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 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}