spec_driven_docs/services/
self_manifest.rs1use camino::{Utf8Path, Utf8PathBuf};
13use serde::{Deserialize, Serialize};
14
15use crate::adapters::fs::sha256_file;
16use crate::domain::ownership::Sha256;
17use crate::domain::version::CanonVersion;
18use crate::error::AppError;
19
20pub const PAYLOAD_RECORD_PATH: &str = "instance/payload-manifest.json";
22
23pub const PAYLOAD_RECORD_SCHEMA: &str = "sdd.payload-manifest/1";
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct PayloadFile {
29 pub path: Utf8PathBuf,
31 pub sha256: Sha256,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct PayloadRecord {
39 pub schema: String,
41 pub version: CanonVersion,
43 pub files: Vec<PayloadFile>,
46}
47
48impl PayloadRecord {
49 #[must_use]
51 pub fn to_json(&self) -> String {
52 let mut text = serde_json::to_string_pretty(self).unwrap_or_default();
53 text.push('\n');
54 text
55 }
56}
57
58pub(crate) fn is_canon_checkout(root: &Utf8Path) -> bool {
59 std::fs::read_to_string(root.join("Cargo.toml"))
60 .is_ok_and(|cargo| cargo.contains("name = \"spec-driven-docs\""))
61}
62
63pub fn describe(root: &Utf8Path) -> Result<PayloadRecord, AppError> {
69 let mut files = Vec::new();
70 for declared in crate::payload_roots::PAYLOAD_ROOTS {
71 if !root.join(declared).exists() {
72 continue;
73 }
74 for entry in walkdir::WalkDir::new(root.join(declared)).sort_by_file_name() {
75 let entry = entry.map_err(|source| AppError::Io(std::io::Error::from(source)))?;
76 if !entry.file_type().is_file() {
77 continue;
78 }
79 let Some(path) = Utf8Path::from_path(entry.path()) else {
80 continue;
81 };
82 let relative = path.strip_prefix(root).unwrap_or(path).to_owned();
83 if relative == PAYLOAD_RECORD_PATH {
84 continue;
85 }
86 files.push(PayloadFile {
87 sha256: sha256_file(path)?,
88 path: relative,
89 });
90 }
91 }
92 files.sort_by(|left, right| left.path.cmp(&right.path));
93 Ok(PayloadRecord {
94 schema: PAYLOAD_RECORD_SCHEMA.to_string(),
95 version: CanonVersion::current(),
96 files,
97 })
98}
99
100pub fn regenerate(root: &Utf8Path) -> Result<String, AppError> {
107 if !is_canon_checkout(root) {
108 return Err(AppError::Refused("not the canon checkout".to_string()));
109 }
110 let record = describe(root)?;
111 crate::adapters::fs::write_file(&root.join(PAYLOAD_RECORD_PATH), record.to_json().as_bytes())?;
112 Ok(format!("OK regenerated {PAYLOAD_RECORD_PATH}"))
113}