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/"];
72
73pub const STATE_ROOT: &str = ".local/state/spec-driven-docs";
75pub const CACHE_ROOT: &str = ".cache/spec-driven-docs";
77pub const SKILL_RECEIPT_FILE: &str = "skills.json";
79pub const SKILL_FILE: &str = "SKILL.md";
81pub const SKILL_REFERENCES_DIR: &str = "references";
83
84pub const SKILL_LOCK_FILE: &str = "skills.lock";
86pub const SELF_DEPEND_STAMP_DIR: &str = "self-depend";
88pub const SELF_DEPEND_CACHE_DIR: &str = "self-depend";
90pub const LEGACY_SKILL_RECEIPT_PATH: &str = ".local/state/spec-driven-docs/skills.json";
96pub const LEGACY_SHARED_ROOT: &str = ".local/state/spec-driven-docs/skills/shared";
102pub const CLAUDE_ROOT: &str = ".claude/skills";
104pub const AGENTS_ROOT: &str = ".agents/skills";
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
109#[serde(rename_all = "kebab-case")]
110pub enum AgentId {
111 Claude,
113 Agents,
115}
116
117impl AgentId {
118 #[must_use]
120 pub const fn as_str(self) -> &'static str {
121 match self {
122 Self::Claude => "claude",
123 Self::Agents => "agents",
124 }
125 }
126}
127
128impl std::fmt::Display for AgentId {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 f.write_str(self.as_str())
131 }
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub struct AgentRoot {
137 pub id: AgentId,
139 pub default: &'static str,
141 pub config_env: Option<&'static str>,
143 pub relocated: &'static str,
145}
146
147const CLAUDE: AgentRoot = AgentRoot {
149 id: AgentId::Claude,
150 default: CLAUDE_ROOT,
151 config_env: Some(CLAUDE_CONFIG_DIR_VAR),
152 relocated: "skills",
153};
154
155const AGENTS: AgentRoot = AgentRoot {
157 id: AgentId::Agents,
158 default: AGENTS_ROOT,
159 config_env: None,
160 relocated: "skills",
161};
162
163pub const AGENT_ROOTS: &[AgentRoot] = &[CLAUDE, AGENTS];
170
171#[must_use]
173pub const fn agent_root(id: AgentId) -> &'static AgentRoot {
174 match id {
175 AgentId::Claude => &CLAUDE,
176 AgentId::Agents => &AGENTS,
177 }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
182#[serde(rename_all = "kebab-case")]
183pub enum PathSource {
184 Recorded,
186 Default,
188 Env,
190 Profile,
192 Proposal,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
198pub struct PathEntry {
199 pub path: Utf8PathBuf,
201 pub source: PathSource,
203}
204
205impl PathEntry {
206 #[must_use]
208 pub fn default_at(path: impl Into<Utf8PathBuf>) -> Self {
209 Self {
210 path: path.into(),
211 source: PathSource::Default,
212 }
213 }
214
215 #[must_use]
217 pub fn from_env(path: impl Into<Utf8PathBuf>) -> Self {
218 Self {
219 path: path.into(),
220 source: PathSource::Env,
221 }
222 }
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
227pub struct AgentRootEntry {
228 pub id: AgentId,
230 pub path: Utf8PathBuf,
232 pub source: PathSource,
234 pub variable: Option<&'static str>,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
245#[serde(tag = "kind", rename_all = "kebab-case")]
246pub enum ProjectLocation {
247 Tracked {
249 path: Utf8PathBuf,
251 source: PathSource,
253 },
254 Untracked {
256 path: Utf8PathBuf,
258 source: PathSource,
260 },
261 External {
263 path: Utf8PathBuf,
265 source: PathSource,
267 },
268 Env {
270 variable: &'static str,
272 value: Option<String>,
274 },
275 None,
277}
278
279#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
285#[serde(tag = "kind", rename_all = "kebab-case")]
286pub enum LocationChoice {
287 Observed {
289 path: Utf8PathBuf,
291 },
292 Env {
294 variable: &'static str,
296 value: Option<String>,
298 },
299 Operator,
301 None,
303}
304
305#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
307pub struct Proposals {
308 pub docs_scratch: Vec<LocationChoice>,
310}
311
312#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
314pub struct UserPaths {
315 pub state_root: PathEntry,
317 pub cache_root: PathEntry,
319 pub skill_receipt: PathEntry,
321 pub agent_roots: Vec<AgentRootEntry>,
323}
324
325#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
327pub struct InstancePaths {
328 pub instance_dir: PathEntry,
330 pub manifest: PathEntry,
332 pub declaration: PathEntry,
334 pub debt: PathEntry,
336 pub legacy_debt: PathEntry,
338 pub hooks_config: PathEntry,
340 pub agents_digest: PathEntry,
342 pub docs_root: PathEntry,
344 pub specs: PathEntry,
346 pub decisions: PathEntry,
348 pub reference: PathEntry,
350 pub guides: PathEntry,
352 pub lint_config: PathEntry,
355 pub lint_discovery: LintDiscovery,
358}
359
360#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
366pub struct LintDiscovery {
367 pub repository_root: Vec<PathEntry>,
371 pub refused_at_docs_root: Vec<PathEntry>,
374 pub refused_beneath: Vec<PathEntry>,
377}
378
379#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
381pub struct ActivePaths {
382 pub profile: ProfileId,
384 pub destinations: InstancePaths,
386 pub docs_scratch: ProjectLocation,
388}
389
390#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
392pub struct CandidatePaths {
393 pub profile: ProfileId,
395 pub destinations: InstancePaths,
397}
398
399#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
401pub struct Paths {
402 pub user: Option<UserPaths>,
405 pub active: Option<ActivePaths>,
407 pub candidates: BTreeMap<String, CandidatePaths>,
409 pub proposals: Proposals,
411}
412
413#[derive(Debug, Clone, Default, PartialEq, Eq)]
415pub struct UserEnv {
416 pub home: Option<Utf8PathBuf>,
418 pub claude_config_dir: Option<Utf8PathBuf>,
420 pub xdg_state_home: Option<Utf8PathBuf>,
422 pub xdg_cache_home: Option<Utf8PathBuf>,
424 pub docs_scratch: Option<String>,
426}
427
428#[must_use]
434pub fn variable(name: &str) -> Option<String> {
435 std::env::var(name)
436 .ok()
437 .map(|value| value.trim().to_string())
438 .filter(|value| !value.is_empty())
439}
440
441impl UserEnv {
442 #[must_use]
444 pub fn from_process() -> Self {
445 let path = |name: &str| variable(name).map(Utf8PathBuf::from);
446 Self {
447 home: path(HOME_VAR),
448 claude_config_dir: path(CLAUDE_CONFIG_DIR_VAR),
449 xdg_state_home: path(XDG_STATE_HOME_VAR),
450 xdg_cache_home: path(XDG_CACHE_HOME_VAR),
451 docs_scratch: variable(DOCS_SCRATCH_VAR),
452 }
453 }
454
455 #[must_use]
457 pub fn state_root(&self) -> Option<PathEntry> {
458 if let Some(base) = self.xdg_state_home.as_ref() {
459 return Some(PathEntry::from_env(base.join(TOOL_DIR)));
460 }
461 self.home
462 .as_ref()
463 .map(|home| PathEntry::default_at(home.join(STATE_ROOT)))
464 }
465
466 #[must_use]
472 pub fn legacy_state_root(&self) -> Option<Utf8PathBuf> {
473 self.home.as_ref().map(|home| home.join(STATE_ROOT))
474 }
475
476 #[must_use]
478 pub fn cache_root(&self) -> Option<PathEntry> {
479 if let Some(base) = self.xdg_cache_home.as_ref() {
480 return Some(PathEntry::from_env(base.join(TOOL_DIR)));
481 }
482 self.home
483 .as_ref()
484 .map(|home| PathEntry::default_at(home.join(CACHE_ROOT)))
485 }
486
487 #[must_use]
489 pub fn agent_root(&self, id: AgentId) -> Option<AgentRootEntry> {
490 let row = agent_root(id);
491 let home = self.home.as_ref()?;
492 let relocated = match row.id {
493 AgentId::Claude => self.claude_config_dir.as_ref(),
494 AgentId::Agents => None,
495 };
496 Some(relocated.map_or_else(
497 || AgentRootEntry {
498 id: row.id,
499 path: home.join(row.default),
500 source: PathSource::Default,
501 variable: None,
502 },
503 |base| AgentRootEntry {
504 id: row.id,
505 path: base.join(row.relocated),
506 source: PathSource::Env,
507 variable: row.config_env,
508 },
509 ))
510 }
511
512 #[must_use]
518 pub fn agent_roots(&self, selected: &[AgentId]) -> Vec<AgentRootEntry> {
519 let mut resolved: Vec<AgentRootEntry> = Vec::new();
520 for row in AGENT_ROOTS {
521 if !selected.contains(&row.id) {
522 continue;
523 }
524 let Some(entry) = self.agent_root(row.id) else {
525 continue;
526 };
527 if resolved.iter().any(|held| held.path == entry.path) {
528 continue;
529 }
530 resolved.push(entry);
531 }
532 resolved
533 }
534
535 #[must_use]
537 pub fn user_paths(&self) -> Option<UserPaths> {
538 let state = self.state_root()?;
539 let cache = self.cache_root()?;
540 Some(UserPaths {
541 skill_receipt: PathEntry {
542 path: state.path.join(SKILL_RECEIPT_FILE),
543 source: state.source,
544 },
545 agent_roots: self.agent_roots(&[AgentId::Claude, AgentId::Agents]),
546 state_root: state,
547 cache_root: cache,
548 })
549 }
550}
551
552#[must_use]
554pub fn instance_paths(docs_root: DocsRoot) -> InstancePaths {
555 let docs = Utf8PathBuf::from(docs_root.as_str());
556 let under = |leaf: &str| PathEntry {
557 path: docs.join(leaf),
558 source: PathSource::Profile,
559 };
560 InstancePaths {
561 instance_dir: PathEntry::default_at(INSTANCE_DIR),
562 manifest: PathEntry::default_at(MANIFEST_PATH),
563 declaration: PathEntry::default_at(CONFIG_PATH),
564 debt: PathEntry::default_at(DEBT_PATH),
565 legacy_debt: PathEntry::default_at(LEGACY_DEBT_PATH),
566 hooks_config: PathEntry::default_at(HOOKS_CONFIG_PATH),
567 agents_digest: PathEntry::default_at(AGENTS_DIGEST_PATH),
568 docs_root: PathEntry {
569 path: docs.clone(),
570 source: PathSource::Profile,
571 },
572 specs: under("specs"),
573 decisions: under("decisions"),
574 reference: under("reference"),
575 guides: under("guides"),
576 lint_config: under(markdownlint::CLI2_NAMES[0]),
577 lint_discovery: LintDiscovery {
578 repository_root: markdownlint::discovery_names()
579 .map(PathEntry::default_at)
580 .collect(),
581 refused_at_docs_root: markdownlint::LIBRARY_NAMES
582 .iter()
583 .map(|name| under(name))
584 .collect(),
585 refused_beneath: vec![under("specs"), under("decisions")],
586 },
587 }
588}
589
590#[must_use]
592pub fn recorded_paths(docs_root: DocsRoot) -> InstancePaths {
593 let mut paths = instance_paths(docs_root);
594 for entry in [
595 &mut paths.docs_root,
596 &mut paths.specs,
597 &mut paths.decisions,
598 &mut paths.reference,
599 &mut paths.guides,
600 &mut paths.lint_config,
601 ]
602 .into_iter()
603 .chain(&mut paths.lint_discovery.refused_at_docs_root)
604 .chain(&mut paths.lint_discovery.refused_beneath)
605 {
606 entry.source = PathSource::Recorded;
607 }
608 paths
609}
610
611#[must_use]
613pub fn candidates() -> BTreeMap<String, CandidatePaths> {
614 ProfileId::every()
615 .map(|profile| {
616 (
617 profile.as_str().to_string(),
618 CandidatePaths {
619 profile,
620 destinations: instance_paths(profile.profile().docs_root),
621 },
622 )
623 })
624 .collect()
625}
626
627#[must_use]
634pub fn docs_scratch_location(recorded: Option<&Utf8Path>, env: &UserEnv) -> ProjectLocation {
635 if env.docs_scratch.is_some() {
636 return ProjectLocation::Env {
637 variable: DOCS_SCRATCH_VAR,
638 value: env.docs_scratch.clone(),
639 };
640 }
641 let Some(path) = recorded else {
642 return ProjectLocation::None;
643 };
644 if path.is_absolute() || path.starts_with("..") {
645 return ProjectLocation::External {
646 path: path.to_owned(),
647 source: PathSource::Recorded,
648 };
649 }
650 ProjectLocation::Untracked {
651 path: path.to_owned(),
652 source: PathSource::Recorded,
653 }
654}
655
656pub const DOCS_SCRATCH_LEAVES: &[&str] = &[".docs-scratch", ".scratch"];
662
663pub fn proposals(env: &UserEnv, held: impl Fn(&Utf8Path) -> bool) -> Proposals {
669 let mut docs_scratch: Vec<LocationChoice> = Vec::new();
670 for leaf in DOCS_SCRATCH_LEAVES {
671 let candidate = Utf8PathBuf::from(*leaf);
672 if held(&candidate) {
673 docs_scratch.push(LocationChoice::Observed { path: candidate });
674 }
675 }
676 docs_scratch.push(LocationChoice::Env {
677 variable: DOCS_SCRATCH_VAR,
678 value: env.docs_scratch.clone(),
679 });
680 docs_scratch.push(LocationChoice::Operator);
681 docs_scratch.push(LocationChoice::None);
682
683 Proposals { docs_scratch }
684}
685
686#[cfg(test)]
687mod tests {
688 use super::*;
689
690 fn env(home: &str) -> UserEnv {
691 UserEnv {
692 home: Some(Utf8PathBuf::from(home)),
693 ..UserEnv::default()
694 }
695 }
696
697 #[test]
698 fn the_agent_root_table_has_two_rows_and_resolves_each_with_its_source() {
699 assert_eq!(AGENT_ROOTS.len(), 2);
700 let resolved = env("/h").agent_roots(&[AgentId::Claude, AgentId::Agents]);
701 assert_eq!(resolved.len(), 2);
702 assert_eq!(resolved[0].path, "/h/.claude/skills");
703 assert_eq!(resolved[0].source, PathSource::Default);
704 assert_eq!(resolved[0].variable, None);
705 assert_eq!(resolved[1].path, "/h/.agents/skills");
706 assert_eq!(resolved[1].id, AgentId::Agents);
707 }
708
709 #[test]
710 fn claude_config_dir_relocates_the_claude_root_and_nothing_else() {
711 let moved = UserEnv {
712 claude_config_dir: Some(Utf8PathBuf::from("/elsewhere/claude")),
713 ..env("/h")
714 };
715 let resolved = moved.agent_roots(&[AgentId::Claude, AgentId::Agents]);
716 assert_eq!(resolved[0].path, "/elsewhere/claude/skills");
717 assert_eq!(resolved[0].source, PathSource::Env);
718 assert_eq!(resolved[0].variable, Some(CLAUDE_CONFIG_DIR_VAR));
719 assert_eq!(resolved[1].path, "/h/.agents/skills");
720 assert_eq!(resolved[1].source, PathSource::Default);
721 }
722
723 #[test]
724 fn an_empty_claude_config_dir_is_treated_as_unset() {
725 let blank = UserEnv {
727 claude_config_dir: None,
728 ..env("/h")
729 };
730 assert_eq!(
731 blank.agent_root(AgentId::Claude).map(|root| root.path),
732 Some(Utf8PathBuf::from("/h/.claude/skills"))
733 );
734 }
735
736 #[test]
737 fn two_selected_roots_that_resolve_to_one_path_are_returned_once() {
738 let collided = UserEnv {
739 claude_config_dir: Some(Utf8PathBuf::from("/h/.agents")),
740 ..env("/h")
741 };
742 let resolved = collided.agent_roots(&[AgentId::Claude, AgentId::Agents]);
743 assert_eq!(resolved.len(), 1);
744 assert_eq!(resolved[0].path, "/h/.agents/skills");
745 assert_eq!(resolved[0].id, AgentId::Claude);
746 }
747
748 #[test]
749 fn the_cache_root_follows_xdg_cache_home_and_its_default() {
750 assert_eq!(
751 env("/h").cache_root(),
752 Some(PathEntry::default_at("/h/.cache/spec-driven-docs"))
753 );
754 let moved = UserEnv {
755 xdg_cache_home: Some(Utf8PathBuf::from("/c")),
756 ..env("/h")
757 };
758 assert_eq!(
759 moved.cache_root(),
760 Some(PathEntry::from_env("/c/spec-driven-docs"))
761 );
762 }
763
764 #[test]
765 fn the_state_root_follows_xdg_state_home_and_its_default() {
766 assert_eq!(
767 env("/h").state_root(),
768 Some(PathEntry::default_at("/h/.local/state/spec-driven-docs"))
769 );
770 let moved = UserEnv {
771 xdg_state_home: Some(Utf8PathBuf::from("/s")),
772 ..env("/h")
773 };
774 assert_eq!(
775 moved.state_root(),
776 Some(PathEntry::from_env("/s/spec-driven-docs"))
777 );
778 assert_eq!(
779 moved.legacy_state_root(),
780 Some(Utf8PathBuf::from("/h/.local/state/spec-driven-docs"))
781 );
782 }
783
784 #[test]
785 fn the_user_paths_hang_off_the_two_roots() {
786 let paths = env("/h").user_paths().unwrap();
787 assert_eq!(
788 paths.skill_receipt.path,
789 "/h/.local/state/spec-driven-docs/skills.json"
790 );
791 }
792
793 #[test]
794 fn the_home_relative_constants_agree_with_the_resolved_roots() {
795 let paths = env("/h").user_paths().unwrap();
796 assert_eq!(
797 paths.skill_receipt.path,
798 Utf8Path::new("/h").join(LEGACY_SKILL_RECEIPT_PATH)
799 );
800 }
801
802 #[test]
803 fn a_candidate_set_exists_for_every_profile() {
804 let candidates = candidates();
805 assert_eq!(candidates.len(), 2);
806 assert_eq!(candidates["codebase"].destinations.specs.path, "docs/specs");
807 assert_eq!(
808 candidates["knowledge-base"].destinations.specs.path,
809 "_docs/specs"
810 );
811 assert_eq!(
812 candidates["codebase"].destinations.declaration.source,
813 PathSource::Default
814 );
815 assert_eq!(
816 candidates["codebase"].destinations.specs.source,
817 PathSource::Profile
818 );
819 }
820
821 #[test]
822 fn a_recorded_location_reports_as_recorded_and_an_override_as_env() {
823 let overridden = UserEnv {
824 docs_scratch: Some("elsewhere".to_string()),
825 ..env("/h")
826 };
827 assert_eq!(
828 docs_scratch_location(Some(Utf8Path::new(".docs-scratch")), &overridden),
829 ProjectLocation::Env {
830 variable: DOCS_SCRATCH_VAR,
831 value: Some("elsewhere".to_string()),
832 }
833 );
834 }
835
836 #[test]
837 fn a_scratch_beside_the_checkout_reports_as_external() {
838 let plain = env("/h");
839 assert_eq!(
840 docs_scratch_location(Some(Utf8Path::new("../x.docs-scratch")), &plain),
841 ProjectLocation::External {
842 path: Utf8PathBuf::from("../x.docs-scratch"),
843 source: PathSource::Recorded,
844 }
845 );
846 assert_eq!(
847 docs_scratch_location(Some(Utf8Path::new(".docs-scratch")), &plain),
848 ProjectLocation::Untracked {
849 path: Utf8PathBuf::from(".docs-scratch"),
850 source: PathSource::Recorded,
851 }
852 );
853 assert_eq!(docs_scratch_location(None, &plain), ProjectLocation::None);
854 }
855
856 #[test]
857 fn a_proposal_carries_a_path_only_where_the_target_holds_one() {
858 let plain = env("/h");
859 let bare = proposals(&plain, |_| false);
860 assert!(
861 !bare
862 .docs_scratch
863 .iter()
864 .any(|choice| matches!(choice, LocationChoice::Observed { .. }))
865 );
866 assert_eq!(bare.docs_scratch.last(), Some(&LocationChoice::None));
867
868 let observed = proposals(&plain, |path| path == Utf8Path::new(".docs-scratch"));
869 assert_eq!(
870 observed.docs_scratch.first(),
871 Some(&LocationChoice::Observed {
872 path: Utf8PathBuf::from(".docs-scratch")
873 })
874 );
875 }
876}