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
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
95/// The declaration and the managed block must say the same thing.
96///
97/// The block is rendered from the declaration, so a difference means the
98/// project edited the declaration and nothing reached the block. That is a
99/// real disagreement between two artifacts that claim to agree, not drift in
100/// a file the project owns, so it fails and names the command that fixes it.
101///
102/// A declaration that does not parse fails once here rather than once from
103/// every always-run gate.
104fn 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    // The documentation block carries the writing-style route the
114    // declaration selects, so a stale route is the same disagreement as a
115    // stale hook filter, and the same command repairs it.
116    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    // Measure from the host stripped of its block, which is what the
146    // installer measures. With the block still in place the first item under
147    // `repos:` is the block's own, and the depth read back differs.
148    let Ok((base, _)) = crate::domain::marker::split_block(&host) else {
149        return;
150    };
151    // The indentation is the host file's, measured the same way the
152    // installer measures it. Rendering with the default would report every
153    // instance whose `repos:` items sit at another depth.
154    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    // Compare per gate rather than over the whole region. A block an older
166    // release rendered carries hooks this renderer no longer emits, and the
167    // upgrade rewrites those; what this names is the wiring a declaration
168    // edit left stale.
169    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(&region);
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
187/// Where the canon's own record keeps the artifacts every skill shares.
188///
189/// `sdd self-manifest` records them as managed entries at their authored
190/// paths, and no consumer landing writes anything there, so their presence
191/// is what tells the two layouts apart.
192const CANON_ONLY_ROOT: &str = "skill-shared/";
193
194/// The manifest must record every projection the profile declares — an
195/// omitted record is an owned file the verifier would silently stop
196/// holding. Applies when the instance is at this binary's version, in
197/// whichever of the two layouts the record claims.
198///
199/// The layout is read from what only the canon's self-manifest records: a
200/// managed entry under `skill-shared/`. That recognizes the ordinary canon
201/// and consumer records. It authenticates nothing, because the record is a
202/// file a user can edit, and changing the claimed layout changes which
203/// obligations this check enforces. The canon branch requires the managed
204/// projection sources, the embedded specs, the canon templates, and the
205/// pre-commit block. The consumer branch requires every declared
206/// destination and both integration blocks. Neither set contains the
207/// other, and the canon branch does not require the whole skill inventory.
208///
209/// A seed that yields, and that the record does not name, is not owed:
210/// the target root held a file of its set, so the landing did not write it.
211fn 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    // Every installed instance carries both integration blocks. The canon's
290    // own layout carries the pre-commit block, which `just hooks` renders;
291    // its root AGENTS.md is release-kit-owned and outside this projection.
292    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
310/// Verify an installed instance offline.
311///
312/// # Errors
313///
314/// [`AppError::ManifestMissing`] / [`AppError::ManifestInvalid`] when the
315/// record itself cannot be trusted, and I/O errors when the disk cannot be
316/// read; recorded-versus-disk differences are reported, not raised.
317pub 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/// Every markdownlint configuration that would replace the delivered one.
404///
405/// A `.markdownlint.*` file beside the documentation root's configuration
406/// replaces its `config`, and any configuration beneath `specs/` or
407/// `decisions/` replaces its `overrides` for that directory. Either one
408/// silently turns the heading shapes off. The repository root is allowed:
409/// a configuration there merges beneath the documentation root's, and it
410/// cannot disable the shapes. Only filenames are read, so no configuration
411/// grammar is parsed.
412///
413/// A symbolic link counts by its own name, because the linter reads a
414/// configuration through one. The scan skips a linked documentation root
415/// or subtree before reading beneath it, and [`linked_lint_scan_roots`]
416/// names it instead. The walk follows neither root nor nested links, so a
417/// linked directory is not descended and a cycle cannot hold it.
418///
419/// SATISFIES instance:the-lint-configuration-composes
420#[must_use]
421pub fn lint_configurations_that_break_composition(
422    target: &Utf8Path,
423    docs_root: crate::domain::profile::DocsRoot,
424) -> Vec<camino::Utf8PathBuf> {
425    use crate::domain::markdownlint::{LIBRARY_NAMES, discovery_names};
426
427    let root = Utf8Path::new(docs_root.as_str());
428    if reached_through_symlink(target, root) {
429        return Vec::new();
430    }
431    let mut found: Vec<camino::Utf8PathBuf> = LIBRARY_NAMES
432        .iter()
433        .map(|name| root.join(name))
434        .filter(|path| {
435            std::fs::symlink_metadata(target.join(path)).is_ok_and(|held| !held.is_dir())
436        })
437        .collect();
438    for subtree in ["specs", "decisions"] {
439        let subtree = root.join(subtree);
440        if reached_through_symlink(target, &subtree) {
441            continue;
442        }
443        for entry in walkdir::WalkDir::new(target.join(subtree))
444            .follow_links(false)
445            .follow_root_links(false)
446            .into_iter()
447            .filter_map(Result::ok)
448            .filter(|entry| !entry.file_type().is_dir())
449        {
450            let Some(name) = entry.file_name().to_str() else {
451                continue;
452            };
453            if !discovery_names().any(|known| known == name) {
454                continue;
455            }
456            if let Ok(relative) = entry.path().strip_prefix(target.as_std_path())
457                && let Some(relative) = camino::Utf8Path::from_path(relative)
458            {
459                found.push(relative.to_path_buf());
460            }
461        }
462    }
463    found.sort();
464    found
465}
466
467/// The documentation root or scan roots reached through a symbolic link.
468///
469/// The linter reads a configuration through the link, and the composition
470/// scan does not follow it, so such a directory is a place no check can see
471/// into. Naming it keeps the failure with the rule it breaks rather than
472/// leaving it to whichever ownership check happens to cover a recorded file
473/// beneath it. A linked documentation root is named alone, because both
474/// scan roots sit beneath it.
475///
476/// SATISFIES instance:the-lint-configuration-composes
477#[must_use]
478pub fn linked_lint_scan_roots(
479    target: &Utf8Path,
480    docs_root: crate::domain::profile::DocsRoot,
481) -> Vec<camino::Utf8PathBuf> {
482    let root = Utf8Path::new(docs_root.as_str());
483    if reached_through_symlink(target, root) {
484        return vec![root.to_path_buf()];
485    }
486    ["specs", "decisions"]
487        .into_iter()
488        .map(|subtree| root.join(subtree))
489        .filter(|subtree| reached_through_symlink(target, subtree))
490        .collect()
491}
492
493fn check_lint_composition(target: &Utf8Path, manifest: &Manifest, report: &mut VerifyReport) {
494    for path in linked_lint_scan_roots(target, manifest.docs_root) {
495        report.fail(format!(
496            "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)"
497        ));
498    }
499    for path in lint_configurations_that_break_composition(target, manifest.docs_root) {
500        report.fail(format!(
501            "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)"
502        ));
503    }
504}
505
506/// The debt file must be readable, and it must be the only debt format.
507///
508/// A file no budget gate can read fails once here rather than once from
509/// every budget gate. The legacy list alone is a note naming its migration:
510/// it still works, and nothing about it is wrong until the day the project
511/// wants a ceiling that only shrinks.
512fn check_debt(target: &Utf8Path, report: &mut VerifyReport) {
513    use crate::domain::debt::{Debt, LEGACY_DEBT_PATH, Presence};
514    let presence = Presence::at(target);
515    if let Err(error) = Debt::read(target) {
516        report.fail(format!("FAIL {error}"));
517        return;
518    }
519    if presence.legacy {
520        report.note(format!(
521            "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'"
522        ));
523    }
524}
525
526/// The marker pair a host file's managed region uses.
527fn markers_for(path: &str) -> (&'static str, &'static str) {
528    if path == HOOKS_CONFIG_PATH {
529        (marker::BEGIN, marker::END)
530    } else {
531        (marker::AGENTS_BEGIN, marker::AGENTS_END)
532    }
533}
534
535fn check_integration(
536    target: &Utf8Path,
537    manifest: &Manifest,
538    report: &mut VerifyReport,
539) -> Result<(), AppError> {
540    for block in &manifest.integration_blocks {
541        let path = block.path.as_str();
542        let (begin, end) = markers_for(path);
543        let full = target.join(&block.path);
544        if reached_through_symlink(target, &block.path) {
545            report.fail(format!("FAIL {path} reached through a symlink"));
546            continue;
547        }
548        if !full.is_file() {
549            report.fail(format!("FAIL missing integration host: {path}"));
550            continue;
551        }
552        let host = std::fs::read_to_string(&full)?;
553        let begins = host.lines().filter(|line| *line == begin).count();
554        let ends = host.lines().filter(|line| *line == end).count();
555        if begins != 1 {
556            report.fail(format!("FAIL missing managed block: {path}"));
557            continue;
558        }
559        if ends != 1 {
560            report.fail(format!("FAIL malformed managed block: {path}"));
561            continue;
562        }
563        match marker::block_hash_with(&host, begin, end) {
564            Some(present) if present == block.marker_hash => {
565                if path == HOOKS_CONFIG_PATH
566                    && let Some(region) = marker::block_region_with(&host, begin, end)
567                {
568                    check_block_entries(&region, report);
569                }
570            }
571            _ => report.fail(format!("FAIL managed block tampered: {path}")),
572        }
573    }
574    Ok(())
575}
576
577/// One note per heading that follows a spec's requirements other than
578/// `## Unenforced`. The gate warns on the same headings in this release, and
579/// a later release fails on them.
580fn note_trailing_sections(path: &Utf8Path, text: &str, report: &mut VerifyReport) {
581    for finding in crate::gates::spec_trailing_section::judge(path.as_str(), text) {
582        if finding.rule == crate::domain::rule_id::RuleId::SpecFollowsTheHeadingShape {
583            report.note(format!(
584                "note: {}:{} {} (docs-specs:a-spec-follows-the-heading-shape); a later release fails on it",
585                path,
586                finding.line.unwrap_or_default(),
587                finding.detail
588            ));
589        }
590    }
591}
592
593fn check_specs(
594    target: &Utf8Path,
595    manifest: &Manifest,
596    report: &mut VerifyReport,
597) -> Result<(), AppError> {
598    let specs = target.join(manifest.docs_root.as_str()).join("specs");
599    if specs.is_dir() {
600        let mut counts = std::collections::BTreeMap::new();
601        let mut names: Vec<_> = specs
602            .read_dir_utf8()?
603            .filter_map(Result::ok)
604            .map(|entry| entry.file_name().to_string())
605            .filter(|name| {
606                #[allow(
607                    clippy::case_sensitive_file_extension_comparisons,
608                    reason = "the corpus convention is lowercase"
609                )]
610                name.ends_with(".md")
611            })
612            .collect();
613        names.sort();
614        for name in names {
615            let text = std::fs::read_to_string(specs.join(&name))?;
616            for id in crate::embedded::rule_ids_in(&text) {
617                *counts.entry(id).or_insert(0usize) += 1;
618            }
619            note_trailing_sections(
620                &camino::Utf8PathBuf::from(format!("{}/specs/{name}", manifest.docs_root.as_str())),
621                &text,
622                report,
623            );
624        }
625        let duplicated: Vec<String> = counts
626            .into_iter()
627            .filter(|(_, n)| *n > 1)
628            .map(|(id, _)| id)
629            .collect();
630        if !duplicated.is_empty() {
631            report.fail("FAIL duplicate rule ID in local specs");
632            for id in duplicated {
633                report.note(format!("### `{id}`"));
634            }
635        }
636    } else {
637        report.fail(format!(
638            "FAIL missing local specs: {}/specs",
639            manifest.docs_root
640        ));
641    }
642    Ok(())
643}
644
645#[cfg(test)]
646mod tests {
647    #![allow(
648        clippy::unwrap_used,
649        reason = "a test panics as its failure signal, not as control flow"
650    )]
651
652    use super::*;
653    use crate::candidate::{Evidence, Input, project};
654    use crate::domain::ownership::{ManagedEntry, Sha256};
655    use crate::domain::profile::{DECLARATION, ProfileId};
656
657    fn consumer(profile: ProfileId) -> Manifest {
658        project(&Input {
659            profile,
660            version: CanonVersion::current(),
661            installed_at: "2026-01-01T00:00:00Z".to_string(),
662            docs_scratch: None,
663            reserve: Vec::new(),
664            writing_style: None,
665            acquisition: None,
666            evidence: Evidence::default(),
667        })
668        .unwrap()
669        .manifest
670    }
671
672    fn failures(manifest: &Manifest) -> Vec<String> {
673        let mut report = VerifyReport::default();
674        check_projection_against(&DECLARATION, manifest, &[], &mut report);
675        report.lines
676    }
677
678    fn managed(path: &str) -> ManagedEntry {
679        ManagedEntry {
680            source: path.into(),
681            destination: path.into(),
682            sha256: Sha256::of(path.as_bytes()),
683        }
684    }
685
686    /// VERIFIES instance:the-lint-configuration-composes
687    ///
688    /// Neither a linked scan root nor its documentation-root ancestor may
689    /// expose external configurations to the composition scan.
690    #[test]
691    fn the_lint_scan_does_not_follow_its_roots_or_their_ancestors() {
692        use crate::domain::profile::DocsRoot;
693
694        for docs_root in [DocsRoot::Docs, DocsRoot::UnderscoreDocs] {
695            for boundary in ["", "specs", "decisions"] {
696                let target = tempfile::tempdir().unwrap();
697                let target = Utf8Path::from_path(target.path()).unwrap();
698                let outside = tempfile::tempdir().unwrap();
699                // A linked documentation root could expose both the direct
700                // library configuration and either recursive scan.
701                for relative in [
702                    ".markdownlint.json",
703                    "specs/.markdownlint-cli2.jsonc",
704                    "decisions/.markdownlint.yaml",
705                ] {
706                    let path = outside.path().join(relative);
707                    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
708                    std::fs::write(path, "{}\n").unwrap();
709                }
710                let link = if boundary.is_empty() {
711                    target.join(docs_root.as_str())
712                } else {
713                    target.join(docs_root.as_str()).join(boundary)
714                };
715                std::fs::create_dir_all(link.parent().unwrap()).unwrap();
716                std::os::unix::fs::symlink(outside.path(), &link).unwrap();
717
718                assert!(
719                    lint_configurations_that_break_composition(target, docs_root).is_empty(),
720                    "{docs_root}/{boundary}: the scan followed a directory link"
721                );
722                let linked = if boundary.is_empty() {
723                    camino::Utf8PathBuf::from(docs_root.as_str())
724                } else {
725                    Utf8Path::new(docs_root.as_str()).join(boundary)
726                };
727                assert_eq!(linked_lint_scan_roots(target, docs_root), [linked]);
728            }
729        }
730    }
731
732    /// VERIFIES instance:the-lint-configuration-composes
733    #[test]
734    fn the_lint_scan_skips_nested_directory_links_and_cycles() {
735        use crate::domain::profile::DocsRoot;
736
737        for docs_root in [DocsRoot::Docs, DocsRoot::UnderscoreDocs] {
738            let target = tempfile::tempdir().unwrap();
739            let target = Utf8Path::from_path(target.path()).unwrap();
740            let specs = target.join(docs_root.as_str()).join("specs");
741            std::fs::create_dir_all(&specs).unwrap();
742            let outside = tempfile::tempdir().unwrap();
743            std::fs::write(outside.path().join(".markdownlint-cli2.jsonc"), "{}\n").unwrap();
744            std::os::unix::fs::symlink(outside.path(), specs.join("linked")).unwrap();
745            std::os::unix::fs::symlink(&specs, specs.join("cycle")).unwrap();
746            // Skipping linked directories must still count a configuration
747            // link by its own filename, even where its target is absent.
748            let config = specs.join(".markdownlint.yaml");
749            std::os::unix::fs::symlink(outside.path().join("absent.yaml"), &config).unwrap();
750
751            assert_eq!(
752                lint_configurations_that_break_composition(target, docs_root),
753                [config.strip_prefix(target).unwrap()]
754            );
755            // A link nested inside a scan root is not a linked scan root.
756            assert!(linked_lint_scan_roots(target, docs_root).is_empty());
757        }
758    }
759
760    /// A knowledge-base record whose managed destinations equal their
761    /// sources satisfied the old discriminator, which then demanded the
762    /// canon's specs and templates and dropped the `AGENTS.md` block.
763    #[test]
764    fn a_consumer_whose_managed_destination_equals_its_source_is_still_a_consumer() {
765        let mut manifest = consumer(ProfileId::KnowledgeBase);
766        for projection in &DECLARATION.managed {
767            if !manifest
768                .managed_files
769                .iter()
770                .any(|entry| entry.destination == projection.source.as_str())
771            {
772                manifest.managed_files.push(managed(&projection.source));
773            }
774        }
775        assert!(failures(&manifest).is_empty(), "{:?}", failures(&manifest));
776
777        let mut without_block = manifest.clone();
778        without_block
779            .integration_blocks
780            .retain(|block| block.path != AGENTS_DIGEST_PATH);
781        assert!(
782            failures(&without_block)
783                .iter()
784                .any(|line| line.contains("no integration block for AGENTS.md")),
785            "{:?}",
786            failures(&without_block)
787        );
788
789        let mut without_seed = manifest;
790        let dropped = without_seed.adopted_files.remove(1).destination;
791        assert!(
792            failures(&without_seed)
793                .iter()
794                .any(|line| line.ends_with(dropped.as_str())),
795            "{:?}",
796            failures(&without_seed)
797        );
798    }
799
800    #[test]
801    fn the_canon_record_is_read_as_the_canon() {
802        let text =
803            std::fs::read_to_string(Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join(MANIFEST_PATH))
804                .unwrap();
805        let mut manifest = Manifest::parse(&text).unwrap();
806        manifest.canon_version = CanonVersion::current();
807        assert!(failures(&manifest).is_empty(), "{:?}", failures(&manifest));
808    }
809
810    #[test]
811    fn a_consumer_omitting_a_declared_seed_fails() {
812        let mut manifest = consumer(ProfileId::Codebase);
813        let dropped = manifest.adopted_files.pop().unwrap().destination;
814        let lines = failures(&manifest);
815        assert!(
816            lines.contains(&format!(
817                "FAIL manifest omits a declared projection: {dropped}"
818            )),
819            "{lines:?}"
820        );
821    }
822
823    /// The marker recognizes a layout and authenticates nothing: a record
824    /// that claims the canon layout is held to the canon's obligations, and
825    /// those do not include the `AGENTS.md` block.
826    #[test]
827    fn a_claimed_canon_layout_changes_which_obligations_are_held() {
828        let mut manifest = consumer(ProfileId::KnowledgeBase);
829        manifest
830            .integration_blocks
831            .retain(|block| block.path != AGENTS_DIGEST_PATH);
832        manifest
833            .managed_files
834            .push(managed("skill-shared/plan-gate.md"));
835        let lines = failures(&manifest);
836        assert!(
837            lines
838                .iter()
839                .any(|line| line
840                    .contains("omits a declared projection: _docs/specs/SPEC-release.md")),
841            "the canon branch owes the canon-only specs: {lines:?}"
842        );
843
844        for projection in &DECLARATION.managed {
845            manifest.managed_files.push(managed(&projection.source));
846        }
847        for file in crate::embedded::SPECS.files() {
848            let name = file.path().to_str().unwrap();
849            manifest
850                .managed_files
851                .push(managed(&format!("_docs/specs/{name}")));
852        }
853        for template in crate::domain::profile::CANON_TEMPLATES.iter() {
854            manifest.managed_files.push(managed(template));
855        }
856        let lines = failures(&manifest);
857        assert!(lines.is_empty(), "{lines:?}");
858    }
859
860    #[test]
861    fn a_yielded_seed_the_record_does_not_name_is_not_owed() {
862        let Some(yielding) = DECLARATION
863            .adopted
864            .iter()
865            .find(|projection| projection.yield_set().is_some())
866        else {
867            return;
868        };
869        let mut manifest = consumer(ProfileId::Codebase);
870        let destination =
871            crate::domain::profile::resolve_destination(&yielding.destination, manifest.docs_root);
872        manifest
873            .adopted_files
874            .retain(|entry| entry.destination != destination);
875        assert!(!failures(&manifest).is_empty());
876
877        let mut report = VerifyReport::default();
878        let cause = yielding
879            .yield_set()
880            .unwrap()
881            .names()
882            .last()
883            .unwrap()
884            .to_string();
885        check_projection_against(&DECLARATION, &manifest, &[cause], &mut report);
886        assert!(report.lines.is_empty(), "{:?}", report.lines);
887    }
888}