Skip to main content

spec_driven_docs/services/
verifier.rs

1//! Offline instance verification.
2//!
3//! Reads the manifest, compares every recorded projection to the disk, holds
4//! the managed block to its recorded hash, checks the block's `sdd` entries
5//! resolve, scans for duplicate rule IDs, and compares the instance's canon
6//! version to this binary's. Everything is local: no network, no canon
7//! checkout, no ambient tools. What gets recorded is the installer's
8//! business; this only holds the record to the disk.
9
10use 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/// What a verification run reports.
21#[derive(Debug, Default)]
22pub struct VerifyReport {
23    /// Every line to print, failures and notes alike, in order.
24    pub lines: Vec<String>,
25    /// How many lines are failures.
26    pub failures: usize,
27    /// How many managed files are missing, symlinked, or byte-drifted.
28    pub managed_drift: usize,
29    /// How many adopted files await reconciliation.
30    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
61/// Read the record of any schema this binary can read, with the older
62/// schema named where it is one.
63///
64/// # Errors
65///
66/// As [`read_manifest`], except that an older schema is read rather than
67/// refused.
68pub(crate) fn read_manifest_any(target: &Utf8Path) -> Result<(Manifest, Option<u32>), AppError> {
69    let path = target.join(MANIFEST_PATH);
70    if reached_through_symlink(target, Utf8Path::new(MANIFEST_PATH)) {
71        return Err(AppError::ManifestInvalid(
72            "manifest reached through a symlink".to_string(),
73        ));
74    }
75    if !path.is_file() {
76        return Err(AppError::ManifestMissing(path));
77    }
78    let text = std::fs::read_to_string(&path)?;
79    Manifest::parse_any(&text).map_err(|error| match error {
80        ManifestParseError::Invalid(detail) => AppError::ManifestInvalid(detail),
81        other => AppError::ManifestInvalid(other.to_string()),
82    })
83}
84
85fn check_block_entries(block: &str, report: &mut VerifyReport) {
86    let mut sdd_entries = 0usize;
87    for line in block.lines() {
88        let Some(entry) = line.trim_start().strip_prefix("entry: ") else {
89            continue;
90        };
91        let words: Vec<&str> = entry.split_whitespace().collect();
92        let Some(gate_position) = words.iter().position(|word| *word == "gate") else {
93            if words.last() == Some(&"verify") {
94                sdd_entries += 1;
95            }
96            continue;
97        };
98        sdd_entries += 1;
99        match words.get(gate_position + 1) {
100            Some(id) if id.parse::<GateId>().is_ok() => {}
101            Some(id) => report.fail(format!(
102                "FAIL managed block entry names an unknown gate: {id}"
103            )),
104            None => report.fail(format!("FAIL managed block entry names no gate: {entry}")),
105        }
106    }
107    if sdd_entries == 0 {
108        report.fail("FAIL managed block wires no sdd entry");
109    }
110}
111
112fn reached_through_symlink(target: &Utf8Path, destination: &Utf8Path) -> bool {
113    matches!(
114        check_destination(target, destination),
115        Err(DestinationRefusal::SymlinkEscape)
116    )
117}
118
119/// The declaration and the managed block must say the same thing.
120///
121/// The block is rendered from the declaration, so a difference means the
122/// project edited the declaration and nothing reached the block. That is a
123/// real disagreement between two artifacts that claim to agree, not drift in
124/// a file the project owns, so it fails and names the command that fixes it.
125///
126/// A declaration that does not parse fails once here rather than once from
127/// every always-run gate.
128fn check_declaration(target: &Utf8Path, manifest: &Manifest, report: &mut VerifyReport) {
129    let declaration = match crate::domain::instance_config::InstanceConfig::read(target) {
130        Ok(declaration) => declaration,
131        Err(error) => {
132            report.fail(format!("FAIL {error}"));
133            return;
134        }
135    };
136
137    // The documentation block carries the writing-style route the
138    // declaration selects, so a stale route is the same disagreement as a
139    // stale hook filter, and the same command repairs it.
140    let agents = target.join(crate::commands::hooks::AGENTS);
141    let agents_recorded = manifest
142        .integration_blocks
143        .iter()
144        .any(|block| block.path.as_str() == crate::commands::hooks::AGENTS);
145    if agents_recorded
146        && let Ok(host) = std::fs::read_to_string(&agents)
147        && let Some(region) = crate::domain::marker::block_region_with(
148            &host,
149            crate::domain::marker::AGENTS_BEGIN,
150            crate::domain::marker::AGENTS_END,
151        )
152    {
153        let expected = crate::services::agents_render::render_block(
154            manifest.docs_root.as_str(),
155            &declaration.writing_style,
156        );
157        if region != expected {
158            report.fail(format!(
159                "FAIL the documentation block in {} does not match the declaration; run 'sdd hooks --apply'",
160                crate::commands::hooks::AGENTS
161            ));
162        }
163    }
164
165    let config = target.join(crate::commands::hooks::CONFIG);
166    let Ok(host) = std::fs::read_to_string(&config) else {
167        return;
168    };
169    // Measure from the host stripped of its block, which is what the
170    // installer measures. With the block still in place the first item under
171    // `repos:` is the block's own, and the depth read back differs.
172    let Ok((base, _)) = crate::domain::marker::split_block(&host) else {
173        return;
174    };
175    // The indentation is the host file's, measured the same way the
176    // installer measures it. Rendering with the default would report every
177    // instance whose `repos:` items sit at another depth.
178    let Ok(indent) = crate::domain::marker::splice_indent(&base) else {
179        return;
180    };
181    let rendered = crate::services::hooks_render::render_block(
182        &crate::services::hooks_render::RenderOptions {
183            docs_root: manifest.docs_root.to_string(),
184            indent,
185            declaration,
186            ..crate::services::hooks_render::RenderOptions::default()
187        },
188    );
189    // Compare per gate rather than over the whole region. A block an older
190    // release rendered carries hooks this renderer no longer emits, and the
191    // upgrade rewrites those; what this names is the wiring a declaration
192    // edit left stale.
193    let expected = crate::services::hooks_render::selectors(&rendered);
194    let Some(region) = crate::domain::marker::block_region(&host) else {
195        return;
196    };
197    let found = crate::services::hooks_render::selectors(&region);
198    for (id, wanted) in &expected {
199        let Some(actual) = found.get(id) else {
200            continue;
201        };
202        if actual != wanted {
203            report.fail(format!(
204                "FAIL the wiring for {id} in {} does not match the declaration; run 'sdd hooks --apply'",
205                crate::commands::hooks::CONFIG
206            ));
207        }
208    }
209}
210
211/// The manifest must record every projection the profile declares, and
212/// every skill file the payload's inventory lands — an omitted record is an
213/// owned file the verifier would silently stop holding. Applies when the
214/// instance is at this binary's version. Every instance, this repository's
215/// own included, is held to the same obligations: every declared
216/// destination, every skill file, and both integration blocks.
217///
218/// SATISFIES release:the-canon-is-an-ordinary-instance
219///
220/// A seed that yields, and that the record does not name, is not owed:
221/// the target root held a file of its set, so the landing did not write it.
222fn check_projection_against(
223    released: &crate::domain::projection::Declaration,
224    manifest: &Manifest,
225    present_at_root: &[String],
226    report: &mut VerifyReport,
227) {
228    if manifest.canon_version != CanonVersion::current() {
229        return;
230    }
231    let Some(declaration) = released.profile(manifest.profile) else {
232        return;
233    };
234    let managed: std::collections::BTreeSet<&str> = manifest
235        .managed_files
236        .iter()
237        .map(|entry| entry.destination.as_str())
238        .collect();
239    let adopted: std::collections::BTreeSet<&str> = manifest
240        .adopted_files
241        .iter()
242        .map(|entry| entry.destination.as_str())
243        .collect();
244
245    let mut missing: Vec<String> = Vec::new();
246    for projection in declaration.managed {
247        let destination = crate::domain::profile::resolve_destination(
248            &projection.destination,
249            manifest.docs_root,
250        );
251        if !managed.contains(destination.as_str()) {
252            missing.push(destination.to_string());
253        }
254    }
255    match crate::embedded::skill_inventory() {
256        Ok(inventory) => {
257            for file in inventory {
258                if !managed.contains(file.destination.as_str()) {
259                    missing.push(file.destination);
260                }
261            }
262        }
263        Err(error) => report.fail(format!("FAIL the payload's skill inventory: {error}")),
264    }
265    for projection in declaration.adopted {
266        let destination = crate::domain::profile::resolve_destination(
267            &projection.destination,
268            manifest.docs_root,
269        );
270        if adopted.contains(destination.as_str()) {
271            continue;
272        }
273        let yielded = projection.yield_set().is_some_and(|set| {
274            set.names()
275                .any(|name| present_at_root.iter().any(|held| held == name))
276        });
277        if !yielded {
278            missing.push(destination.to_string());
279        }
280    }
281    for destination in missing {
282        report.fail(format!(
283            "FAIL manifest omits a declared projection: {destination}"
284        ));
285    }
286    // Every instance carries both integration blocks.
287    for path in [HOOKS_CONFIG_PATH, AGENTS_DIGEST_PATH] {
288        if !manifest
289            .integration_blocks
290            .iter()
291            .any(|block| block.path.as_str() == path)
292        {
293            report.fail(format!(
294                "FAIL manifest records no integration block for {path}"
295            ));
296        }
297    }
298}
299
300/// Verify an installed instance offline.
301///
302/// # Errors
303///
304/// [`AppError::ManifestMissing`] / [`AppError::ManifestInvalid`] when the
305/// record itself cannot be trusted, and I/O errors when the disk cannot be
306/// read; recorded-versus-disk differences are reported, not raised.
307pub fn verify(target: &Utf8Path) -> Result<VerifyReport, AppError> {
308    // An older schema is judged for what it records; the version gate
309    // warns that `sdd upgrade` moves it.
310    let (manifest, _) = read_manifest_any(target)?;
311    let released = &*crate::domain::profile::DECLARATION;
312    let mut report = VerifyReport::default();
313
314    check_declaration(target, &manifest, &mut report);
315
316    for entry in &manifest.managed_files {
317        let file = target.join(&entry.destination);
318        if reached_through_symlink(target, &entry.destination) {
319            report.managed_drift += 1;
320            report.fail(format!(
321                "FAIL managed file reached through a symlink: {}",
322                entry.destination
323            ));
324            continue;
325        }
326        if !file.is_file() {
327            report.managed_drift += 1;
328            report.fail(format!("FAIL missing managed file: {}", entry.destination));
329            continue;
330        }
331        if sha256_file(&file)? != entry.sha256 {
332            report.managed_drift += 1;
333            report.fail(format!("FAIL managed drift: {}", entry.destination));
334        }
335    }
336
337    for entry in &manifest.adopted_files {
338        let file = target.join(&entry.destination);
339        if reached_through_symlink(target, &entry.destination) {
340            report.fail(format!(
341                "FAIL adopted file reached through a symlink: {}",
342                entry.destination
343            ));
344            continue;
345        }
346        if !file.is_file() {
347            report.fail(format!("FAIL missing adopted file: {}", entry.destination));
348            continue;
349        }
350        if sha256_file(&file)? != entry.sha256 {
351            report.adopted_drift += 1;
352            report.note(format!(
353                "DRIFT adopted file requires reconciliation: {}",
354                entry.destination
355            ));
356        }
357    }
358
359    check_projection_against(
360        released,
361        &manifest,
362        &crate::services::installer::present_at_root(target),
363        &mut report,
364    );
365    check_integration(target, &manifest, &mut report)?;
366    check_specs(target, &manifest, &mut report)?;
367    check_lint_composition(target, &manifest, &mut report);
368    check_debt(target, &mut report);
369    for reconciliation in crate::services::policy::needed(target, manifest.docs_root)? {
370        report.note(reconciliation.note(manifest.docs_root));
371    }
372
373    // The version gate owns the version text: it refuses a record newer than
374    // this binary before verification runs, and warns on stderr where the
375    // binary is newer.
376    if report.failures == 0 {
377        report.note(format!(
378            "OK spec-driven-docs {} at {target}",
379            manifest.canon_version
380        ));
381    }
382    Ok(report)
383}
384
385/// Every markdownlint configuration that would replace the delivered one.
386///
387/// A `.markdownlint.*` file beside the documentation root's configuration
388/// replaces its `config`, and any configuration beneath `specs/` or
389/// `decisions/` replaces its `overrides` for that directory. Either one
390/// silently turns the heading shapes off. The repository root is allowed:
391/// a configuration there merges beneath the documentation root's, and it
392/// cannot disable the shapes. Only filenames are read, so no configuration
393/// grammar is parsed.
394///
395/// A symbolic link counts by its own name, because the linter reads a
396/// configuration through one. The scan skips a linked documentation root
397/// or subtree before reading beneath it, and [`linked_lint_scan_roots`]
398/// names it instead. The walk follows neither root nor nested links, so a
399/// linked directory is not descended and a cycle cannot hold it.
400///
401/// SATISFIES instance:the-lint-configuration-composes
402#[must_use]
403pub fn lint_configurations_that_break_composition(
404    target: &Utf8Path,
405    docs_root: crate::domain::profile::DocsRoot,
406) -> Vec<camino::Utf8PathBuf> {
407    use crate::domain::markdownlint::{LIBRARY_NAMES, discovery_names};
408
409    let root = Utf8Path::new(docs_root.as_str());
410    if reached_through_symlink(target, root) {
411        return Vec::new();
412    }
413    let mut found: Vec<camino::Utf8PathBuf> = LIBRARY_NAMES
414        .iter()
415        .map(|name| root.join(name))
416        .filter(|path| {
417            std::fs::symlink_metadata(target.join(path)).is_ok_and(|held| !held.is_dir())
418        })
419        .collect();
420    for subtree in ["specs", "decisions"] {
421        let subtree = root.join(subtree);
422        if reached_through_symlink(target, &subtree) {
423            continue;
424        }
425        for entry in walkdir::WalkDir::new(target.join(subtree))
426            .follow_links(false)
427            .follow_root_links(false)
428            .into_iter()
429            .filter_map(Result::ok)
430            .filter(|entry| !entry.file_type().is_dir())
431        {
432            let Some(name) = entry.file_name().to_str() else {
433                continue;
434            };
435            if !discovery_names().any(|known| known == name) {
436                continue;
437            }
438            if let Ok(relative) = entry.path().strip_prefix(target.as_std_path())
439                && let Some(relative) = camino::Utf8Path::from_path(relative)
440            {
441                found.push(relative.to_path_buf());
442            }
443        }
444    }
445    found.sort();
446    found
447}
448
449/// The documentation root or scan roots reached through a symbolic link.
450///
451/// The linter reads a configuration through the link, and the composition
452/// scan does not follow it, so such a directory is a place no check can see
453/// into. Naming it keeps the failure with the rule it breaks rather than
454/// leaving it to whichever ownership check happens to cover a recorded file
455/// beneath it. A linked documentation root is named alone, because both
456/// scan roots sit beneath it.
457///
458/// SATISFIES instance:the-lint-configuration-composes
459#[must_use]
460pub fn linked_lint_scan_roots(
461    target: &Utf8Path,
462    docs_root: crate::domain::profile::DocsRoot,
463) -> Vec<camino::Utf8PathBuf> {
464    let root = Utf8Path::new(docs_root.as_str());
465    if reached_through_symlink(target, root) {
466        return vec![root.to_path_buf()];
467    }
468    ["specs", "decisions"]
469        .into_iter()
470        .map(|subtree| root.join(subtree))
471        .filter(|subtree| reached_through_symlink(target, subtree))
472        .collect()
473}
474
475fn check_lint_composition(target: &Utf8Path, manifest: &Manifest, report: &mut VerifyReport) {
476    for path in linked_lint_scan_roots(target, manifest.docs_root) {
477        report.fail(format!(
478            "FAIL {path} is reached through a symlink, so no check sees the lint configuration beneath it; replace the link with the directory (instance:the-lint-configuration-composes)"
479        ));
480    }
481    for path in lint_configurations_that_break_composition(target, manifest.docs_root) {
482        report.fail(format!(
483            "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)"
484        ));
485    }
486}
487
488/// The debt file must be readable, and it must be the only debt format.
489///
490/// A file no budget gate can read fails once here rather than once from
491/// every budget gate. The legacy list alone is a note naming its migration:
492/// it still works, and nothing about it is wrong until the day the project
493/// wants a ceiling that only shrinks.
494fn check_debt(target: &Utf8Path, report: &mut VerifyReport) {
495    use crate::domain::debt::{Debt, LEGACY_DEBT_PATH, Presence};
496    let presence = Presence::at(target);
497    if let Err(error) = Debt::read(target) {
498        report.fail(format!("FAIL {error}"));
499        return;
500    }
501    if presence.legacy {
502        report.note(format!(
503            "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'"
504        ));
505    }
506}
507
508/// The marker pair a host file's managed region uses.
509fn markers_for(path: &str) -> (&'static str, &'static str) {
510    if path == HOOKS_CONFIG_PATH {
511        (marker::BEGIN, marker::END)
512    } else {
513        (marker::AGENTS_BEGIN, marker::AGENTS_END)
514    }
515}
516
517fn check_integration(
518    target: &Utf8Path,
519    manifest: &Manifest,
520    report: &mut VerifyReport,
521) -> Result<(), AppError> {
522    for block in &manifest.integration_blocks {
523        let path = block.path.as_str();
524        let (begin, end) = markers_for(path);
525        let full = target.join(&block.path);
526        if reached_through_symlink(target, &block.path) {
527            report.fail(format!("FAIL {path} reached through a symlink"));
528            continue;
529        }
530        if !full.is_file() {
531            report.fail(format!("FAIL missing integration host: {path}"));
532            continue;
533        }
534        let host = std::fs::read_to_string(&full)?;
535        let begins = host.lines().filter(|line| *line == begin).count();
536        let ends = host.lines().filter(|line| *line == end).count();
537        if begins != 1 {
538            report.fail(format!("FAIL missing managed block: {path}"));
539            continue;
540        }
541        if ends != 1 {
542            report.fail(format!("FAIL malformed managed block: {path}"));
543            continue;
544        }
545        match marker::block_hash_with(&host, begin, end) {
546            Some(present) if present == block.marker_hash => {
547                if path == HOOKS_CONFIG_PATH
548                    && let Some(region) = marker::block_region_with(&host, begin, end)
549                {
550                    check_block_entries(&region, report);
551                }
552            }
553            _ => report.fail(format!("FAIL managed block tampered: {path}")),
554        }
555    }
556    Ok(())
557}
558
559/// One failure per heading that follows a spec's requirements other than
560/// `## Unenforced`, the headings the `spec-trailing-section` gate fails on.
561fn fail_trailing_sections(path: &Utf8Path, text: &str, report: &mut VerifyReport) {
562    for finding in crate::gates::spec_trailing_section::judge(path.as_str(), text) {
563        if finding.rule == crate::domain::rule_id::RuleId::SpecFollowsTheHeadingShape {
564            report.fail(format!(
565                "FAIL {}:{} {} (docs-specs:a-spec-follows-the-heading-shape)",
566                path,
567                finding.line.unwrap_or_default(),
568                finding.detail
569            ));
570        }
571    }
572}
573
574fn check_specs(
575    target: &Utf8Path,
576    manifest: &Manifest,
577    report: &mut VerifyReport,
578) -> Result<(), AppError> {
579    let specs = target.join(manifest.docs_root.as_str()).join("specs");
580    if specs.is_dir() {
581        let mut counts = std::collections::BTreeMap::new();
582        let mut names: Vec<_> = specs
583            .read_dir_utf8()?
584            .filter_map(Result::ok)
585            .map(|entry| entry.file_name().to_string())
586            .filter(|name| {
587                #[allow(
588                    clippy::case_sensitive_file_extension_comparisons,
589                    reason = "the corpus convention is lowercase"
590                )]
591                name.ends_with(".md")
592            })
593            .collect();
594        names.sort();
595        for name in names {
596            let text = std::fs::read_to_string(specs.join(&name))?;
597            for id in crate::embedded::rule_ids_in(&text) {
598                *counts.entry(id).or_insert(0usize) += 1;
599            }
600            fail_trailing_sections(
601                &camino::Utf8PathBuf::from(format!("{}/specs/{name}", manifest.docs_root.as_str())),
602                &text,
603                report,
604            );
605        }
606        let duplicated: Vec<String> = counts
607            .into_iter()
608            .filter(|(_, n)| *n > 1)
609            .map(|(id, _)| id)
610            .collect();
611        if !duplicated.is_empty() {
612            report.fail("FAIL duplicate rule ID in local specs");
613            for id in duplicated {
614                report.note(format!("### `{id}`"));
615            }
616        }
617    } else {
618        report.fail(format!(
619            "FAIL missing local specs: {}/specs",
620            manifest.docs_root
621        ));
622    }
623    Ok(())
624}
625
626#[cfg(test)]
627mod tests {
628    #![allow(
629        clippy::unwrap_used,
630        reason = "a test panics as its failure signal, not as control flow"
631    )]
632
633    use super::*;
634    use crate::candidate::{Evidence, Input, project};
635    use crate::domain::ownership::{ManagedEntry, Sha256};
636    use crate::domain::profile::{DECLARATION, ProfileId};
637
638    fn consumer(profile: ProfileId) -> Manifest {
639        project(&Input {
640            profile,
641            version: CanonVersion::current(),
642            installed_at: "2026-01-01T00:00:00Z".to_string(),
643            docs_scratch: None,
644            reserve: Vec::new(),
645            writing_style: None,
646            acquisition: None,
647            evidence: Evidence::default(),
648        })
649        .unwrap()
650        .manifest
651    }
652
653    fn failures(manifest: &Manifest) -> Vec<String> {
654        let mut report = VerifyReport::default();
655        check_projection_against(&DECLARATION, manifest, &[], &mut report);
656        report.lines
657    }
658
659    fn managed(path: &str) -> ManagedEntry {
660        ManagedEntry {
661            source: path.into(),
662            destination: path.into(),
663            sha256: Sha256::of(path.as_bytes()),
664        }
665    }
666
667    /// VERIFIES instance:the-lint-configuration-composes
668    ///
669    /// Neither a linked scan root nor its documentation-root ancestor may
670    /// expose external configurations to the composition scan.
671    #[test]
672    fn the_lint_scan_does_not_follow_its_roots_or_their_ancestors() {
673        use crate::domain::profile::DocsRoot;
674
675        for docs_root in [DocsRoot::Docs, DocsRoot::UnderscoreDocs] {
676            for boundary in ["", "specs", "decisions"] {
677                let target = tempfile::tempdir().unwrap();
678                let target = Utf8Path::from_path(target.path()).unwrap();
679                let outside = tempfile::tempdir().unwrap();
680                // A linked documentation root could expose both the direct
681                // library configuration and either recursive scan.
682                for relative in [
683                    ".markdownlint.json",
684                    "specs/.markdownlint-cli2.jsonc",
685                    "decisions/.markdownlint.yaml",
686                ] {
687                    let path = outside.path().join(relative);
688                    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
689                    std::fs::write(path, "{}\n").unwrap();
690                }
691                let link = if boundary.is_empty() {
692                    target.join(docs_root.as_str())
693                } else {
694                    target.join(docs_root.as_str()).join(boundary)
695                };
696                std::fs::create_dir_all(link.parent().unwrap()).unwrap();
697                std::os::unix::fs::symlink(outside.path(), &link).unwrap();
698
699                assert!(
700                    lint_configurations_that_break_composition(target, docs_root).is_empty(),
701                    "{docs_root}/{boundary}: the scan followed a directory link"
702                );
703                let linked = if boundary.is_empty() {
704                    camino::Utf8PathBuf::from(docs_root.as_str())
705                } else {
706                    Utf8Path::new(docs_root.as_str()).join(boundary)
707                };
708                assert_eq!(linked_lint_scan_roots(target, docs_root), [linked]);
709            }
710        }
711    }
712
713    /// VERIFIES instance:the-lint-configuration-composes
714    #[test]
715    fn the_lint_scan_skips_nested_directory_links_and_cycles() {
716        use crate::domain::profile::DocsRoot;
717
718        for docs_root in [DocsRoot::Docs, DocsRoot::UnderscoreDocs] {
719            let target = tempfile::tempdir().unwrap();
720            let target = Utf8Path::from_path(target.path()).unwrap();
721            let specs = target.join(docs_root.as_str()).join("specs");
722            std::fs::create_dir_all(&specs).unwrap();
723            let outside = tempfile::tempdir().unwrap();
724            std::fs::write(outside.path().join(".markdownlint-cli2.jsonc"), "{}\n").unwrap();
725            std::os::unix::fs::symlink(outside.path(), specs.join("linked")).unwrap();
726            std::os::unix::fs::symlink(&specs, specs.join("cycle")).unwrap();
727            // Skipping linked directories must still count a configuration
728            // link by its own filename, even where its target is absent.
729            let config = specs.join(".markdownlint.yaml");
730            std::os::unix::fs::symlink(outside.path().join("absent.yaml"), &config).unwrap();
731
732            assert_eq!(
733                lint_configurations_that_break_composition(target, docs_root),
734                [config.strip_prefix(target).unwrap()]
735            );
736            // A link nested inside a scan root is not a linked scan root.
737            assert!(linked_lint_scan_roots(target, docs_root).is_empty());
738        }
739    }
740
741    /// A knowledge-base record whose managed destinations equal their
742    /// sources satisfied the old discriminator, which then demanded the
743    /// canon's specs and templates and dropped the `AGENTS.md` block.
744    #[test]
745    fn a_consumer_whose_managed_destination_equals_its_source_is_still_a_consumer() {
746        let mut manifest = consumer(ProfileId::KnowledgeBase);
747        for projection in &DECLARATION.managed {
748            if !manifest
749                .managed_files
750                .iter()
751                .any(|entry| entry.destination == projection.source.as_str())
752            {
753                manifest.managed_files.push(managed(&projection.source));
754            }
755        }
756        assert!(failures(&manifest).is_empty(), "{:?}", failures(&manifest));
757
758        let mut without_block = manifest.clone();
759        without_block
760            .integration_blocks
761            .retain(|block| block.path != AGENTS_DIGEST_PATH);
762        assert!(
763            failures(&without_block)
764                .iter()
765                .any(|line| line.contains("no integration block for AGENTS.md")),
766            "{:?}",
767            failures(&without_block)
768        );
769
770        let mut without_seed = manifest;
771        let dropped = without_seed.adopted_files.remove(1).destination;
772        assert!(
773            failures(&without_seed)
774                .iter()
775                .any(|line| line.ends_with(dropped.as_str())),
776            "{:?}",
777            failures(&without_seed)
778        );
779    }
780
781    /// VERIFIES release:the-canon-is-an-ordinary-instance
782    ///
783    /// This repository's own record is held like any instance's: it owes
784    /// every skill entry and both integration blocks.
785    #[test]
786    fn verify_holds_the_canon_to_the_instance_obligations() {
787        let text =
788            std::fs::read_to_string(Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join(MANIFEST_PATH))
789                .unwrap();
790        let mut manifest = Manifest::parse(&text).unwrap();
791        manifest.canon_version = CanonVersion::current();
792        // This repository keeps its own root lint configuration, so the root
793        // seed yielded, as it does in any instance that holds one.
794        let failures = |manifest: &Manifest| {
795            let mut report = VerifyReport::default();
796            check_projection_against(
797                &DECLARATION,
798                manifest,
799                &[".markdownlint-cli2.jsonc".to_string()],
800                &mut report,
801            );
802            report.lines
803        };
804        assert!(failures(&manifest).is_empty(), "{:?}", failures(&manifest));
805
806        let mut without_skill = manifest.clone();
807        without_skill
808            .managed_files
809            .retain(|entry| entry.destination != ".claude/skills/sdd-setup/SKILL.md");
810        assert!(
811            failures(&without_skill).iter().any(|line| line
812                == "FAIL manifest omits a declared projection: .claude/skills/sdd-setup/SKILL.md"),
813            "{:?}",
814            failures(&without_skill)
815        );
816
817        let mut without_block = manifest;
818        without_block
819            .integration_blocks
820            .retain(|block| block.path != AGENTS_DIGEST_PATH);
821        assert!(
822            failures(&without_block)
823                .iter()
824                .any(|line| line.contains("no integration block for AGENTS.md")),
825            "{:?}",
826            failures(&without_block)
827        );
828    }
829
830    #[test]
831    fn a_consumer_omitting_a_declared_seed_fails() {
832        let mut manifest = consumer(ProfileId::Codebase);
833        let dropped = manifest.adopted_files.pop().unwrap().destination;
834        let lines = failures(&manifest);
835        assert!(
836            lines.contains(&format!(
837                "FAIL manifest omits a declared projection: {dropped}"
838            )),
839            "{lines:?}"
840        );
841    }
842
843    /// No entry moves a record to other obligations: a record carrying a
844    /// managed entry under `skill-shared/` still owes the AGENTS.md block.
845    #[test]
846    fn no_entry_selects_another_layout() {
847        let mut manifest = consumer(ProfileId::KnowledgeBase);
848        manifest
849            .integration_blocks
850            .retain(|block| block.path != AGENTS_DIGEST_PATH);
851        manifest
852            .managed_files
853            .push(managed("skill-shared/plan-gate.md"));
854        let lines = failures(&manifest);
855        assert!(
856            lines
857                .iter()
858                .any(|line| line.contains("no integration block for AGENTS.md")),
859            "{lines:?}"
860        );
861    }
862
863    #[test]
864    fn a_yielded_seed_the_record_does_not_name_is_not_owed() {
865        let Some(yielding) = DECLARATION
866            .adopted
867            .iter()
868            .find(|projection| projection.yield_set().is_some())
869        else {
870            return;
871        };
872        let mut manifest = consumer(ProfileId::Codebase);
873        let destination =
874            crate::domain::profile::resolve_destination(&yielding.destination, manifest.docs_root);
875        manifest
876            .adopted_files
877            .retain(|entry| entry.destination != destination);
878        assert!(!failures(&manifest).is_empty());
879
880        let mut report = VerifyReport::default();
881        let cause = yielding
882            .yield_set()
883            .unwrap()
884            .names()
885            .last()
886            .unwrap()
887            .to_string();
888        check_projection_against(&DECLARATION, &manifest, &[cause], &mut report);
889        assert!(report.lines.is_empty(), "{:?}", report.lines);
890    }
891}