Skip to main content

spec_driven_docs/services/
self_manifest.rs

1//! Regenerate the canon's own instance manifest.
2//!
3//! The canon is an instance of itself, but not one the installer can
4//! produce: its files sit where it authors them rather than under the
5//! vendored directory. Recording their hashes by hand is how the manifest
6//! drifts from the payload, so it is generated from the payload instead —
7//! and only in the canon checkout, which is recognised by its own crate
8//! manifest.
9
10use camino::Utf8Path;
11
12use crate::adapters::fs::sha256_file;
13use crate::domain::manifest::{CANON_SOURCE, MANIFEST_PATH, Manifest, SCHEMA_VERSION};
14use crate::domain::ownership::{AdoptedEntry, IntegrationBlock, ManagedEntry};
15use crate::domain::profile::{DocsRoot, ProfileId};
16use crate::domain::version::CanonVersion;
17use crate::error::AppError;
18
19pub(crate) fn is_canon_checkout(root: &Utf8Path) -> bool {
20    std::fs::read_to_string(root.join("Cargo.toml"))
21        .is_ok_and(|cargo| cargo.contains("name = \"spec-driven-docs\""))
22}
23
24fn sorted_files(root: &Utf8Path, dir: &str, matches: impl Fn(&str) -> bool) -> Vec<String> {
25    let mut names: Vec<String> = root
26        .join(dir)
27        .read_dir_utf8()
28        .map(|entries| {
29            entries
30                .filter_map(Result::ok)
31                .map(|entry| entry.file_name().to_string())
32                .filter(|name| matches(name))
33                .collect()
34        })
35        .unwrap_or_default();
36    names.sort();
37    names
38        .into_iter()
39        .map(|name| format!("{dir}/{name}"))
40        .collect()
41}
42
43/// Every `skills/<name>/SKILL.md` path in the checkout, sorted by name.
44fn skill_files(root: &Utf8Path) -> Vec<String> {
45    let mut names: Vec<String> = root
46        .join("skills")
47        .read_dir_utf8()
48        .map(|entries| {
49            entries
50                .filter_map(Result::ok)
51                .filter(|entry| entry.path().is_dir())
52                .map(|entry| entry.file_name().to_string())
53                .collect()
54        })
55        .unwrap_or_default();
56    names.sort();
57    names
58        .into_iter()
59        .map(|name| format!("skills/{name}/SKILL.md"))
60        .collect()
61}
62
63/// Regenerate `.spec-driven-docs/manifest.json` in the canon checkout.
64///
65/// # Errors
66///
67/// [`AppError::Refused`] outside the canon checkout, and I/O errors when a
68/// recorded file cannot be read or the manifest cannot be written.
69pub fn regenerate(root: &Utf8Path) -> Result<String, AppError> {
70    if !is_canon_checkout(root) {
71        return Err(AppError::Refused("not the canon checkout".to_string()));
72    }
73
74    let mut managed = Vec::new();
75    // The payload convention is lowercase; the shell glob this replaces was
76    // case-sensitive too.
77    #[allow(clippy::case_sensitive_file_extension_comparisons)]
78    let jsonc = |name: &str| name.ends_with(".jsonc");
79    for path in sorted_files(root, ".markdownlint", jsonc) {
80        managed.push(ManagedEntry {
81            source: path.clone().into(),
82            destination: path.clone().into(),
83            sha256: sha256_file(&root.join(&path))?,
84        });
85    }
86    for path in skill_files(root) {
87        managed.push(ManagedEntry {
88            source: path.clone().into(),
89            destination: path.clone().into(),
90            sha256: sha256_file(&root.join(&path))?,
91        });
92    }
93    // The shared skill artifacts are payload the same way the skills are:
94    // the embedded inventory names them, so the record cannot miss one.
95    for (path, _) in crate::embedded::shared_artifacts() {
96        let path = format!("skill-shared/{path}");
97        managed.push(ManagedEntry {
98            source: path.clone().into(),
99            destination: path.clone().into(),
100            sha256: sha256_file(&root.join(&path))?,
101        });
102    }
103    // The vendored SimpleEnglish surface the profiles project into an
104    // instance. The canon records it at its authored path, so this record
105    // and an instance's hold the same bytes under different destinations.
106    for path in crate::domain::profile::SIMPLE_ENGLISH_MANAGED {
107        managed.push(ManagedEntry {
108            source: (*path).into(),
109            destination: (*path).into(),
110            sha256: sha256_file(&root.join(path))?,
111        });
112    }
113
114    #[allow(clippy::case_sensitive_file_extension_comparisons)]
115    let spec = |name: &str| name.starts_with("SPEC-") && name.ends_with(".md");
116    let mut adopted_paths = sorted_files(root, "_docs/specs", spec);
117    for template in crate::domain::profile::CANON_TEMPLATES {
118        adopted_paths.push((*template).to_string());
119    }
120    let mut adopted = Vec::new();
121    for path in adopted_paths {
122        let digest = sha256_file(&root.join(&path))?;
123        adopted.push(AdoptedEntry {
124            source: path.clone().into(),
125            destination: path.into(),
126            sha256: digest.clone(),
127            baseline_sha256: digest,
128        });
129    }
130    // The dogfood tracking registry: the canon owns its populated bytes, and
131    // the tracking template is the baseline an instance seeds from.
132    let registry = "_docs/reference/tracking.yaml";
133    let registry_baseline = "templates/TEMPLATE-tracking.yaml";
134    if root.join(registry).is_file() {
135        adopted.push(AdoptedEntry {
136            source: registry_baseline.into(),
137            destination: registry.into(),
138            sha256: sha256_file(&root.join(registry))?,
139            baseline_sha256: sha256_file(&root.join(registry_baseline))?,
140        });
141    }
142
143    let config = std::fs::read_to_string(root.join(".pre-commit-config.yaml"))?;
144    let marker_hash = crate::domain::marker::block_hash(&config).ok_or_else(|| {
145        AppError::Refused("no managed block in .pre-commit-config.yaml".to_string())
146    })?;
147
148    let installed_at = std::fs::read_to_string(root.join(MANIFEST_PATH))
149        .ok()
150        .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
151        .and_then(|value| {
152            value
153                .get("installed_at")
154                .and_then(|v| v.as_str())
155                .map(String::from)
156        })
157        .unwrap_or_else(|| {
158            jiff::Timestamp::now()
159                .strftime("%Y-%m-%dT%H:%M:%SZ")
160                .to_string()
161        });
162
163    let manifest = Manifest {
164        schema_version: SCHEMA_VERSION,
165        canon_version: CanonVersion::current(),
166        canon_source: CANON_SOURCE.to_string(),
167        profile: ProfileId::KnowledgeBase,
168        docs_root: DocsRoot::UnderscoreDocs,
169        installed_at,
170        managed_files: managed,
171        adopted_files: adopted,
172        integration_blocks: vec![IntegrationBlock {
173            path: ".pre-commit-config.yaml".into(),
174            marker_hash,
175        }],
176    };
177    crate::adapters::fs::write_file(&root.join(MANIFEST_PATH), manifest.to_json().as_bytes())?;
178    Ok(format!("OK regenerated {MANIFEST_PATH}"))
179}