spec_driven_docs/services/
verifier.rs1use camino::Utf8Path;
11
12use crate::adapters::fs::{DestinationRefusal, check_destination, sha256_file};
13use crate::domain::gate_id::GateId;
14use crate::domain::manifest::{MANIFEST_PATH, Manifest, ManifestParseError};
15use crate::domain::marker;
16use crate::domain::version::CanonVersion;
17use crate::error::AppError;
18
19#[derive(Debug, Default)]
21pub struct VerifyReport {
22 pub lines: Vec<String>,
24 pub failures: usize,
26 pub managed_drift: usize,
28 pub adopted_drift: usize,
30}
31
32impl VerifyReport {
33 fn fail(&mut self, line: impl Into<String>) {
34 self.lines.push(line.into());
35 self.failures += 1;
36 }
37
38 fn note(&mut self, line: impl Into<String>) {
39 self.lines.push(line.into());
40 }
41}
42
43pub(crate) fn read_manifest(target: &Utf8Path) -> Result<Manifest, AppError> {
44 let path = target.join(MANIFEST_PATH);
45 if reached_through_symlink(target, Utf8Path::new(MANIFEST_PATH)) {
46 return Err(AppError::ManifestInvalid(
47 "manifest reached through a symlink".to_string(),
48 ));
49 }
50 if !path.is_file() {
51 return Err(AppError::ManifestMissing(path));
52 }
53 let text = std::fs::read_to_string(&path)?;
54 Manifest::parse(&text).map_err(|error| match error {
55 ManifestParseError::Invalid(detail) => AppError::ManifestInvalid(detail),
56 other => AppError::ManifestInvalid(other.to_string()),
57 })
58}
59
60fn check_block_entries(block: &str, report: &mut VerifyReport) {
61 let mut sdd_entries = 0usize;
62 for line in block.lines() {
63 let Some(entry) = line.trim_start().strip_prefix("entry: ") else {
64 continue;
65 };
66 let words: Vec<&str> = entry.split_whitespace().collect();
67 let Some(gate_position) = words.iter().position(|word| *word == "gate") else {
68 if words.last() == Some(&"verify") {
69 sdd_entries += 1;
70 }
71 continue;
72 };
73 sdd_entries += 1;
74 match words.get(gate_position + 1) {
75 Some(id) if id.parse::<GateId>().is_ok() => {}
76 Some(id) => report.fail(format!(
77 "FAIL managed block entry names an unknown gate: {id}"
78 )),
79 None => report.fail(format!("FAIL managed block entry names no gate: {entry}")),
80 }
81 }
82 if sdd_entries == 0 {
83 report.fail("FAIL managed block wires no sdd entry");
84 }
85}
86
87fn reached_through_symlink(target: &Utf8Path, destination: &Utf8Path) -> bool {
88 matches!(
89 check_destination(target, destination),
90 Err(DestinationRefusal::SymlinkEscape)
91 )
92}
93
94fn check_projection(manifest: &Manifest, report: &mut VerifyReport) {
104 if manifest.canon_version != CanonVersion::current() {
105 return;
106 }
107 let declaration = manifest.profile.profile();
108 let managed: std::collections::BTreeSet<&str> = manifest
109 .managed_files
110 .iter()
111 .map(|entry| entry.destination.as_str())
112 .collect();
113 let adopted: std::collections::BTreeSet<&str> = manifest
114 .adopted_files
115 .iter()
116 .map(|entry| entry.destination.as_str())
117 .collect();
118
119 let self_layout = declaration
120 .managed
121 .iter()
122 .all(|projection| managed.contains(projection.source));
123
124 let mut expected: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
125 let mut missing: Vec<String> = Vec::new();
126 if self_layout {
127 for projection in declaration.managed {
128 expected.insert(projection.source.to_string());
129 }
130 for file in crate::embedded::SPECS.files() {
131 if let Some(name) = file.path().as_os_str().to_str() {
132 expected.insert(format!("_docs/specs/{name}"));
133 }
134 }
135 for template in crate::domain::profile::CANON_TEMPLATES {
136 expected.insert((*template).to_string());
137 }
138 for destination in &expected {
139 if !managed.contains(destination.as_str()) && !adopted.contains(destination.as_str()) {
140 missing.push(destination.clone());
141 }
142 }
143 } else {
144 for projection in declaration.managed {
145 if !managed.contains(projection.destination) {
146 missing.push(projection.destination.to_string());
147 }
148 }
149 for projection in declaration.adopted {
150 let destination = crate::domain::profile::resolve_destination(
151 projection.destination,
152 manifest.docs_root,
153 );
154 if !adopted.contains(destination.as_str()) {
155 missing.push(destination.to_string());
156 }
157 }
158 }
159 for destination in missing {
160 report.fail(format!(
161 "FAIL manifest omits a declared projection: {destination}"
162 ));
163 }
164 if !manifest
165 .integration_blocks
166 .iter()
167 .any(|block| block.path == ".pre-commit-config.yaml")
168 {
169 report.fail("FAIL manifest records no integration block for .pre-commit-config.yaml");
170 }
171}
172
173pub fn verify(target: &Utf8Path) -> Result<VerifyReport, AppError> {
181 let manifest = read_manifest(target)?;
182 let mut report = VerifyReport::default();
183
184 for entry in &manifest.managed_files {
185 let file = target.join(&entry.destination);
186 if reached_through_symlink(target, &entry.destination) {
187 report.managed_drift += 1;
188 report.fail(format!(
189 "FAIL managed file reached through a symlink: {}",
190 entry.destination
191 ));
192 continue;
193 }
194 if !file.is_file() {
195 report.managed_drift += 1;
196 report.fail(format!("FAIL missing managed file: {}", entry.destination));
197 continue;
198 }
199 if sha256_file(&file)? != entry.sha256 {
200 report.managed_drift += 1;
201 report.fail(format!("FAIL managed drift: {}", entry.destination));
202 }
203 }
204
205 for entry in &manifest.adopted_files {
206 let file = target.join(&entry.destination);
207 if reached_through_symlink(target, &entry.destination) {
208 report.fail(format!(
209 "FAIL adopted file reached through a symlink: {}",
210 entry.destination
211 ));
212 continue;
213 }
214 if !file.is_file() {
215 report.fail(format!("FAIL missing adopted file: {}", entry.destination));
216 continue;
217 }
218 if sha256_file(&file)? != entry.sha256 {
219 report.adopted_drift += 1;
220 report.note(format!(
221 "DRIFT adopted file requires reconciliation: {}",
222 entry.destination
223 ));
224 }
225 }
226
227 check_projection(&manifest, &mut report);
228 check_integration(target, &manifest, &mut report)?;
229 check_specs(target, &manifest, &mut report)?;
230
231 let current = CanonVersion::current();
232 if manifest.canon_version > current {
233 report.fail(format!(
234 "FAIL sdd {current} is older than the installed canon {}; upgrade sdd",
235 manifest.canon_version
236 ));
237 } else if manifest.canon_version < current {
238 report.note(format!(
239 "note: sdd {current} is newer than the installed canon {}; run 'sdd upgrade'",
240 manifest.canon_version
241 ));
242 }
243
244 if report.failures == 0 {
245 report.note(format!(
246 "OK spec-driven-docs {} at {target}",
247 manifest.canon_version
248 ));
249 }
250 Ok(report)
251}
252
253fn check_integration(
254 target: &Utf8Path,
255 manifest: &Manifest,
256 report: &mut VerifyReport,
257) -> Result<(), AppError> {
258 let config_path = target.join(".pre-commit-config.yaml");
259 if reached_through_symlink(target, Utf8Path::new(".pre-commit-config.yaml")) {
260 report.fail("FAIL .pre-commit-config.yaml reached through a symlink");
261 } else if config_path.is_file() {
262 let config = std::fs::read_to_string(&config_path)?;
263 let begins = config.lines().filter(|line| *line == marker::BEGIN).count();
264 let ends = config.lines().filter(|line| *line == marker::END).count();
265 if begins != 1 {
266 report.fail("FAIL missing managed pre-commit block");
267 } else if ends != 1 {
268 report.fail("FAIL malformed managed pre-commit block");
269 } else {
270 let recorded = manifest
271 .integration_blocks
272 .iter()
273 .find(|block| block.path == ".pre-commit-config.yaml")
274 .map(|block| &block.marker_hash);
275 match (recorded, marker::block_hash(&config)) {
276 (None, _) => {
277 report.fail("FAIL manifest records no marker hash for .pre-commit-config.yaml");
278 }
279 (Some(recorded), Some(present)) if *recorded == present => {
280 if let Some(block) = marker::block_region(&config) {
281 check_block_entries(&block, report);
282 }
283 }
284 (Some(_), _) => report.fail("FAIL managed block tampered: .pre-commit-config.yaml"),
285 }
286 }
287 } else {
288 report.fail("FAIL missing .pre-commit-config.yaml");
289 }
290 Ok(())
291}
292
293fn check_specs(
294 target: &Utf8Path,
295 manifest: &Manifest,
296 report: &mut VerifyReport,
297) -> Result<(), AppError> {
298 let specs = target.join(manifest.docs_root.as_str()).join("specs");
299 if specs.is_dir() {
300 let mut counts = std::collections::BTreeMap::new();
301 let mut names: Vec<_> = specs
302 .read_dir_utf8()?
303 .filter_map(Result::ok)
304 .map(|entry| entry.file_name().to_string())
305 .filter(|name| {
306 #[allow(clippy::case_sensitive_file_extension_comparisons)]
308 name.ends_with(".md")
309 })
310 .collect();
311 names.sort();
312 for name in names {
313 let text = std::fs::read_to_string(specs.join(name))?;
314 for id in crate::embedded::rule_ids_in(&text) {
315 *counts.entry(id).or_insert(0usize) += 1;
316 }
317 }
318 let duplicated: Vec<String> = counts
319 .into_iter()
320 .filter(|(_, n)| *n > 1)
321 .map(|(id, _)| id)
322 .collect();
323 if !duplicated.is_empty() {
324 report.fail("FAIL duplicate rule ID in local specs");
325 for id in duplicated {
326 report.note(format!("### `{id}`"));
327 }
328 }
329 } else {
330 report.fail(format!(
331 "FAIL missing local specs: {}/specs",
332 manifest.docs_root
333 ));
334 }
335 Ok(())
336}