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";
43pub const DIRENV_IN_ENVRC_VAR: &str = "DIRENV_IN_ENVRC";
48pub const HTTP_ORIGIN_VAR: &str = "SDD_HTTP_ORIGIN";
51
52pub const TOOL_DIR: &str = "spec-driven-docs";
54
55pub const INSTANCE_DIR: &str = ".spec-driven-docs";
57pub const MANIFEST_PATH: &str = ".spec-driven-docs/manifest.json";
59pub const CONFIG_PATH: &str = ".spec-driven-docs/config.yaml";
61pub const DEBT_PATH: &str = ".spec-driven-docs/debt.yaml";
63pub const LEGACY_DEBT_PATH: &str = ".spec-driven-docs/chapter-size-debt.txt";
65pub const HOOKS_CONFIG_PATH: &str = ".pre-commit-config.yaml";
67pub const AGENTS_DIGEST_PATH: &str = "AGENTS.md";
69
70pub const PRUNABLE_ROOTS: &[&str] = &[".spec-driven-docs/", ".claude/skills/", ".agents/skills/"];
73
74pub const STATE_ROOT: &str = ".local/state/spec-driven-docs";
76pub const CACHE_ROOT: &str = ".cache/spec-driven-docs";
78pub const SKILL_RECEIPT_FILE: &str = "skills.json";
80pub const SKILL_FILE: &str = "SKILL.md";
82pub const SKILL_REFERENCES_DIR: &str = "references";
84
85pub const SKILL_LOCK_FILE: &str = "skills.lock";
87pub const SELF_DEPEND_STAMP_DIR: &str = "self-depend";
89pub const SELF_DEPEND_CACHE_DIR: &str = "self-depend";
91pub const LEGACY_SKILL_RECEIPT_PATH: &str = ".local/state/spec-driven-docs/skills.json";
97pub const LEGACY_SHARED_ROOT: &str = ".local/state/spec-driven-docs/skills/shared";
103pub const CLAUDE_ROOT: &str = ".claude/skills";
105pub const AGENTS_ROOT: &str = ".agents/skills";
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
110#[serde(rename_all = "kebab-case")]
111pub enum AgentId {
112 Claude,
114 Agents,
116}
117
118impl AgentId {
119 #[must_use]
121 pub const fn as_str(self) -> &'static str {
122 match self {
123 Self::Claude => "claude",
124 Self::Agents => "agents",
125 }
126 }
127}
128
129impl std::fmt::Display for AgentId {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 f.write_str(self.as_str())
132 }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub struct AgentRoot {
138 pub id: AgentId,
140 pub default: &'static str,
142 pub config_env: Option<&'static str>,
144 pub relocated: &'static str,
146}
147
148const CLAUDE: AgentRoot = AgentRoot {
150 id: AgentId::Claude,
151 default: CLAUDE_ROOT,
152 config_env: Some(CLAUDE_CONFIG_DIR_VAR),
153 relocated: "skills",
154};
155
156const AGENTS: AgentRoot = AgentRoot {
158 id: AgentId::Agents,
159 default: AGENTS_ROOT,
160 config_env: None,
161 relocated: "skills",
162};
163
164pub const AGENT_ROOTS: &[AgentRoot] = &[CLAUDE, AGENTS];
171
172#[must_use]
174pub const fn agent_root(id: AgentId) -> &'static AgentRoot {
175 match id {
176 AgentId::Claude => &CLAUDE,
177 AgentId::Agents => &AGENTS,
178 }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
183#[serde(rename_all = "kebab-case")]
184pub enum PathSource {
185 Recorded,
187 Default,
189 Env,
191 Profile,
193 Proposal,
195}
196
197#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
199pub struct PathEntry {
200 pub path: Utf8PathBuf,
202 pub source: PathSource,
204}
205
206impl PathEntry {
207 #[must_use]
209 pub fn default_at(path: impl Into<Utf8PathBuf>) -> Self {
210 Self {
211 path: path.into(),
212 source: PathSource::Default,
213 }
214 }
215
216 #[must_use]
218 pub fn from_env(path: impl Into<Utf8PathBuf>) -> Self {
219 Self {
220 path: path.into(),
221 source: PathSource::Env,
222 }
223 }
224}
225
226#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
228pub struct AgentRootEntry {
229 pub id: AgentId,
231 pub path: Utf8PathBuf,
233 pub source: PathSource,
235 pub variable: Option<&'static str>,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
246#[serde(tag = "kind", rename_all = "kebab-case")]
247pub enum ProjectLocation {
248 Tracked {
250 path: Utf8PathBuf,
252 source: PathSource,
254 },
255 Untracked {
257 path: Utf8PathBuf,
259 source: PathSource,
261 },
262 External {
264 path: Utf8PathBuf,
266 source: PathSource,
268 },
269 Env {
271 variable: &'static str,
273 value: Option<String>,
275 },
276 None,
278}
279
280#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
286#[serde(tag = "kind", rename_all = "kebab-case")]
287pub enum LocationChoice {
288 Observed {
290 path: Utf8PathBuf,
292 },
293 Env {
295 variable: &'static str,
297 value: Option<String>,
299 },
300 Operator,
302 None,
304}
305
306#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
308pub struct Proposals {
309 pub docs_scratch: Vec<LocationChoice>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
315pub struct UserPaths {
316 pub state_root: PathEntry,
318 pub cache_root: PathEntry,
320 #[serde(skip_serializing_if = "Option::is_none")]
323 pub skill_receipt: Option<PathEntry>,
324 #[serde(skip_serializing_if = "Vec::is_empty")]
327 pub agent_roots: Vec<AgentRootEntry>,
328}
329
330impl UserPaths {
331 #[must_use]
334 pub fn with_skill_entries_while_a_receipt_exists(mut self, legacy: Option<&Utf8Path>) -> Self {
335 let held = self
336 .skill_receipt
337 .as_ref()
338 .is_some_and(|receipt| receipt.path.is_file())
339 || legacy.is_some_and(Utf8Path::is_file);
340 if !held {
341 self.skill_receipt = None;
342 self.agent_roots.clear();
343 }
344 self
345 }
346}
347
348#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
350pub struct InstancePaths {
351 pub instance_dir: PathEntry,
353 pub manifest: PathEntry,
355 pub declaration: PathEntry,
357 pub debt: PathEntry,
359 pub legacy_debt: PathEntry,
361 pub hooks_config: PathEntry,
363 pub agents_digest: PathEntry,
365 pub docs_root: PathEntry,
367 pub specs: PathEntry,
369 pub decisions: PathEntry,
371 pub reference: PathEntry,
373 pub guides: PathEntry,
375 pub lint_config: PathEntry,
378 pub lint_discovery: LintDiscovery,
381}
382
383#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
389pub struct LintDiscovery {
390 pub repository_root: Vec<PathEntry>,
394 pub refused_at_docs_root: Vec<PathEntry>,
397 pub refused_beneath: Vec<PathEntry>,
400}
401
402#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
404pub struct ActivePaths {
405 pub profile: ProfileId,
407 pub destinations: InstancePaths,
409 pub docs_scratch: ProjectLocation,
411}
412
413#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
415pub struct CandidatePaths {
416 pub profile: ProfileId,
418 pub destinations: InstancePaths,
420}
421
422#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
424pub struct Paths {
425 pub user: Option<UserPaths>,
428 pub active: Option<ActivePaths>,
430 pub candidates: BTreeMap<String, CandidatePaths>,
432 pub proposals: Proposals,
434}
435
436#[derive(Debug, Clone, Default, PartialEq, Eq)]
438pub struct UserEnv {
439 pub home: Option<Utf8PathBuf>,
441 pub claude_config_dir: Option<Utf8PathBuf>,
443 pub xdg_state_home: Option<Utf8PathBuf>,
445 pub xdg_cache_home: Option<Utf8PathBuf>,
447 pub docs_scratch: Option<String>,
449}
450
451#[must_use]
457pub fn variable(name: &str) -> Option<String> {
458 std::env::var(name)
459 .ok()
460 .map(|value| value.trim().to_string())
461 .filter(|value| !value.is_empty())
462}
463
464impl UserEnv {
465 #[must_use]
467 pub fn from_process() -> Self {
468 let path = |name: &str| variable(name).map(Utf8PathBuf::from);
469 Self {
470 home: path(HOME_VAR),
471 claude_config_dir: path(CLAUDE_CONFIG_DIR_VAR),
472 xdg_state_home: path(XDG_STATE_HOME_VAR),
473 xdg_cache_home: path(XDG_CACHE_HOME_VAR),
474 docs_scratch: variable(DOCS_SCRATCH_VAR),
475 }
476 }
477
478 #[must_use]
480 pub fn state_root(&self) -> Option<PathEntry> {
481 if let Some(base) = self.xdg_state_home.as_ref() {
482 return Some(PathEntry::from_env(base.join(TOOL_DIR)));
483 }
484 self.home
485 .as_ref()
486 .map(|home| PathEntry::default_at(home.join(STATE_ROOT)))
487 }
488
489 #[must_use]
495 pub fn legacy_state_root(&self) -> Option<Utf8PathBuf> {
496 self.home.as_ref().map(|home| home.join(STATE_ROOT))
497 }
498
499 #[must_use]
501 pub fn cache_root(&self) -> Option<PathEntry> {
502 if let Some(base) = self.xdg_cache_home.as_ref() {
503 return Some(PathEntry::from_env(base.join(TOOL_DIR)));
504 }
505 self.home
506 .as_ref()
507 .map(|home| PathEntry::default_at(home.join(CACHE_ROOT)))
508 }
509
510 #[must_use]
512 pub fn agent_root(&self, id: AgentId) -> Option<AgentRootEntry> {
513 let row = agent_root(id);
514 let home = self.home.as_ref()?;
515 let relocated = match row.id {
516 AgentId::Claude => self.claude_config_dir.as_ref(),
517 AgentId::Agents => None,
518 };
519 Some(relocated.map_or_else(
520 || AgentRootEntry {
521 id: row.id,
522 path: home.join(row.default),
523 source: PathSource::Default,
524 variable: None,
525 },
526 |base| AgentRootEntry {
527 id: row.id,
528 path: base.join(row.relocated),
529 source: PathSource::Env,
530 variable: row.config_env,
531 },
532 ))
533 }
534
535 #[must_use]
542 pub fn agent_roots(&self, selected: &[AgentId]) -> Vec<AgentRootEntry> {
543 let mut resolved: Vec<AgentRootEntry> = Vec::new();
544 for row in AGENT_ROOTS {
545 if !selected.contains(&row.id) {
546 continue;
547 }
548 let Some(entry) = self.agent_root(row.id) else {
549 continue;
550 };
551 let reached = |path: &Utf8Path| {
554 std::fs::canonicalize(path).unwrap_or_else(|_| path.as_std_path().to_path_buf())
555 };
556 if resolved
557 .iter()
558 .any(|held| reached(&held.path) == reached(&entry.path))
559 {
560 continue;
561 }
562 resolved.push(entry);
563 }
564 resolved
565 }
566
567 #[must_use]
569 pub fn user_paths(&self) -> Option<UserPaths> {
570 let state = self.state_root()?;
571 let cache = self.cache_root()?;
572 Some(UserPaths {
573 skill_receipt: Some(PathEntry {
574 path: state.path.join(SKILL_RECEIPT_FILE),
575 source: state.source,
576 }),
577 agent_roots: self.agent_roots(&[AgentId::Claude, AgentId::Agents]),
578 state_root: state,
579 cache_root: cache,
580 })
581 }
582}
583
584#[must_use]
586pub fn instance_paths(docs_root: DocsRoot) -> InstancePaths {
587 let docs = Utf8PathBuf::from(docs_root.as_str());
588 let under = |leaf: &str| PathEntry {
589 path: docs.join(leaf),
590 source: PathSource::Profile,
591 };
592 InstancePaths {
593 instance_dir: PathEntry::default_at(INSTANCE_DIR),
594 manifest: PathEntry::default_at(MANIFEST_PATH),
595 declaration: PathEntry::default_at(CONFIG_PATH),
596 debt: PathEntry::default_at(DEBT_PATH),
597 legacy_debt: PathEntry::default_at(LEGACY_DEBT_PATH),
598 hooks_config: PathEntry::default_at(HOOKS_CONFIG_PATH),
599 agents_digest: PathEntry::default_at(AGENTS_DIGEST_PATH),
600 docs_root: PathEntry {
601 path: docs.clone(),
602 source: PathSource::Profile,
603 },
604 specs: under("specs"),
605 decisions: under("decisions"),
606 reference: under("reference"),
607 guides: under("guides"),
608 lint_config: under(markdownlint::CLI2_NAMES[0]),
609 lint_discovery: LintDiscovery {
610 repository_root: markdownlint::discovery_names()
611 .map(PathEntry::default_at)
612 .collect(),
613 refused_at_docs_root: markdownlint::LIBRARY_NAMES
614 .iter()
615 .map(|name| under(name))
616 .collect(),
617 refused_beneath: vec![under("specs"), under("decisions")],
618 },
619 }
620}
621
622#[must_use]
624pub fn recorded_paths(docs_root: DocsRoot) -> InstancePaths {
625 let mut paths = instance_paths(docs_root);
626 for entry in [
627 &mut paths.docs_root,
628 &mut paths.specs,
629 &mut paths.decisions,
630 &mut paths.reference,
631 &mut paths.guides,
632 &mut paths.lint_config,
633 ]
634 .into_iter()
635 .chain(&mut paths.lint_discovery.refused_at_docs_root)
636 .chain(&mut paths.lint_discovery.refused_beneath)
637 {
638 entry.source = PathSource::Recorded;
639 }
640 paths
641}
642
643#[must_use]
645pub fn candidates() -> BTreeMap<String, CandidatePaths> {
646 ProfileId::every()
647 .map(|profile| {
648 (
649 profile.as_str().to_string(),
650 CandidatePaths {
651 profile,
652 destinations: instance_paths(profile.profile().docs_root),
653 },
654 )
655 })
656 .collect()
657}
658
659#[must_use]
666pub fn docs_scratch_location(recorded: Option<&Utf8Path>, env: &UserEnv) -> ProjectLocation {
667 if env.docs_scratch.is_some() {
668 return ProjectLocation::Env {
669 variable: DOCS_SCRATCH_VAR,
670 value: env.docs_scratch.clone(),
671 };
672 }
673 let Some(path) = recorded else {
674 return ProjectLocation::None;
675 };
676 if path.is_absolute() || path.starts_with("..") {
677 return ProjectLocation::External {
678 path: path.to_owned(),
679 source: PathSource::Recorded,
680 };
681 }
682 ProjectLocation::Untracked {
683 path: path.to_owned(),
684 source: PathSource::Recorded,
685 }
686}
687
688pub const DOCS_SCRATCH_LEAVES: &[&str] = &[".docs-scratch", ".scratch"];
694
695pub fn proposals(env: &UserEnv, held: impl Fn(&Utf8Path) -> bool) -> Proposals {
701 let mut docs_scratch: Vec<LocationChoice> = Vec::new();
702 for leaf in DOCS_SCRATCH_LEAVES {
703 let candidate = Utf8PathBuf::from(*leaf);
704 if held(&candidate) {
705 docs_scratch.push(LocationChoice::Observed { path: candidate });
706 }
707 }
708 docs_scratch.push(LocationChoice::Env {
709 variable: DOCS_SCRATCH_VAR,
710 value: env.docs_scratch.clone(),
711 });
712 docs_scratch.push(LocationChoice::Operator);
713 docs_scratch.push(LocationChoice::None);
714
715 Proposals { docs_scratch }
716}
717
718#[cfg(test)]
719mod tests {
720 use super::*;
721
722 fn env(home: &str) -> UserEnv {
723 UserEnv {
724 home: Some(Utf8PathBuf::from(home)),
725 ..UserEnv::default()
726 }
727 }
728
729 #[test]
730 fn the_agent_root_table_has_two_rows_and_resolves_each_with_its_source() {
731 assert_eq!(AGENT_ROOTS.len(), 2);
732 let resolved = env("/h").agent_roots(&[AgentId::Claude, AgentId::Agents]);
733 assert_eq!(resolved.len(), 2);
734 assert_eq!(resolved[0].path, "/h/.claude/skills");
735 assert_eq!(resolved[0].source, PathSource::Default);
736 assert_eq!(resolved[0].variable, None);
737 assert_eq!(resolved[1].path, "/h/.agents/skills");
738 assert_eq!(resolved[1].id, AgentId::Agents);
739 }
740
741 #[test]
742 fn claude_config_dir_relocates_the_claude_root_and_nothing_else() {
743 let moved = UserEnv {
744 claude_config_dir: Some(Utf8PathBuf::from("/elsewhere/claude")),
745 ..env("/h")
746 };
747 let resolved = moved.agent_roots(&[AgentId::Claude, AgentId::Agents]);
748 assert_eq!(resolved[0].path, "/elsewhere/claude/skills");
749 assert_eq!(resolved[0].source, PathSource::Env);
750 assert_eq!(resolved[0].variable, Some(CLAUDE_CONFIG_DIR_VAR));
751 assert_eq!(resolved[1].path, "/h/.agents/skills");
752 assert_eq!(resolved[1].source, PathSource::Default);
753 }
754
755 #[test]
756 fn an_empty_claude_config_dir_is_treated_as_unset() {
757 let blank = UserEnv {
759 claude_config_dir: None,
760 ..env("/h")
761 };
762 assert_eq!(
763 blank.agent_root(AgentId::Claude).map(|root| root.path),
764 Some(Utf8PathBuf::from("/h/.claude/skills"))
765 );
766 }
767
768 #[test]
769 fn two_selected_roots_that_resolve_to_one_path_are_returned_once() {
770 let collided = UserEnv {
771 claude_config_dir: Some(Utf8PathBuf::from("/h/.agents")),
772 ..env("/h")
773 };
774 let resolved = collided.agent_roots(&[AgentId::Claude, AgentId::Agents]);
775 assert_eq!(resolved.len(), 1);
776 assert_eq!(resolved[0].path, "/h/.agents/skills");
777 assert_eq!(resolved[0].id, AgentId::Claude);
778 }
779
780 #[test]
781 fn the_cache_root_follows_xdg_cache_home_and_its_default() {
782 assert_eq!(
783 env("/h").cache_root(),
784 Some(PathEntry::default_at("/h/.cache/spec-driven-docs"))
785 );
786 let moved = UserEnv {
787 xdg_cache_home: Some(Utf8PathBuf::from("/c")),
788 ..env("/h")
789 };
790 assert_eq!(
791 moved.cache_root(),
792 Some(PathEntry::from_env("/c/spec-driven-docs"))
793 );
794 }
795
796 #[test]
797 fn the_state_root_follows_xdg_state_home_and_its_default() {
798 assert_eq!(
799 env("/h").state_root(),
800 Some(PathEntry::default_at("/h/.local/state/spec-driven-docs"))
801 );
802 let moved = UserEnv {
803 xdg_state_home: Some(Utf8PathBuf::from("/s")),
804 ..env("/h")
805 };
806 assert_eq!(
807 moved.state_root(),
808 Some(PathEntry::from_env("/s/spec-driven-docs"))
809 );
810 assert_eq!(
811 moved.legacy_state_root(),
812 Some(Utf8PathBuf::from("/h/.local/state/spec-driven-docs"))
813 );
814 }
815
816 #[test]
817 fn the_user_paths_hang_off_the_two_roots() {
818 let paths = env("/h").user_paths().unwrap();
819 assert_eq!(
820 paths.skill_receipt.unwrap().path,
821 "/h/.local/state/spec-driven-docs/skills.json"
822 );
823 }
824
825 #[test]
826 fn the_home_relative_constants_agree_with_the_resolved_roots() {
827 let paths = env("/h").user_paths().unwrap();
828 assert_eq!(
829 paths.skill_receipt.unwrap().path,
830 Utf8Path::new("/h").join(LEGACY_SKILL_RECEIPT_PATH)
831 );
832 }
833
834 #[test]
835 fn a_candidate_set_exists_for_every_profile() {
836 let candidates = candidates();
837 assert_eq!(candidates.len(), 2);
838 assert_eq!(candidates["codebase"].destinations.specs.path, "docs/specs");
839 assert_eq!(
840 candidates["knowledge-base"].destinations.specs.path,
841 "_docs/specs"
842 );
843 assert_eq!(
844 candidates["codebase"].destinations.declaration.source,
845 PathSource::Default
846 );
847 assert_eq!(
848 candidates["codebase"].destinations.specs.source,
849 PathSource::Profile
850 );
851 }
852
853 #[test]
854 fn a_recorded_location_reports_as_recorded_and_an_override_as_env() {
855 let overridden = UserEnv {
856 docs_scratch: Some("elsewhere".to_string()),
857 ..env("/h")
858 };
859 assert_eq!(
860 docs_scratch_location(Some(Utf8Path::new(".docs-scratch")), &overridden),
861 ProjectLocation::Env {
862 variable: DOCS_SCRATCH_VAR,
863 value: Some("elsewhere".to_string()),
864 }
865 );
866 }
867
868 #[test]
869 fn a_scratch_beside_the_checkout_reports_as_external() {
870 let plain = env("/h");
871 assert_eq!(
872 docs_scratch_location(Some(Utf8Path::new("../x.docs-scratch")), &plain),
873 ProjectLocation::External {
874 path: Utf8PathBuf::from("../x.docs-scratch"),
875 source: PathSource::Recorded,
876 }
877 );
878 assert_eq!(
879 docs_scratch_location(Some(Utf8Path::new(".docs-scratch")), &plain),
880 ProjectLocation::Untracked {
881 path: Utf8PathBuf::from(".docs-scratch"),
882 source: PathSource::Recorded,
883 }
884 );
885 assert_eq!(docs_scratch_location(None, &plain), ProjectLocation::None);
886 }
887
888 #[test]
889 fn a_proposal_carries_a_path_only_where_the_target_holds_one() {
890 let plain = env("/h");
891 let bare = proposals(&plain, |_| false);
892 assert!(
893 !bare
894 .docs_scratch
895 .iter()
896 .any(|choice| matches!(choice, LocationChoice::Observed { .. }))
897 );
898 assert_eq!(bare.docs_scratch.last(), Some(&LocationChoice::None));
899
900 let observed = proposals(&plain, |path| path == Utf8Path::new(".docs-scratch"));
901 assert_eq!(
902 observed.docs_scratch.first(),
903 Some(&LocationChoice::Observed {
904 path: Utf8PathBuf::from(".docs-scratch")
905 })
906 );
907 }
908}