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::paths::{AGENTS_DIGEST_PATH, HOOKS_CONFIG_PATH};
17use crate::domain::version::CanonVersion;
18use crate::error::AppError;
19
20#[derive(Debug, Default)]
22pub struct VerifyReport {
23 pub lines: Vec<String>,
25 pub failures: usize,
27 pub managed_drift: usize,
29 pub adopted_drift: usize,
31}
32
33impl VerifyReport {
34 fn fail(&mut self, line: impl Into<String>) {
35 self.lines.push(line.into());
36 self.failures += 1;
37 }
38
39 fn note(&mut self, line: impl Into<String>) {
40 self.lines.push(line.into());
41 }
42}
43
44pub(crate) fn read_manifest(target: &Utf8Path) -> Result<Manifest, AppError> {
45 let path = target.join(MANIFEST_PATH);
46 if reached_through_symlink(target, Utf8Path::new(MANIFEST_PATH)) {
47 return Err(AppError::ManifestInvalid(
48 "manifest reached through a symlink".to_string(),
49 ));
50 }
51 if !path.is_file() {
52 return Err(AppError::ManifestMissing(path));
53 }
54 let text = std::fs::read_to_string(&path)?;
55 Manifest::parse(&text).map_err(|error| match error {
56 ManifestParseError::Invalid(detail) => AppError::ManifestInvalid(detail),
57 other => AppError::ManifestInvalid(other.to_string()),
58 })
59}
60
61fn check_block_entries(block: &str, report: &mut VerifyReport) {
62 let mut sdd_entries = 0usize;
63 for line in block.lines() {
64 let Some(entry) = line.trim_start().strip_prefix("entry: ") else {
65 continue;
66 };
67 let words: Vec<&str> = entry.split_whitespace().collect();
68 let Some(gate_position) = words.iter().position(|word| *word == "gate") else {
69 if words.last() == Some(&"verify") {
70 sdd_entries += 1;
71 }
72 continue;
73 };
74 sdd_entries += 1;
75 match words.get(gate_position + 1) {
76 Some(id) if id.parse::<GateId>().is_ok() => {}
77 Some(id) => report.fail(format!(
78 "FAIL managed block entry names an unknown gate: {id}"
79 )),
80 None => report.fail(format!("FAIL managed block entry names no gate: {entry}")),
81 }
82 }
83 if sdd_entries == 0 {
84 report.fail("FAIL managed block wires no sdd entry");
85 }
86}
87
88fn reached_through_symlink(target: &Utf8Path, destination: &Utf8Path) -> bool {
89 matches!(
90 check_destination(target, destination),
91 Err(DestinationRefusal::SymlinkEscape)
92 )
93}
94
95fn check_declaration(target: &Utf8Path, manifest: &Manifest, report: &mut VerifyReport) {
105 let declaration = match crate::domain::instance_config::InstanceConfig::read(target) {
106 Ok(declaration) => declaration,
107 Err(error) => {
108 report.fail(format!("FAIL {error}"));
109 return;
110 }
111 };
112
113 let agents = target.join(crate::commands::hooks::AGENTS);
117 let agents_recorded = manifest
118 .integration_blocks
119 .iter()
120 .any(|block| block.path.as_str() == crate::commands::hooks::AGENTS);
121 if agents_recorded
122 && let Ok(host) = std::fs::read_to_string(&agents)
123 && let Some(region) = crate::domain::marker::block_region_with(
124 &host,
125 crate::domain::marker::AGENTS_BEGIN,
126 crate::domain::marker::AGENTS_END,
127 )
128 {
129 let expected = crate::services::agents_render::render_block(
130 manifest.docs_root.as_str(),
131 &declaration.writing_style,
132 );
133 if region != expected {
134 report.fail(format!(
135 "FAIL the documentation block in {} does not match the declaration; run 'sdd hooks --apply'",
136 crate::commands::hooks::AGENTS
137 ));
138 }
139 }
140
141 let config = target.join(crate::commands::hooks::CONFIG);
142 let Ok(host) = std::fs::read_to_string(&config) else {
143 return;
144 };
145 let Ok((base, _)) = crate::domain::marker::split_block(&host) else {
149 return;
150 };
151 let Ok(indent) = crate::domain::marker::splice_indent(&base) else {
155 return;
156 };
157 let rendered = crate::services::hooks_render::render_block(
158 &crate::services::hooks_render::RenderOptions {
159 docs_root: manifest.docs_root.to_string(),
160 indent,
161 declaration,
162 ..crate::services::hooks_render::RenderOptions::default()
163 },
164 );
165 let expected = crate::services::hooks_render::selectors(&rendered);
170 let Some(region) = crate::domain::marker::block_region(&host) else {
171 return;
172 };
173 let found = crate::services::hooks_render::selectors(®ion);
174 for (id, wanted) in &expected {
175 let Some(actual) = found.get(id) else {
176 continue;
177 };
178 if actual != wanted {
179 report.fail(format!(
180 "FAIL the wiring for {id} in {} does not match the declaration; run 'sdd hooks --apply'",
181 crate::commands::hooks::CONFIG
182 ));
183 }
184 }
185}
186
187const CANON_ONLY_ROOT: &str = "skill-shared/";
193
194fn check_projection_against(
212 released: &crate::domain::projection::Declaration,
213 manifest: &Manifest,
214 present_at_root: &[String],
215 report: &mut VerifyReport,
216) {
217 if manifest.canon_version != CanonVersion::current() {
218 return;
219 }
220 let Some(declaration) = released.profile(manifest.profile) else {
221 return;
222 };
223 let managed: std::collections::BTreeSet<&str> = manifest
224 .managed_files
225 .iter()
226 .map(|entry| entry.destination.as_str())
227 .collect();
228 let adopted: std::collections::BTreeSet<&str> = manifest
229 .adopted_files
230 .iter()
231 .map(|entry| entry.destination.as_str())
232 .collect();
233
234 let self_layout = managed
235 .iter()
236 .any(|destination| destination.starts_with(CANON_ONLY_ROOT));
237
238 let mut expected: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
239 let mut missing: Vec<String> = Vec::new();
240 if self_layout {
241 for projection in declaration.managed {
242 expected.insert(projection.source.clone());
243 }
244 for file in crate::embedded::SPECS.files() {
245 if let Some(name) = file.path().as_os_str().to_str() {
246 expected.insert(format!("_docs/specs/{name}"));
247 }
248 }
249 for template in crate::domain::profile::CANON_TEMPLATES.iter() {
250 expected.insert((*template).to_string());
251 }
252 for destination in &expected {
253 if !managed.contains(destination.as_str()) && !adopted.contains(destination.as_str()) {
254 missing.push(destination.clone());
255 }
256 }
257 } else {
258 for projection in declaration.managed {
259 let destination = crate::domain::profile::resolve_destination(
260 &projection.destination,
261 manifest.docs_root,
262 );
263 if !managed.contains(destination.as_str()) {
264 missing.push(destination.to_string());
265 }
266 }
267 for projection in declaration.adopted {
268 let destination = crate::domain::profile::resolve_destination(
269 &projection.destination,
270 manifest.docs_root,
271 );
272 if adopted.contains(destination.as_str()) {
273 continue;
274 }
275 let yielded = projection.yield_set().is_some_and(|set| {
276 set.names()
277 .any(|name| present_at_root.iter().any(|held| held == name))
278 });
279 if !yielded {
280 missing.push(destination.to_string());
281 }
282 }
283 }
284 for destination in missing {
285 report.fail(format!(
286 "FAIL manifest omits a declared projection: {destination}"
287 ));
288 }
289 let required: &[&str] = if self_layout {
293 &[HOOKS_CONFIG_PATH]
294 } else {
295 &[HOOKS_CONFIG_PATH, AGENTS_DIGEST_PATH]
296 };
297 for path in required {
298 if !manifest
299 .integration_blocks
300 .iter()
301 .any(|block| block.path.as_str() == *path)
302 {
303 report.fail(format!(
304 "FAIL manifest records no integration block for {path}"
305 ));
306 }
307 }
308}
309
310pub fn verify(target: &Utf8Path) -> Result<VerifyReport, AppError> {
318 let manifest = read_manifest(target)?;
319 let released = &*crate::domain::profile::DECLARATION;
320 let mut report = VerifyReport::default();
321
322 check_declaration(target, &manifest, &mut report);
323
324 for entry in &manifest.managed_files {
325 let file = target.join(&entry.destination);
326 if reached_through_symlink(target, &entry.destination) {
327 report.managed_drift += 1;
328 report.fail(format!(
329 "FAIL managed file reached through a symlink: {}",
330 entry.destination
331 ));
332 continue;
333 }
334 if !file.is_file() {
335 report.managed_drift += 1;
336 report.fail(format!("FAIL missing managed file: {}", entry.destination));
337 continue;
338 }
339 if sha256_file(&file)? != entry.sha256 {
340 report.managed_drift += 1;
341 report.fail(format!("FAIL managed drift: {}", entry.destination));
342 }
343 }
344
345 for entry in &manifest.adopted_files {
346 let file = target.join(&entry.destination);
347 if reached_through_symlink(target, &entry.destination) {
348 report.fail(format!(
349 "FAIL adopted file reached through a symlink: {}",
350 entry.destination
351 ));
352 continue;
353 }
354 if !file.is_file() {
355 report.fail(format!("FAIL missing adopted file: {}", entry.destination));
356 continue;
357 }
358 if sha256_file(&file)? != entry.sha256 {
359 report.adopted_drift += 1;
360 report.note(format!(
361 "DRIFT adopted file requires reconciliation: {}",
362 entry.destination
363 ));
364 }
365 }
366
367 check_projection_against(
368 released,
369 &manifest,
370 &crate::services::installer::present_at_root(target),
371 &mut report,
372 );
373 check_integration(target, &manifest, &mut report)?;
374 check_specs(target, &manifest, &mut report)?;
375 check_lint_composition(target, &manifest, &mut report);
376 check_debt(target, &mut report);
377 for reconciliation in crate::services::policy::needed(target, manifest.docs_root)? {
378 report.note(reconciliation.note(manifest.docs_root));
379 }
380
381 let current = CanonVersion::current();
382 if manifest.canon_version > current {
383 report.fail(format!(
384 "FAIL sdd {current} is older than the installed canon {}; upgrade sdd",
385 manifest.canon_version
386 ));
387 } else if manifest.canon_version < current {
388 report.note(format!(
389 "note: sdd {current} is newer than the installed canon {}; run 'sdd upgrade'",
390 manifest.canon_version
391 ));
392 }
393
394 if report.failures == 0 {
395 report.note(format!(
396 "OK spec-driven-docs {} at {target}",
397 manifest.canon_version
398 ));
399 }
400 Ok(report)
401}
402
403#[must_use]
419pub fn lint_configurations_that_break_composition(
420 target: &Utf8Path,
421 docs_root: crate::domain::profile::DocsRoot,
422) -> Vec<camino::Utf8PathBuf> {
423 use crate::domain::markdownlint::{LIBRARY_NAMES, discovery_names};
424
425 let root = Utf8Path::new(docs_root.as_str());
426 let mut found: Vec<camino::Utf8PathBuf> = LIBRARY_NAMES
427 .iter()
428 .map(|name| root.join(name))
429 .filter(|path| {
430 std::fs::symlink_metadata(target.join(path)).is_ok_and(|held| !held.is_dir())
431 })
432 .collect();
433 for subtree in ["specs", "decisions"] {
434 for entry in walkdir::WalkDir::new(target.join(root).join(subtree))
435 .follow_links(false)
436 .into_iter()
437 .filter_map(Result::ok)
438 .filter(|entry| !entry.file_type().is_dir())
439 {
440 let Some(name) = entry.file_name().to_str() else {
441 continue;
442 };
443 if !discovery_names().any(|known| known == name) {
444 continue;
445 }
446 if let Ok(relative) = entry.path().strip_prefix(target.as_std_path())
447 && let Some(relative) = camino::Utf8Path::from_path(relative)
448 {
449 found.push(relative.to_path_buf());
450 }
451 }
452 }
453 found.sort();
454 found
455}
456
457fn check_lint_composition(target: &Utf8Path, manifest: &Manifest, report: &mut VerifyReport) {
458 for path in lint_configurations_that_break_composition(target, manifest.docs_root) {
459 report.fail(format!(
460 "FAIL {path} replaces the delivered lint configuration and turns the heading shapes off; fold it into the root .markdownlint-cli2.jsonc (instance:the-lint-configuration-composes)"
461 ));
462 }
463}
464
465fn check_debt(target: &Utf8Path, report: &mut VerifyReport) {
472 use crate::domain::debt::{Debt, LEGACY_DEBT_PATH, Presence};
473 let presence = Presence::at(target);
474 if let Err(error) = Debt::read(target) {
475 report.fail(format!("FAIL {error}"));
476 return;
477 }
478 if presence.legacy {
479 report.note(format!(
480 "note: {LEGACY_DEBT_PATH} is the legacy debt list, which skips a listed chapter instead of holding it to a ceiling; run 'sdd debt migrate --apply'"
481 ));
482 }
483}
484
485fn markers_for(path: &str) -> (&'static str, &'static str) {
487 if path == HOOKS_CONFIG_PATH {
488 (marker::BEGIN, marker::END)
489 } else {
490 (marker::AGENTS_BEGIN, marker::AGENTS_END)
491 }
492}
493
494fn check_integration(
495 target: &Utf8Path,
496 manifest: &Manifest,
497 report: &mut VerifyReport,
498) -> Result<(), AppError> {
499 for block in &manifest.integration_blocks {
500 let path = block.path.as_str();
501 let (begin, end) = markers_for(path);
502 let full = target.join(&block.path);
503 if reached_through_symlink(target, &block.path) {
504 report.fail(format!("FAIL {path} reached through a symlink"));
505 continue;
506 }
507 if !full.is_file() {
508 report.fail(format!("FAIL missing integration host: {path}"));
509 continue;
510 }
511 let host = std::fs::read_to_string(&full)?;
512 let begins = host.lines().filter(|line| *line == begin).count();
513 let ends = host.lines().filter(|line| *line == end).count();
514 if begins != 1 {
515 report.fail(format!("FAIL missing managed block: {path}"));
516 continue;
517 }
518 if ends != 1 {
519 report.fail(format!("FAIL malformed managed block: {path}"));
520 continue;
521 }
522 match marker::block_hash_with(&host, begin, end) {
523 Some(present) if present == block.marker_hash => {
524 if path == HOOKS_CONFIG_PATH
525 && let Some(region) = marker::block_region_with(&host, begin, end)
526 {
527 check_block_entries(®ion, report);
528 }
529 }
530 _ => report.fail(format!("FAIL managed block tampered: {path}")),
531 }
532 }
533 Ok(())
534}
535
536fn check_specs(
537 target: &Utf8Path,
538 manifest: &Manifest,
539 report: &mut VerifyReport,
540) -> Result<(), AppError> {
541 let specs = target.join(manifest.docs_root.as_str()).join("specs");
542 if specs.is_dir() {
543 let mut counts = std::collections::BTreeMap::new();
544 let mut names: Vec<_> = specs
545 .read_dir_utf8()?
546 .filter_map(Result::ok)
547 .map(|entry| entry.file_name().to_string())
548 .filter(|name| {
549 #[allow(
550 clippy::case_sensitive_file_extension_comparisons,
551 reason = "the corpus convention is lowercase"
552 )]
553 name.ends_with(".md")
554 })
555 .collect();
556 names.sort();
557 for name in names {
558 let text = std::fs::read_to_string(specs.join(name))?;
559 for id in crate::embedded::rule_ids_in(&text) {
560 *counts.entry(id).or_insert(0usize) += 1;
561 }
562 }
563 let duplicated: Vec<String> = counts
564 .into_iter()
565 .filter(|(_, n)| *n > 1)
566 .map(|(id, _)| id)
567 .collect();
568 if !duplicated.is_empty() {
569 report.fail("FAIL duplicate rule ID in local specs");
570 for id in duplicated {
571 report.note(format!("### `{id}`"));
572 }
573 }
574 } else {
575 report.fail(format!(
576 "FAIL missing local specs: {}/specs",
577 manifest.docs_root
578 ));
579 }
580 Ok(())
581}
582
583#[cfg(test)]
584mod tests {
585 #![allow(
586 clippy::unwrap_used,
587 reason = "a test panics as its failure signal, not as control flow"
588 )]
589
590 use super::*;
591 use crate::candidate::{Evidence, Input, project};
592 use crate::domain::ownership::{ManagedEntry, Sha256};
593 use crate::domain::profile::{DECLARATION, ProfileId};
594
595 fn consumer(profile: ProfileId) -> Manifest {
596 project(&Input {
597 profile,
598 version: CanonVersion::current(),
599 installed_at: "2026-01-01T00:00:00Z".to_string(),
600 docs_scratch: None,
601 reserve: Vec::new(),
602 writing_style: None,
603 evidence: Evidence::default(),
604 })
605 .unwrap()
606 .manifest
607 }
608
609 fn failures(manifest: &Manifest) -> Vec<String> {
610 let mut report = VerifyReport::default();
611 check_projection_against(&DECLARATION, manifest, &[], &mut report);
612 report.lines
613 }
614
615 fn managed(path: &str) -> ManagedEntry {
616 ManagedEntry {
617 source: path.into(),
618 destination: path.into(),
619 sha256: Sha256::of(path.as_bytes()),
620 }
621 }
622
623 #[test]
627 fn a_consumer_whose_managed_destination_equals_its_source_is_still_a_consumer() {
628 let mut manifest = consumer(ProfileId::KnowledgeBase);
629 for projection in &DECLARATION.managed {
630 if !manifest
631 .managed_files
632 .iter()
633 .any(|entry| entry.destination == projection.source.as_str())
634 {
635 manifest.managed_files.push(managed(&projection.source));
636 }
637 }
638 assert!(failures(&manifest).is_empty(), "{:?}", failures(&manifest));
639
640 let mut without_block = manifest.clone();
641 without_block
642 .integration_blocks
643 .retain(|block| block.path != AGENTS_DIGEST_PATH);
644 assert!(
645 failures(&without_block)
646 .iter()
647 .any(|line| line.contains("no integration block for AGENTS.md")),
648 "{:?}",
649 failures(&without_block)
650 );
651
652 let mut without_seed = manifest;
653 let dropped = without_seed.adopted_files.remove(1).destination;
654 assert!(
655 failures(&without_seed)
656 .iter()
657 .any(|line| line.ends_with(dropped.as_str())),
658 "{:?}",
659 failures(&without_seed)
660 );
661 }
662
663 #[test]
664 fn the_canon_record_is_read_as_the_canon() {
665 let text =
666 std::fs::read_to_string(Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join(MANIFEST_PATH))
667 .unwrap();
668 let mut manifest = Manifest::parse(&text).unwrap();
669 manifest.canon_version = CanonVersion::current();
670 assert!(failures(&manifest).is_empty(), "{:?}", failures(&manifest));
671 }
672
673 #[test]
674 fn a_consumer_omitting_a_declared_seed_fails() {
675 let mut manifest = consumer(ProfileId::Codebase);
676 let dropped = manifest.adopted_files.pop().unwrap().destination;
677 let lines = failures(&manifest);
678 assert!(
679 lines.contains(&format!(
680 "FAIL manifest omits a declared projection: {dropped}"
681 )),
682 "{lines:?}"
683 );
684 }
685
686 #[test]
690 fn a_claimed_canon_layout_changes_which_obligations_are_held() {
691 let mut manifest = consumer(ProfileId::KnowledgeBase);
692 manifest
693 .integration_blocks
694 .retain(|block| block.path != AGENTS_DIGEST_PATH);
695 manifest
696 .managed_files
697 .push(managed("skill-shared/plan-gate.md"));
698 let lines = failures(&manifest);
699 assert!(
700 lines
701 .iter()
702 .any(|line| line
703 .contains("omits a declared projection: _docs/specs/SPEC-release.md")),
704 "the canon branch owes the canon-only specs: {lines:?}"
705 );
706
707 for projection in &DECLARATION.managed {
708 manifest.managed_files.push(managed(&projection.source));
709 }
710 for file in crate::embedded::SPECS.files() {
711 let name = file.path().to_str().unwrap();
712 manifest
713 .managed_files
714 .push(managed(&format!("_docs/specs/{name}")));
715 }
716 for template in crate::domain::profile::CANON_TEMPLATES.iter() {
717 manifest.managed_files.push(managed(template));
718 }
719 let lines = failures(&manifest);
720 assert!(lines.is_empty(), "{lines:?}");
721 }
722
723 #[test]
724 fn a_yielded_seed_the_record_does_not_name_is_not_owed() {
725 let Some(yielding) = DECLARATION
726 .adopted
727 .iter()
728 .find(|projection| projection.yield_set().is_some())
729 else {
730 return;
731 };
732 let mut manifest = consumer(ProfileId::Codebase);
733 let destination =
734 crate::domain::profile::resolve_destination(&yielding.destination, manifest.docs_root);
735 manifest
736 .adopted_files
737 .retain(|entry| entry.destination != destination);
738 assert!(!failures(&manifest).is_empty());
739
740 let mut report = VerifyReport::default();
741 let cause = yielding
742 .yield_set()
743 .unwrap()
744 .names()
745 .last()
746 .unwrap()
747 .to_string();
748 check_projection_against(&DECLARATION, &manifest, &[cause], &mut report);
749 assert!(report.lines.is_empty(), "{:?}", report.lines);
750 }
751}