doctrine 0.2.1

Project tooling CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// SPDX-License-Identifier: GPL-3.0-only
//! `coverage_scan` — the SL-042 P3 impure reconcile-reader shell.
//!
//! This is the ONLY git/disk seam in the coverage data flow (CLAUDE.md
//! pure/imperative split; design §5.2). It corpus-walks every slice's
//! `coverage.toml`, filters to one requirement, resolves each surviving entry's
//! staleness against git ONCE per scan, and hands the pure folds
//! ([`crate::coverage::composite`] / [`crate::coverage::drift`]) in-memory
//! `(CoverageEntry, IsStale)` cells. The folds stay pure — staleness arrives
//! already resolved here, never inside a fold.
//!
//! Degradations are total, never fatal: a missing slice tree, an unreadable or
//! malformed `coverage.toml`, or an unborn HEAD all narrow the result rather than
//! erroring — a single bad file or a fresh repo must not abort a reconcile read.

// The shell is a leaf built ahead of its consumer: P3 lands the scan; the CLI
// reconcile reader that calls it is a future slice. Until then `scan_coverage`
// is dead in the bins/lib build, so the module carries the self-clearing
// `not(test)` dead_code expect (the `dead-code-self-clearing-leaf` precedent).
// Under `cfg(test)` the perf-spike/integration tests exercise it, so the lint
// would not fire there; scoping to `not(test)` fulfils the expectation exactly
// where the lint applies. Retires itself when the reader is wired.
#![cfg_attr(
    not(test),
    expect(
        dead_code,
        reason = "SL-042 P3 reconcile-reader shell is a leaf built ahead of its \
                  CLI-reader consumer — scan_coverage is dead in the bins/lib \
                  build until that reader is wired (future slice)"
    )
)]

use std::fs;
use std::path::Path;

use crate::coverage::{self, CoverageEntry, IsStale};
use crate::git;

/// Repo-relative slice tree — the dir whose `*/coverage.toml` files this shell
/// walks. Mirrors `state::SLICE_DIR`; kept local so the shell owns its one path.
const SLICE_DIR: &str = ".doctrine/slice";

/// Walk every slice's `coverage.toml`, keep the entries citing `req`, and resolve
/// each one's [`IsStale`] against git — the in-memory cells the pure folds consume.
///
/// Data flow (design §5.2): corpus-walk → parse → filter by requirement →
/// resolve `HEAD` ONCE → per-entry `commits_touching(anchor..HEAD over
/// touched_paths)`. An unborn/non-repo HEAD makes every cell [`IsStale::Unknown`].
/// A missing slice tree or any unreadable/malformed file is skipped, never fatal.
pub(crate) fn scan_coverage(root: &Path, req: &str) -> Vec<(CoverageEntry, IsStale)> {
    let matched = collect_matching_entries(root, req);

    // Resolve HEAD ONCE for the whole scan (the single git anchor for staleness).
    // None ⇒ unborn / non-repo / git failure ⇒ every cell is Unknown.
    let head = git::head_sha(root);

    matched
        .into_iter()
        .map(|entry| {
            let stale = match head.as_deref() {
                Some(head) => IsStale::from(git::commits_touching(
                    root,
                    &entry.touched_paths,
                    &entry.git_anchor,
                    head,
                )),
                None => IsStale::Unknown,
            };
            (entry, stale)
        })
        .collect()
}

/// The disk half: corpus-walk `<root>/.doctrine/slice/*/coverage.toml`, parse
/// each, and keep entries whose key requirement matches `req`. Missing dir →
/// empty; an unreadable or malformed file is skipped (degradation, not error).
fn collect_matching_entries(root: &Path, req: &str) -> Vec<CoverageEntry> {
    let slice_root = root.join(SLICE_DIR);
    let Ok(slices) = fs::read_dir(&slice_root) else {
        return Vec::new(); // absent / unreadable tree → empty
    };

    let mut out = Vec::new();
    for slice in slices.flatten() {
        let coverage_path = slice.path().join("coverage.toml");
        let Ok(body) = fs::read_to_string(&coverage_path) else {
            continue; // no coverage.toml in this slice (or unreadable) → skip
        };
        let Ok(file) = coverage::parse(&body) else {
            continue; // malformed coverage.toml → skip, never abort the scan
        };
        out.extend(file.entry.into_iter().filter(|e| e.key.requirement == req));
    }
    out
}

#[cfg(test)]
#[expect(
    clippy::unwrap_used,
    reason = "tests: fail-fast unwrap on disk/git setup is idiomatic"
)]
mod tests {
    use super::*;
    use std::process::Command;
    use std::time::Instant;

    // --- helpers -------------------------------------------------------------

    /// Write one slice's `coverage.toml` under a project root.
    fn write_coverage(root: &Path, slice_num: u32, body: &str) {
        let dir = root.join(SLICE_DIR).join(format!("{slice_num:03}"));
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("coverage.toml"), body).unwrap();
    }

    /// A minimal `[[entry]]` body for one requirement.
    fn one_entry_body(slice: &str, req: &str, status: &str) -> String {
        format!(
            "[[entry]]\n\
             slice = \"{slice}\"\n\
             requirement = \"{req}\"\n\
             contributing_change = \"{slice}\"\n\
             mode = \"VT\"\n\
             status = \"{status}\"\n\
             git_anchor = \"deadbeef\"\n"
        )
    }

    // --- behaviour: filter + degradations ------------------------------------

    #[test]
    fn missing_slice_tree_yields_empty() {
        let dir = tempfile::tempdir().unwrap();
        assert!(scan_coverage(dir.path(), "REQ-110").is_empty());
    }

    #[test]
    fn filters_to_the_requested_requirement_across_slices() {
        let dir = tempfile::tempdir().unwrap();
        write_coverage(
            dir.path(),
            40,
            &one_entry_body("SL-040", "REQ-110", "verified"),
        );
        write_coverage(
            dir.path(),
            41,
            &one_entry_body("SL-041", "REQ-999", "planned"),
        );
        write_coverage(
            dir.path(),
            42,
            &one_entry_body("SL-042", "REQ-110", "planned"),
        );

        let cells = scan_coverage(dir.path(), "REQ-110");
        assert_eq!(
            cells.len(),
            2,
            "only the two REQ-110 entries survive the filter"
        );
        assert!(cells.iter().all(|(e, _)| e.key.requirement == "REQ-110"));
    }

    #[test]
    fn malformed_coverage_file_is_skipped_not_fatal() {
        let dir = tempfile::tempdir().unwrap();
        write_coverage(
            dir.path(),
            40,
            &one_entry_body("SL-040", "REQ-110", "verified"),
        );
        write_coverage(dir.path(), 41, "this is not valid toml = = =");
        let cells = scan_coverage(dir.path(), "REQ-110");
        assert_eq!(
            cells.len(),
            1,
            "the good file survives; the bad one is skipped"
        );
    }

    #[test]
    fn no_head_makes_every_cell_unknown() {
        // A tempdir that is NOT a git repo → head_sha None → all Unknown.
        let dir = tempfile::tempdir().unwrap();
        write_coverage(
            dir.path(),
            40,
            &one_entry_body("SL-040", "REQ-110", "verified"),
        );
        let cells = scan_coverage(dir.path(), "REQ-110");
        assert_eq!(cells.len(), 1);
        assert_eq!(cells.first().unwrap().1, IsStale::Unknown);
    }

    // --- VT-4 (R2 perf spike) — TWO axes, measured separately ----------------
    //
    // Axis (a): scan fan-in (walk+parse+filter), IsStale precomputed Unknown
    // (no git). Sweep N ∈ {50, 500, 2000}; the 2000 tier is #[ignore]d so it
    // never bloats the default gate — run it explicitly to confirm the cliff.
    // Axis (b): per-call git::commits_touching subprocess cost against the REAL
    // fork repo with real paths. N calls, per-call cost — NO fabricated commits.
    //
    // Bounds are DEBUG-budgeted (~10× release; mem.pattern.testing.debug-vs-
    // release-scale-timing): generous, cliff-detecting, not tight absolutes.

    /// Axis (a): build N slice coverage files, then measure ONLY walk+parse+filter.
    fn measure_scan_fanin(n: u32) -> std::time::Duration {
        let dir = tempfile::tempdir().unwrap();
        for i in 0..n {
            // Half the files carry the target requirement, half a decoy — so the
            // filter does real work.
            let req = if i % 2 == 0 { "REQ-110" } else { "REQ-999" };
            write_coverage(dir.path(), i, &one_entry_body("SL-000", req, "planned"));
        }
        let start = Instant::now();
        let cells = scan_coverage(dir.path(), "REQ-110");
        let elapsed = start.elapsed();
        // Sanity: half matched (the non-repo tempdir resolves all to Unknown,
        // which is fine — axis (a) is the walk cost, not the git cost).
        let expected = n.div_euclid(2) + n.rem_euclid(2);
        assert_eq!(cells.len() as u32, expected, "filter kept the REQ-110 half");
        elapsed
    }

    #[test]
    fn vt4a_scan_fanin_small_tiers() {
        // Default-gate tiers: cheap, always run. Print per-tier timing.
        for n in [50_u32, 500] {
            let d = measure_scan_fanin(n);
            println!("VT-4(a) scan fan-in N={n}: {d:?}");
            // Loose debug ceiling — flags a pathological regression, not a cliff.
            assert!(
                d.as_secs() < 10,
                "scan fan-in N={n} took {d:?} — investigate (debug budget ~10x)"
            );
        }
    }

    #[test]
    #[ignore = "heavy 2000-file tier — run explicitly to confirm the scan cliff; \
                numbers recorded in the worker report"]
    fn vt4a_scan_fanin_heavy_tier() {
        let d = measure_scan_fanin(2000);
        println!("VT-4(a) scan fan-in N=2000: {d:?}");
        assert!(d.as_secs() < 30, "scan fan-in N=2000 took {d:?}");
    }

    /// Axis (b): per-call `git::commits_touching` subprocess cost against the
    /// real fork repo. Returns (total, per_call). Skips gracefully if the fork is
    /// not a usable git repo (e.g. CI without history).
    fn measure_staleness_per_call(n: u32) -> Option<(std::time::Duration, std::time::Duration)> {
        // The fork repo: CARGO_MANIFEST_DIR is the crate root = the worktree.
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let head = git::head_sha(root)?;
        // An old SHA reachable from HEAD: first commit on the branch.
        let out = Command::new("git")
            .arg("-C")
            .arg(root)
            .args(["rev-list", "--max-parents=0", "HEAD"])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let roots = String::from_utf8(out.stdout).ok()?;
        let base = roots.lines().next()?.trim().to_owned();
        if base.is_empty() {
            return None;
        }
        let paths = vec!["src/coverage.rs".to_owned()];

        let start = Instant::now();
        for _ in 0..n {
            // Real subprocess each call — this is the cost we are measuring.
            let _ = git::commits_touching(root, &paths, &base, &head);
        }
        let total = start.elapsed();
        let per = total.checked_div(n).unwrap_or(total);
        Some((total, per))
    }

    #[test]
    fn vt4b_staleness_per_call_cost() {
        // Modest N so the gate stays fast; per-call cost is the signal, not total.
        let Some((total, per)) = measure_staleness_per_call(20) else {
            println!("VT-4(b) staleness: fork not a usable git repo — skipped");
            return;
        };
        println!("VT-4(b) staleness N=20: total {total:?}, per-call {per:?}");
        // A git subprocess pair (merge-base + rev-list) is single-digit ms to
        // low tens of ms; flag only a pathological per-call cost.
        assert!(
            per.as_millis() < 2000,
            "per-call staleness {per:?} — investigate subprocess cost"
        );
    }

    // --- PHASE-04 temp-git-repo helper (R-e seam-fit) ------------------------
    //
    // A throwaway born git repo (NEVER the doctrine repo's own .doctrine/): init,
    // pin identity, write+commit files. Mirrors git.rs's `ScratchRepo` shape; kept
    // local because that helper is private to git.rs's test module.

    /// Run `git -C <root> <args>` with pinned identity (no machine config needed),
    /// asserting success; returns trimmed stdout.
    fn git_at(root: &Path, args: &[&str]) -> String {
        let out = Command::new("git")
            .arg("-C")
            .arg(root)
            .args([
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "-c",
                "commit.gpgsign=false",
            ])
            .args(args)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
        String::from_utf8(out.stdout).unwrap().trim().to_owned()
    }

    /// Write `rel` under `root` (creating parents), stage and commit it, return the
    /// resulting HEAD SHA.
    fn write_commit(root: &Path, rel: &str, contents: &str, msg: &str) -> String {
        let full = root.join(rel);
        fs::create_dir_all(full.parent().unwrap()).unwrap();
        fs::write(&full, contents).unwrap();
        git_at(root, &["add", rel]);
        git_at(root, &["commit", "-q", "-m", msg]);
        git_at(root, &["rev-parse", "HEAD"])
    }

    // --- T1 (R-e): the staleness seam fits a coverage entry's own granularity --
    //
    // H1 ("git::commits_touching fits coverage's (git_anchor, touched_paths)
    // granularity") turned from hypothesis into a test-backed fact: drive the seam
    // with the EXACT field types a CoverageEntry carries (a String anchor, a
    // Vec<String> of repo-relative paths) against a real temp git repo. No leaf
    // widening was needed — the existing signature consumed coverage's granularity
    // verbatim.

    #[test]
    fn seam_fits_coverage_entry_granularity_stale_and_fresh() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        git_at(root, &["init", "-q", "-b", "main"]);

        // A coverage entry's anchor is the SHA after the path was first seen.
        let anchor = write_commit(root, "src/foo.rs", "fn a() {}\n", "add foo");
        // A second, unrelated path moves HEAD without touching foo.rs.
        let _ = write_commit(root, "src/bar.rs", "fn b() {}\n", "add bar");
        let head_fresh = git_at(root, &["rev-parse", "HEAD"]);

        // Use a CoverageEntry's ACTUAL field shapes as the seam inputs.
        let entry = entry_with(&anchor, &["src/foo.rs"]);
        // foo.rs was NOT touched between anchor and head_fresh → Fresh.
        let fresh = IsStale::from(git::commits_touching(
            root,
            &entry.touched_paths,
            &entry.git_anchor,
            &head_fresh,
        ));
        assert_eq!(
            fresh,
            IsStale::Fresh,
            "anchor..HEAD over an untouched path resolves Fresh through the seam"
        );

        // Now modify foo.rs and commit — HEAD moves PAST the anchor over that path.
        let head_stale = write_commit(root, "src/foo.rs", "fn a() { 1; }\n", "edit foo");
        let stale = IsStale::from(git::commits_touching(
            root,
            &entry.touched_paths,
            &entry.git_anchor,
            &head_stale,
        ));
        assert_eq!(
            stale,
            IsStale::Stale,
            "a commit touching the path since the anchor resolves Stale through the seam"
        );
    }

    /// Build a `CoverageEntry` carrying the given anchor + touched paths (the two
    /// fields the staleness seam consumes), Verified VH evidence.
    fn entry_with(anchor: &str, paths: &[&str]) -> CoverageEntry {
        use crate::requirement::CoverageStatus;
        CoverageEntry {
            key: coverage::CoverageKey {
                slice: "SL-042".to_owned(),
                requirement: "REQ-115".to_owned(),
                contributing_change: "SL-042".to_owned(),
                mode: "VH".to_owned(),
            },
            status: CoverageStatus::Verified,
            git_anchor: anchor.to_owned(),
            attested_date: Some("2026-06-12".to_owned()),
            touched_paths: paths.iter().map(|p| (*p).to_owned()).collect(),
        }
    }

    // --- T2 (VT-1 / NF-002): VH/VA Verified evidence is FLAGGED stale, never ---
    //     auto-demoted. The core decay lock, end-to-end through scan_coverage.
    //
    // Layout a temp git repo with a committed source file (the anchor), a slice
    // coverage.toml carrying a VH and a VA Verified entry over that file, then move
    // HEAD past the anchor by editing the file. scan_coverage must mark both cells
    // Stale while their `status` stays Verified — staleness is a SEPARATE axis from
    // the observed status; nothing demotes Verified to Failed/Blocked/etc.

    /// Render a two-entry (VH + VA) coverage.toml body, both `Verified`, anchored at
    /// `anchor` over `path`. The mode is the only field that differs between them.
    fn vh_va_coverage_body(anchor: &str, path: &str) -> String {
        let entry = |mode: &str| {
            format!(
                "[[entry]]\n\
                 slice = \"SL-042\"\n\
                 requirement = \"REQ-115\"\n\
                 contributing_change = \"SL-042\"\n\
                 mode = \"{mode}\"\n\
                 status = \"verified\"\n\
                 git_anchor = \"{anchor}\"\n\
                 attested_date = \"2026-06-12\"\n\
                 touched_paths = [\"{path}\"]\n"
            )
        };
        format!("{}{}", entry("VH"), entry("VA"))
    }

    #[test]
    fn vh_va_verified_evidence_is_flagged_stale_never_demoted() {
        use crate::requirement::CoverageStatus;

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        git_at(root, &["init", "-q", "-b", "main"]);

        // 1. A committed source file → its commit SHA is the coverage anchor.
        let anchor = write_commit(root, "src/foo.rs", "fn a() {}\n", "add foo");

        // 2. Lay the VH + VA Verified coverage entries over src/foo.rs at `anchor`,
        //    and commit them INSIDE the temp repo so the temp repo's own HEAD is
        //    valid for head_sha / commits_touching (NOT the doctrine repo's HEAD).
        let cov_rel = ".doctrine/slice/042/coverage.toml";
        write_commit(
            root,
            cov_rel,
            &vh_va_coverage_body(&anchor, "src/foo.rs"),
            "coverage",
        );

        // 3. Move HEAD PAST the anchor over src/foo.rs (edit + commit). `anchor` is
        //    now a strict ancestor of HEAD (the merge-base gate passes) and a commit
        //    has touched the path since.
        write_commit(root, "src/foo.rs", "fn a() { 1; }\n", "edit foo");

        // 4. Scan. Both VH and VA cells must be Stale, status still Verified.
        let cells = scan_coverage(root, "REQ-115");
        assert_eq!(
            cells.len(),
            2,
            "the VH and VA entries both survive the filter"
        );

        for (entry, stale) in &cells {
            assert_eq!(
                *stale,
                IsStale::Stale,
                "{} evidence over an edited path is flagged stale",
                entry.key.mode
            );
            assert_eq!(
                entry.status,
                CoverageStatus::Verified,
                "{} status stays Verified — staleness NEVER auto-demotes (NF-002)",
                entry.key.mode
            );
        }
        // Spell the mode coverage out: both attestation kinds are present.
        assert!(cells.iter().any(|(e, _)| e.key.mode == "VH"));
        assert!(cells.iter().any(|(e, _)| e.key.mode == "VA"));
    }

    #[test]
    fn vh_va_verified_evidence_untouched_since_anchor_is_fresh() {
        use crate::requirement::CoverageStatus;

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        git_at(root, &["init", "-q", "-b", "main"]);

        // The anchor is the SHA at which foo.rs was last touched.
        let anchor = write_commit(root, "src/foo.rs", "fn a() {}\n", "add foo");
        // Commit the coverage store and an UNRELATED file — HEAD advances but never
        // touches src/foo.rs after the anchor.
        write_commit(
            root,
            ".doctrine/slice/042/coverage.toml",
            &vh_va_coverage_body(&anchor, "src/foo.rs"),
            "coverage",
        );
        write_commit(root, "src/bar.rs", "fn b() {}\n", "add bar");

        let cells = scan_coverage(root, "REQ-115");
        assert_eq!(cells.len(), 2);
        for (entry, stale) in &cells {
            assert_eq!(
                *stale,
                IsStale::Fresh,
                "{} evidence over an untouched path is Fresh — the contrast case",
                entry.key.mode
            );
            assert_eq!(entry.status, CoverageStatus::Verified, "status unchanged");
        }
    }

    // --- T3 (VT-2 / EX-3): no parallel staleness impl ------------------------
    //
    // Coverage staleness flows ONLY through git::commits_touching — there is no
    // second staleness leaf. Structurally assert that the coverage modules
    // reference the seam and carry NO code path into the memory-side staleness leaf
    // (the cs leaf below — a DISTINCT, unrelated module that must not bleed in
    // here). We match the `::`-path FORM of that module, never the bare word, so
    // prose may name it without tripping the guard.

    /// The memory-side staleness leaf's module path form. Spelled by concatenation
    /// so this very assertion's source carries no literal `<name>::` token to
    /// false-positive on (the guard reads its own file).
    fn rival_staleness_path() -> String {
        format!("{}::", "contentset")
    }

    #[test]
    fn coverage_staleness_flows_only_through_commits_touching() {
        let scan_src = include_str!("coverage_scan.rs");
        let cov_src = include_str!("coverage.rs");
        let rival = rival_staleness_path();

        assert!(
            scan_src.contains("commits_touching"),
            "the scan shell resolves staleness through git::commits_touching"
        );
        // The single staleness seam — no parallel impl, no path into the rival leaf.
        for (name, src) in [("coverage_scan.rs", scan_src), ("coverage.rs", cov_src)] {
            assert!(
                !src.contains(&rival),
                "{name} must not path into the memory-side staleness leaf — coverage \
                 staleness has its own single seam (git::commits_touching), no \
                 parallel impl"
            );
        }
    }
}