Skip to main content

spec_driven_docs/domain/
manifest.rs

1//! The instance manifest: the persistent record of what an instance holds.
2//!
3//! Schema version 3. The manifest is what lets a later `sdd` distinguish
4//! managed drift from adopted reconciliation and its own version from the
5//! instance's. This module owns the shape and its parse-time invariants;
6//! reading it from disk, comparing it to bytes, and writing it belong to
7//! the services.
8
9use camino::{Utf8Path, Utf8PathBuf};
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13use crate::domain::ownership::{AdoptedEntry, IntegrationBlock, ManagedEntry};
14use crate::domain::profile::{DocsRoot, ProfileId};
15use crate::domain::version::CanonVersion;
16
17/// The manifest schema this binary reads and writes.
18pub const SCHEMA_VERSION: u32 = 3;
19/// Where the canon is published.
20pub const CANON_SOURCE: &str = "https://github.com/gubasso/spec-driven-docs";
21// Every control path this tool names is declared in `domain::paths`, and
22// reaches its callers from here so that the names they already import stay
23// where they were.
24pub use crate::domain::paths::{DOCS_SCRATCH_VAR, INSTANCE_DIR, MANIFEST_PATH};
25
26/// Fields an earlier release of this schema version wrote and this one
27/// does not read.
28///
29/// A record carrying one parses as if the field were absent, and the next
30/// write omits it, so an instance in the field crosses the removal without
31/// an operator edit and without a schema bump.
32pub const RETIRED_FIELDS: &[&str] = &["plan_zone"];
33
34/// A `--docs-scratch` value the argument cannot mean.
35#[derive(Debug, Error, PartialEq, Eq)]
36#[error("{0}")]
37pub struct DeclaredPathError(String);
38
39/// A declared path, normalized: relative, non-empty, and `./` stripped.
40///
41/// `parents` says whether the path may leave the instance root. A docs
42/// scratch may, because staging beside the checkout is one of the offered
43/// answers.
44fn declared_path(value: &str, parents: bool) -> Result<Utf8PathBuf, DeclaredPathError> {
45    let value = value.trim();
46    if value.is_empty() {
47        return Err(DeclaredPathError("the path is empty".to_string()));
48    }
49    let path = Utf8Path::new(value);
50    if path.is_absolute() {
51        return Err(DeclaredPathError(format!("{value} is not relative")));
52    }
53    let mut normalized = Utf8PathBuf::new();
54    for component in path.components() {
55        match component {
56            camino::Utf8Component::CurDir => {}
57            camino::Utf8Component::ParentDir if parents => normalized.push(".."),
58            camino::Utf8Component::ParentDir => {
59                return Err(DeclaredPathError(format!("{value} leaves the repository")));
60            }
61            other => normalized.push(other.as_str()),
62        }
63    }
64    if normalized.as_str().is_empty() {
65        return Err(DeclaredPathError(format!("{value} names no directory")));
66    }
67    Ok(normalized)
68}
69
70/// Whether a recorded docs-scratch path is one a reader can resolve.
71///
72/// The same check the argument runs. A record reaches a reinstall through a
73/// permissive read, so without this a hand-edited value is carried forward
74/// and only the post-write verification catches it.
75///
76/// # Errors
77///
78/// [`DeclaredPathError`] for a path that is empty or absolute.
79pub fn validate_docs_scratch_path(path: &Utf8Path) -> Result<(), DeclaredPathError> {
80    declared_path(path.as_str(), true).map(|_| ())
81}
82
83/// Read the `--docs-scratch` argument.
84///
85/// `none` clears a recorded value. Without a clearing word an operator who
86/// declares a scratch by typo can change it but never return to the
87/// undeclared state.
88///
89/// # Errors
90///
91/// [`DeclaredPathError`] for a path that is empty or absolute.
92pub fn parse_docs_scratch(value: &str) -> Result<Option<Utf8PathBuf>, DeclaredPathError> {
93    if value.trim() == "none" {
94        return Ok(None);
95    }
96    declared_path(value, true).map(Some)
97}
98
99/// Everything an instance records about itself.
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct Manifest {
103    /// Always [`SCHEMA_VERSION`] once parsed.
104    pub schema_version: u32,
105    /// The canon release that produced the installed payload.
106    pub canon_version: CanonVersion,
107    /// Where that canon is published.
108    pub canon_source: String,
109    /// The profile the instance was installed with.
110    pub profile: ProfileId,
111    /// The documentation root the gates read.
112    pub docs_root: DocsRoot,
113    /// When the instance was first installed; preserved across reinstalls.
114    pub installed_at: String,
115    /// Where material that is not a statement yet is kept.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub docs_scratch: Option<Utf8PathBuf>,
118    /// Byte projections the canon keeps owning.
119    pub managed_files: Vec<ManagedEntry>,
120    /// Files the instance owns against a recorded baseline.
121    pub adopted_files: Vec<AdoptedEntry>,
122    /// Marked regions the canon owns inside project files.
123    pub integration_blocks: Vec<IntegrationBlock>,
124}
125
126/// A manifest that could not be accepted.
127#[derive(Debug, Error)]
128pub enum ManifestParseError {
129    /// Not JSON, or JSON that does not fit the schema.
130    #[error("invalid manifest schema: {0}")]
131    Invalid(String),
132    /// A well-formed manifest of an older schema; upgradable, not readable.
133    #[error("manifest schema_version {0} is older than this binary's; run 'sdd upgrade'")]
134    Older(u32),
135    /// A well-formed manifest of a newer schema; this binary is too old.
136    #[error("manifest schema_version {0} is newer than this binary's; upgrade sdd")]
137    Newer(u32),
138}
139
140impl Manifest {
141    /// Parse and validate a serialized manifest.
142    ///
143    /// # Errors
144    ///
145    /// [`ManifestParseError::Older`] / [`ManifestParseError::Newer`] when the
146    /// recorded schema version is not [`SCHEMA_VERSION`], and
147    /// [`ManifestParseError::Invalid`] for anything that does not fit the
148    /// schema or records no managed file.
149    pub fn parse(json: &str) -> Result<Self, ManifestParseError> {
150        let mut value: serde_json::Value =
151            serde_json::from_str(json).map_err(|e| ManifestParseError::Invalid(e.to_string()))?;
152        match value
153            .get("schema_version")
154            .and_then(serde_json::Value::as_u64)
155        {
156            Some(v) if v == u64::from(SCHEMA_VERSION) => {}
157            Some(v) if v < u64::from(SCHEMA_VERSION) => {
158                return Err(ManifestParseError::Older(u32::try_from(v).unwrap_or(0)));
159            }
160            Some(v) => {
161                return Err(ManifestParseError::Newer(
162                    u32::try_from(v).unwrap_or(u32::MAX),
163                ));
164            }
165            None => {
166                return Err(ManifestParseError::Invalid(
167                    "no numeric schema_version".to_string(),
168                ));
169            }
170        }
171        // A field an earlier release of this schema wrote is dropped on
172        // read, so the record parses as it would have without it.
173        if let Some(object) = value.as_object_mut() {
174            for field in RETIRED_FIELDS {
175                object.remove(*field);
176            }
177        }
178        let manifest: Self = serde_json::from_value(value)
179            .map_err(|e| ManifestParseError::Invalid(e.to_string()))?;
180        if manifest.managed_files.is_empty() {
181            return Err(ManifestParseError::Invalid(
182                "managed_files is empty".to_string(),
183            ));
184        }
185        // The declared location carries the same invariant the argument
186        // enforces. Without this the record is the weaker gate: a
187        // hand-edited absolute path makes a reader resolve outside the
188        // repository.
189        if let Some(path) = &manifest.docs_scratch
190            && let Err(error) = validate_docs_scratch_path(path)
191        {
192            return Err(ManifestParseError::Invalid(format!(
193                "docs_scratch: {error}"
194            )));
195        }
196        let mut paths = std::collections::BTreeSet::new();
197        for block in &manifest.integration_blocks {
198            if !paths.insert(&block.path) {
199                return Err(ManifestParseError::Invalid(format!(
200                    "duplicate integration block path: {}",
201                    block.path
202                )));
203            }
204        }
205        Ok(manifest)
206    }
207
208    /// Parse a record of this schema or of an older one.
209    ///
210    /// An older record is read for what its schema records: the release,
211    /// the profile, the managed digests, the regions, and the adopted
212    /// entries where it carries them. The second value names its schema,
213    /// so a caller warns that `sdd upgrade` moves it. A corrupt record and
214    /// a newer schema still fail.
215    ///
216    /// # Errors
217    ///
218    /// [`ManifestParseError::Invalid`] for a record no schema reads, and
219    /// [`ManifestParseError::Newer`] for a schema newer than this binary's.
220    pub fn parse_any(json: &str) -> Result<(Self, Option<u32>), ManifestParseError> {
221        let schema = match Self::parse(json) {
222            Ok(manifest) => return Ok((manifest, None)),
223            Err(ManifestParseError::Older(schema)) => schema,
224            Err(error) => return Err(error),
225        };
226        let invalid = |error: serde_json::Error| ManifestParseError::Invalid(error.to_string());
227        let legacy: LegacyManifest = serde_json::from_str(json).map_err(invalid)?;
228        let value: serde_json::Value = serde_json::from_str(json).map_err(invalid)?;
229        let field = |key: &str| value.get(key).cloned().unwrap_or(serde_json::Value::Null);
230        let managed_files: Vec<ManagedEntry> = serde_json::from_value(field("managed_files"))
231            .unwrap_or_else(|_| {
232                legacy
233                    .managed_files
234                    .iter()
235                    .map(|entry| ManagedEntry {
236                        source: entry.destination.clone(),
237                        destination: entry.destination.clone(),
238                        sha256: entry.sha256.clone(),
239                    })
240                    .collect()
241            });
242        let manifest = Self {
243            schema_version: legacy.schema_version,
244            canon_version: legacy.canon_version,
245            canon_source: field("canon_source")
246                .as_str()
247                .unwrap_or(CANON_SOURCE)
248                .to_string(),
249            profile: legacy.profile,
250            docs_root: legacy.docs_root,
251            installed_at: legacy.installed_at,
252            docs_scratch: serde_json::from_value(field("docs_scratch")).unwrap_or_default(),
253            managed_files,
254            adopted_files: serde_json::from_value(field("adopted_files")).unwrap_or_default(),
255            integration_blocks: legacy.integration_blocks,
256        };
257        Ok((manifest, Some(schema)))
258    }
259
260    /// Serialize in the canonical on-disk form: two-space indent, trailing newline.
261    #[must_use]
262    pub fn to_json(&self) -> String {
263        let mut json = serde_json::to_string_pretty(self).unwrap_or_default();
264        json.push('\n');
265        json
266    }
267}
268
269/// The parts of an older manifest an upgrade needs.
270///
271/// Deliberately permissive: unknown fields of an older version pass through
272/// unread, so the upgrader can migrate any instance a previous distribution
273/// produced.
274#[derive(Debug, Clone, Deserialize)]
275pub struct LegacyManifest {
276    /// The recorded schema version; the upgrader requires an older one.
277    pub schema_version: u32,
278    /// The canon release the instance was installed from.
279    pub canon_version: CanonVersion,
280    /// The profile the instance was installed with.
281    pub profile: ProfileId,
282    /// The documentation root the gates read.
283    pub docs_root: DocsRoot,
284    /// When the instance was first installed.
285    pub installed_at: String,
286    /// Destination and hash of every file the older version managed.
287    pub managed_files: Vec<LegacyOwnedFile>,
288    /// The marked regions the older version owned inside project files.
289    ///
290    /// Version 1 recorded none, so the default carries that case. Dropping
291    /// the field instead would skip the edited-block conflict check on
292    /// every version-2 upgrade and overwrite the operator's edits.
293    #[serde(default)]
294    pub integration_blocks: Vec<IntegrationBlock>,
295}
296
297/// One version-1 managed entry: only what the conflict scan reads.
298#[derive(Debug, Clone, Deserialize)]
299pub struct LegacyOwnedFile {
300    /// Where the instance holds the file, relative to its root.
301    pub destination: Utf8PathBuf,
302    /// The bytes version 1 recorded for it.
303    pub sha256: crate::domain::ownership::Sha256,
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::domain::ownership::Sha256;
310
311    fn sample() -> Manifest {
312        Manifest {
313            schema_version: SCHEMA_VERSION,
314            canon_version: "0.2.0".parse().unwrap(),
315            canon_source: CANON_SOURCE.to_string(),
316            profile: ProfileId::KnowledgeBase,
317            docs_root: DocsRoot::UnderscoreDocs,
318            installed_at: "2026-08-25T00:00:00Z".to_string(),
319            docs_scratch: Some("scratch".into()),
320            managed_files: vec![ManagedEntry {
321                source: ".markdownlint/spec.markdownlint-cli2.jsonc".into(),
322                destination: ".spec-driven-docs/markdownlint/spec.markdownlint-cli2.jsonc".into(),
323                sha256: Sha256::of(b"x"),
324            }],
325            adopted_files: vec![],
326            integration_blocks: vec![],
327        }
328    }
329
330    #[test]
331    fn round_trips_through_json() {
332        let manifest = sample();
333        let json = manifest.to_json();
334        assert!(json.ends_with('\n'));
335        assert_eq!(Manifest::parse(&json).unwrap(), manifest);
336    }
337
338    #[test]
339    fn rejects_an_older_schema_as_upgradable() {
340        let mut value: serde_json::Value = serde_json::from_str(&sample().to_json()).unwrap();
341        value["schema_version"] = 1.into();
342        assert!(matches!(
343            Manifest::parse(&value.to_string()),
344            Err(ManifestParseError::Older(1))
345        ));
346    }
347
348    #[test]
349    fn rejects_a_newer_schema_as_binary_too_old() {
350        let mut value: serde_json::Value = serde_json::from_str(&sample().to_json()).unwrap();
351        value["schema_version"] = 4.into();
352        assert!(matches!(
353            Manifest::parse(&value.to_string()),
354            Err(ManifestParseError::Newer(4))
355        ));
356    }
357
358    /// A record written before the docs scratch was declared reads as the
359    /// project declaring none, rather than as a broken manifest.
360    #[test]
361    fn a_record_without_the_declared_location_defaults_it() {
362        let mut value: serde_json::Value = serde_json::from_str(&sample().to_json()).unwrap();
363        value.as_object_mut().unwrap().remove("docs_scratch");
364        let manifest = Manifest::parse(&value.to_string()).unwrap();
365        assert_eq!(manifest.docs_scratch, None);
366    }
367
368    /// A field an earlier release of this schema wrote parses as absent,
369    /// whatever shape it carries, and the next write omits it.
370    #[test]
371    fn a_retired_field_is_dropped_on_read_and_omitted_on_write() {
372        for retired in RETIRED_FIELDS {
373            let mut value: serde_json::Value = serde_json::from_str(&sample().to_json()).unwrap();
374            value[*retired] = serde_json::json!({"kind": "tracked", "path": "docs/plan"});
375            let manifest = Manifest::parse(&value.to_string()).unwrap();
376            assert_eq!(manifest, sample());
377            assert!(!manifest.to_json().contains(retired));
378        }
379    }
380
381    #[test]
382    fn a_docs_scratch_may_leave_the_repository() {
383        assert_eq!(
384            parse_docs_scratch("../beside-the-checkout").unwrap(),
385            Some(Utf8PathBuf::from("../beside-the-checkout"))
386        );
387        assert!(parse_docs_scratch("/tmp/scratch").is_err());
388        assert!(parse_docs_scratch("").is_err());
389    }
390
391    /// The declared value has a clearing word, so a typo can be undone.
392    #[test]
393    fn the_declared_location_can_be_cleared() {
394        assert_eq!(parse_docs_scratch("none").unwrap(), None);
395        // And a directory literally named `none` is still reachable.
396        assert_eq!(
397            parse_docs_scratch("./none").unwrap(),
398            Some(Utf8PathBuf::from("none"))
399        );
400    }
401
402    /// The record carries the same invariant the argument enforces.
403    #[test]
404    fn a_recorded_location_the_argument_would_refuse_is_invalid() {
405        let mut value: serde_json::Value = serde_json::from_str(&sample().to_json()).unwrap();
406        value["docs_scratch"] = "/tmp/scratch".into();
407        assert!(matches!(
408            Manifest::parse(&value.to_string()),
409            Err(ManifestParseError::Invalid(_))
410        ));
411    }
412
413    #[test]
414    fn rejects_unknown_fields_and_empty_managed_sets() {
415        let mut value: serde_json::Value = serde_json::from_str(&sample().to_json()).unwrap();
416        value["canon_ref"] = "v0.2.0".into();
417        assert!(matches!(
418            Manifest::parse(&value.to_string()),
419            Err(ManifestParseError::Invalid(_))
420        ));
421
422        let mut value: serde_json::Value = serde_json::from_str(&sample().to_json()).unwrap();
423        value["managed_files"] = serde_json::Value::Array(vec![]);
424        assert!(matches!(
425            Manifest::parse(&value.to_string()),
426            Err(ManifestParseError::Invalid(_))
427        ));
428    }
429
430    #[test]
431    fn legacy_manifest_reads_a_version_one_shape() {
432        let json = r#"{
433            "schema_version": 1,
434            "canon_version": "0.1.6",
435            "canon_source": "https://github.com/gubasso/spec-driven-docs",
436            "canon_ref": "pre-release",
437            "profile": "knowledge-base",
438            "docs_root": "_docs",
439            "installed_at": "2026-08-24T00:00:00Z",
440            "managed_files": [
441                {"source": "scripts/verify.sh", "destination": ".spec-driven-docs/verify.sh",
442                 "sha256": "dc17d596ae2c196cc01b439c291416f91198cc274e2376fd01a4d614c1ff60ad"}
443            ],
444            "adopted_files": [],
445            "integration_blocks": []
446        }"#;
447        let legacy: LegacyManifest = serde_json::from_str(json).unwrap();
448        assert_eq!(legacy.schema_version, 1);
449        assert_eq!(legacy.canon_version.to_string(), "0.1.6");
450        assert_eq!(legacy.managed_files.len(), 1);
451        assert!(legacy.integration_blocks.is_empty());
452    }
453
454    /// A record of the shape version 2 actually wrote — the current one
455    /// without `docs_scratch`, which version 2 had no field for — parses,
456    /// and its integration blocks reach the upgrade. Without them the
457    /// edited-block conflict check is skipped on every version-2 hop.
458    #[test]
459    fn legacy_manifest_reads_the_version_two_shape() {
460        let mut value: serde_json::Value = serde_json::from_str(&sample().to_json()).unwrap();
461        value["schema_version"] = 2.into();
462        let object = value.as_object_mut().unwrap();
463        object.remove("docs_scratch");
464        value["integration_blocks"] = serde_json::json!([{
465            "path": ".pre-commit-config.yaml",
466            "marker_hash": Sha256::of(b"block").to_string(),
467        }]);
468        let legacy: LegacyManifest = serde_json::from_str(&value.to_string()).unwrap();
469        assert_eq!(legacy.integration_blocks.len(), 1);
470        assert_eq!(legacy.integration_blocks[0].path, ".pre-commit-config.yaml");
471    }
472}