1use 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
17pub const SCHEMA_VERSION: u32 = 3;
19pub const CANON_SOURCE: &str = "https://github.com/gubasso/spec-driven-docs";
21pub use crate::domain::paths::{DOCS_SCRATCH_VAR, INSTANCE_DIR, MANIFEST_PATH};
25
26pub const RETIRED_FIELDS: &[&str] = &["plan_zone"];
33
34#[derive(Debug, Error, PartialEq, Eq)]
36#[error("{0}")]
37pub struct DeclaredPathError(String);
38
39fn 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
70pub fn validate_docs_scratch_path(path: &Utf8Path) -> Result<(), DeclaredPathError> {
80 declared_path(path.as_str(), true).map(|_| ())
81}
82
83pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct Manifest {
103 pub schema_version: u32,
105 pub canon_version: CanonVersion,
107 pub canon_source: String,
109 pub profile: ProfileId,
111 pub docs_root: DocsRoot,
113 pub installed_at: String,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub docs_scratch: Option<Utf8PathBuf>,
118 pub managed_files: Vec<ManagedEntry>,
120 pub adopted_files: Vec<AdoptedEntry>,
122 pub integration_blocks: Vec<IntegrationBlock>,
124}
125
126#[derive(Debug, Error)]
128pub enum ManifestParseError {
129 #[error("invalid manifest schema: {0}")]
131 Invalid(String),
132 #[error("manifest schema_version {0} is older than this binary's; run 'sdd upgrade'")]
134 Older(u32),
135 #[error("manifest schema_version {0} is newer than this binary's; upgrade sdd")]
137 Newer(u32),
138}
139
140impl Manifest {
141 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 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 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 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 #[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#[derive(Debug, Clone, Deserialize)]
275pub struct LegacyManifest {
276 pub schema_version: u32,
278 pub canon_version: CanonVersion,
280 pub profile: ProfileId,
282 pub docs_root: DocsRoot,
284 pub installed_at: String,
286 pub managed_files: Vec<LegacyOwnedFile>,
288 #[serde(default)]
294 pub integration_blocks: Vec<IntegrationBlock>,
295}
296
297#[derive(Debug, Clone, Deserialize)]
299pub struct LegacyOwnedFile {
300 pub destination: Utf8PathBuf,
302 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 #[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 #[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 #[test]
393 fn the_declared_location_can_be_cleared() {
394 assert_eq!(parse_docs_scratch("none").unwrap(), None);
395 assert_eq!(
397 parse_docs_scratch("./none").unwrap(),
398 Some(Utf8PathBuf::from("none"))
399 );
400 }
401
402 #[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 #[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}