doctrine 0.2.0

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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
// SPDX-License-Identifier: GPL-3.0-only
//! Worktree provisioning — the sole copy path into a fork (SL-029, design §3).
//!
//! ADR-001 leaf: the pure core (`WITHHELD`, `parse_allowlist`, `is_withheld`,
//! `select_copies`, `allowlist_violations`) takes paths/strings as inputs — no
//! disk, git, clock, or rng. The impure shell (`run_provision`,
//! `run_check_allowlist`) is the thin imperative seam: it reads
//! `.worktreeinclude`, drives `git ls-files`/`rev-parse` through the `git.rs`
//! runners, and copies via the `fsutil` safe-copy helper.
//!
//! Two-layer exclusion (OQ-3-B): `select_copies` is the *guarantee* — it drops
//! any file matching the coordination/runtime tier even under a broad `**`
//! allowlist, so the copy physically cannot leak the tier. `allowlist_violations`
//! is a static *smell test* — a green result is NOT completeness (F7);
//! `select_copies` remains the guarantee.

use std::fs;
use std::io::{self, ErrorKind, Write};
use std::path::{Path, PathBuf};

use anyhow::{Context, bail};
use glob::{MatchOptions, Pattern};

use crate::fsutil::{self, CopyOutcome};
use crate::git;
use crate::root;

/// The coordination/runtime tier a fork must never receive, categorised.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Tier {
    /// `.doctrine/state/**` — phase sheets, the boot snapshot.
    State,
    /// `.doctrine/slice/*/phases` — per-slice symlink into the state tree.
    PhaseLink,
    /// `**/handover.md` — disposable agent context.
    Handover,
    /// `.doctrine/slice/*/inquisition.md` — disposable adversarial-review scratch.
    Inquisition,
    /// `.doctrine/memory/{index,embeddings,state,shipped}` — regenerable caches.
    MemoryCache,
}

impl std::fmt::Display for Tier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            Tier::State => "state",
            Tier::PhaseLink => "phase-link",
            Tier::Handover => "handover",
            Tier::Inquisition => "inquisition",
            Tier::MemoryCache => "memory-cache",
        };
        f.write_str(name)
    }
}

/// One categorised withhold glob.
#[derive(Debug)]
pub(crate) struct Withhold {
    pub(crate) tier: Tier,
    pub(crate) glob: &'static str,
}

const fn w(tier: Tier, glob: &'static str) -> Withhold {
    Withhold { tier, glob }
}

/// The single structured authority (design §3 F4): every glob here is pinned to
/// a runtime-tier line in `.gitignore` (24, 31–38). The parity test
/// (`every_runtime_gitignore_glob_is_classified`) fails CI if a new runtime glob
/// lands in `.gitignore` without a home here or in [`DERIVED_RUNTIME`].
pub(crate) const WITHHELD: &[Withhold] = &[
    w(Tier::State, ".doctrine/state/**"),
    w(Tier::PhaseLink, ".doctrine/slice/*/phases"),
    w(Tier::Handover, "**/handover.md"),
    w(Tier::Inquisition, ".doctrine/slice/*/inquisition.md"),
    w(Tier::MemoryCache, ".doctrine/memory/index/**"),
    w(Tier::MemoryCache, ".doctrine/memory/embeddings/**"),
    w(Tier::MemoryCache, ".doctrine/memory/state/**"),
    w(Tier::MemoryCache, ".doctrine/memory/shipped/**"),
];

/// Gitignored-but-*derived* trees: regenerated by `doctrine install` in the fork,
/// never copied and not a hazard — documented, deliberately out of [`WITHHELD`]
/// (design §3). Classified so the parity test does not flag them unclassified.
/// Only the parity test consumes it today (the `select_copies` guarantee needs no
/// derived list — derived paths simply fall through as unallowlisted/uncopied);
/// the expectation self-clears the moment a non-test consumer appears.
#[cfg_attr(
    not(test),
    expect(
        dead_code,
        reason = "classification authority; only the .gitignore parity test reads it so far (SL-029)"
    )
)]
pub(crate) const DERIVED_RUNTIME: &[&str] = &[".doctrine/skills/*"];

/// Match options shared by every glob comparison: `**` is the *only* way to cross
/// a path separator, so a single `*` matches one component (gitignore-ish, and
/// what keeps `*` from silently spanning `.doctrine/state/...`).
const MATCH_OPTS: MatchOptions = MatchOptions {
    case_sensitive: true,
    require_literal_separator: true,
    require_literal_leading_dot: false,
};

fn glob_matches(pat: &Pattern, path: &str) -> bool {
    pat.matches_with(path, MATCH_OPTS)
}

// ---------------------------------------------------------------------------
// Allowlist (the documented `glob` subset, design §3 M6)
// ---------------------------------------------------------------------------

/// A parsed `.worktreeinclude`: the documented subset — blank/`#`-comment lines,
/// literal repo-relative paths, and `* ** ?` patterns. No `!` negation, no
/// anchoring (rejected at parse).
#[derive(Debug)]
pub(crate) struct Allowlist {
    pub(crate) patterns: Vec<Pattern>,
}

/// Why a `.worktreeinclude` line is unsupported in v1.
#[derive(Debug, thiserror::Error)]
pub(crate) enum ParseError {
    /// `!`-negation — unsupported (a project must not rely on un-implemented semantics).
    #[error("line {line}: negation (`!`) is unsupported in .worktreeinclude v1: `{raw}`")]
    Negation { line: usize, raw: String },
    /// Leading-`/` anchoring — unsupported.
    #[error("line {line}: anchoring (leading `/`) is unsupported in .worktreeinclude v1: `{raw}`")]
    Anchoring { line: usize, raw: String },
    /// Not a valid `glob` pattern.
    #[error("line {line}: invalid glob `{raw}`: {source}")]
    BadGlob {
        line: usize,
        raw: String,
        #[source]
        source: glob::PatternError,
    },
}

/// Parse `.worktreeinclude` text into an [`Allowlist`], rejecting `!`/anchoring
/// with a clear error so a project cannot silently rely on unsupported semantics.
pub(crate) fn parse_allowlist(text: &str) -> Result<Allowlist, ParseError> {
    let mut patterns = Vec::new();
    for (i, raw_line) in text.lines().enumerate() {
        let line = raw_line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let n = i + 1;
        if line.starts_with('!') {
            return Err(ParseError::Negation {
                line: n,
                raw: line.to_string(),
            });
        }
        if line.starts_with('/') {
            return Err(ParseError::Anchoring {
                line: n,
                raw: line.to_string(),
            });
        }
        let pat = Pattern::new(line).map_err(|source| ParseError::BadGlob {
            line: n,
            raw: line.to_string(),
            source,
        })?;
        patterns.push(pat);
    }
    Ok(Allowlist { patterns })
}

// ---------------------------------------------------------------------------
// The exclusion core (pure)
// ---------------------------------------------------------------------------

/// The tier a repo-relative path belongs to, if it is withheld. Non-fallible:
/// the static [`WITHHELD`] globs are proven to compile by `withheld_globs_all_compile`.
pub(crate) fn is_withheld(rel: &str) -> Option<Tier> {
    WITHHELD.iter().find_map(|item| {
        Pattern::new(item.glob)
            .ok()
            .filter(|p| glob_matches(p, rel))
            .map(|_p| item.tier)
    })
}

/// A withheld candidate: the path that matched the allowlist but is skipped.
#[derive(Debug)]
pub(crate) struct Withheld {
    pub(crate) path: String,
    pub(crate) tier: Tier,
}

/// The partition of allowlisted candidates into those to copy and those withheld.
#[derive(Debug)]
pub(crate) struct Selection {
    pub(crate) copy: Vec<String>,
    pub(crate) withheld: Vec<Withheld>,
}

/// Partition gitignored `candidates`: a path is copied iff it matches the
/// allowlist AND is not withheld; a withheld match is dropped (skip+warn) **even
/// under a broad `*`/`**`** — this is the copy-time guarantee (design §3).
pub(crate) fn select_copies(allow: &Allowlist, candidates: &[String]) -> Selection {
    let mut copy = Vec::new();
    let mut withheld = Vec::new();
    for cand in candidates {
        if !allow.patterns.iter().any(|p| glob_matches(p, cand)) {
            continue;
        }
        match is_withheld(cand) {
            Some(tier) => withheld.push(Withheld {
                path: cand.clone(),
                tier,
            }),
            None => copy.push(cand.clone()),
        }
    }
    Selection { copy, withheld }
}

/// A static smell-test hit: an allowlist pattern that *names* a withheld tier.
#[derive(Debug)]
pub(crate) struct Violation {
    pub(crate) pattern: String,
    pub(crate) tier: Tier,
}

/// A concrete representative path for a glob: replace each wildcard with a literal
/// segment so a pattern that "would pull" the tier matches it. `**`→`x`, `*`→`x`,
/// `?`→`x`. e.g. `.doctrine/state/**` → `.doctrine/state/x`.
fn representative(glob: &str) -> String {
    glob.replace("**", "x").replace(['*', '?'], "x")
}

/// Patterns that *name* a withheld glob (a [`WITHHELD`] representative matches the
/// pattern). The static smell test behind `check-allowlist` and `provision`'s
/// fail-closed gate. **Green is not completeness (F7)** — [`select_copies`] is the
/// guarantee; this only proves no pattern *names* the tier.
pub(crate) fn allowlist_violations(allow: &Allowlist) -> Vec<Violation> {
    let mut out = Vec::new();
    for item in WITHHELD {
        let rep = representative(item.glob);
        for pat in &allow.patterns {
            if glob_matches(pat, &rep) {
                out.push(Violation {
                    pattern: pat.as_str().to_string(),
                    tier: item.tier,
                });
            }
        }
    }
    out
}

/// HEAD-stationarity compare for `branch-point-check` (SL-031 §5.2): true iff the
/// orchestrator's pre-spawn base `B` still equals coordination HEAD.
///
/// **Naming note (C-V).** This is the D5 *concurrency extension* — a ref-equality
/// assert at the batch-commit boundary — NOT a merge-base / branch-point
/// computation, and NOT SL-029's creation-time single-tree check. The "branch
/// point" name is kept for continuity; the operation is nothing more than the
/// shas being equal. Pure (ADR-001 leaf): the caller's shell does the HEAD read.
pub(crate) fn matches(base: &str, head: &str) -> bool {
    base == head
}

// ---------------------------------------------------------------------------
// Impure shell — provision / check-allowlist
// ---------------------------------------------------------------------------

const ALLOWLIST_FILE: &str = ".worktreeinclude";

/// Read `<root>/.worktreeinclude`; **absent ⇒ empty allowlist ⇒ copy nothing** (F2).
fn read_allowlist(root: &Path) -> anyhow::Result<Allowlist> {
    let path = root.join(ALLOWLIST_FILE);
    match fs::read_to_string(&path) {
        Ok(text) => parse_allowlist(&text).map_err(|e| anyhow::anyhow!("{}: {e}", path.display())),
        Err(e) if e.kind() == ErrorKind::NotFound => Ok(Allowlist {
            patterns: Vec::new(),
        }),
        Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
    }
}

/// Resolve a `git rev-parse --git-common-dir` answer (relative to `root`, or
/// absolute for a linked worktree) to a canonical path for comparison.
fn resolve_common_dir(root: &Path, common: &str) -> anyhow::Result<PathBuf> {
    let raw = Path::new(common);
    let joined = if raw.is_absolute() {
        raw.to_path_buf()
    } else {
        root.join(raw)
    };
    fs::canonicalize(&joined)
        .with_context(|| format!("canonicalize git-common-dir {}", joined.display()))
}

/// True iff `root` sits on a *linked* worktree rather than the primary tree:
/// `git rev-parse --git-dir` (this tree's gitdir) differs from `--git-common-dir`
/// (the repo's shared gitdir). On the primary tree both resolve to the same
/// `.git`; on a linked worktree the gitdir is `.git/worktrees/<name>` (SL-032
/// PHASE-04, ADR-006 amendment). Shared, not memory-private — the provision path
/// may call it; `memory record` calls it to warn on squash-orphan risk.
pub(crate) fn is_linked_worktree(root: &Path) -> anyhow::Result<bool> {
    let git_dir = resolve_common_dir(root, &git::git_text(root, &["rev-parse", "--git-dir"])?)?;
    let common = resolve_common_dir(
        root,
        &git::git_text(root, &["rev-parse", "--git-common-dir"])?,
    )?;
    Ok(git_dir != common)
}

/// Verify `fork` is a real sibling worktree of `source`: it shares the source's
/// `git-common-dir` and is not the source itself (design §3 copy safety, B5).
fn verify_sibling_worktree(source: &Path, fork: &Path) -> anyhow::Result<()> {
    if source == fork {
        bail!("fork path is the source tree itself; refusing to provision");
    }
    let source_common = resolve_common_dir(
        source,
        &git::git_text(source, &["rev-parse", "--git-common-dir"])?,
    )?;
    let fork_common = resolve_common_dir(
        fork,
        &git::git_text(fork, &["rev-parse", "--git-common-dir"])?,
    )?;
    if source_common != fork_common {
        bail!(
            "fork {} is not a worktree of the source repo (git-common-dir differs)",
            fork.display()
        );
    }
    Ok(())
}

/// Enumerate the copy candidate set: gitignored, untracked files, NUL-delimited
/// so newline/quoted paths survive (design §3 m9).
fn enumerate_candidates(root: &Path) -> anyhow::Result<Vec<String>> {
    let raw = git::git_bytes(
        root,
        &[
            "ls-files",
            "-z",
            "--others",
            "--ignored",
            "--exclude-standard",
        ],
    )?;
    let mut out = Vec::new();
    for chunk in raw.split(|b| *b == 0) {
        if chunk.is_empty() {
            continue;
        }
        let path = std::str::from_utf8(chunk)
            .map_err(|e| anyhow::anyhow!("non-utf8 path from git ls-files: {e}"))?;
        out.push(path.to_string());
    }
    Ok(out)
}

/// `doctrine worktree provision <fork>` — the sole copier (design §3).
///
/// Runs from the SOURCE root and writes `<fork>`: read `.worktreeinclude` (absent
/// ⇒ empty) → `allowlist_violations` fail-closed → verify `<fork>` is a sibling
/// worktree → enumerate gitignored candidates → `select_copies` → safe copy,
/// skip+warn withheld → report copied/withheld (exit 0).
pub(crate) fn run_provision(path: Option<PathBuf>, fork: &Path) -> anyhow::Result<()> {
    let source = root::find(path, &root::default_markers())?;
    let source = fs::canonicalize(&source)
        .with_context(|| format!("canonicalize source root {}", source.display()))?;

    let allow = read_allowlist(&source)?;

    // Fail closed: a tier-naming pattern aborts before any copy (VT-8).
    let violations = allowlist_violations(&allow);
    if !violations.is_empty() {
        for v in &violations {
            writeln!(
                io::stderr(),
                "refusing: pattern `{}` names the withheld {} tier",
                v.pattern,
                v.tier
            )?;
        }
        bail!(
            "{} .worktreeinclude pattern(s) name a withheld tier; refusing to provision",
            violations.len()
        );
    }

    let fork =
        fs::canonicalize(fork).with_context(|| format!("canonicalize fork {}", fork.display()))?;
    verify_sibling_worktree(&source, &fork)?;

    let candidates = enumerate_candidates(&source)?;
    let selection = select_copies(&allow, &candidates);

    let withheld_target = |rel: &Path| rel.to_str().is_some_and(|s| is_withheld(s).is_some());

    let mut copied = 0usize;
    let mut skipped = 0usize;
    for rel in &selection.copy {
        match fsutil::copy_selected(&source, &fork, Path::new(rel), &withheld_target)? {
            CopyOutcome::Copied => copied += 1,
            CopyOutcome::Skipped(reason) => {
                skipped += 1;
                writeln!(io::stderr(), "skipped {rel}: {reason}")?;
            }
        }
    }
    for held in &selection.withheld {
        writeln!(io::stderr(), "withheld {} ({} tier)", held.path, held.tier)?;
    }

    writeln!(
        io::stdout(),
        "provisioned {}: {copied} copied, {} withheld, {skipped} skipped",
        fork.display(),
        selection.withheld.len()
    )?;
    Ok(())
}

/// `doctrine worktree check-allowlist` — the static smell test. Nonzero exit on a
/// tier-naming pattern OR an unsupported-syntax (`!`/anchoring) pattern.
pub(crate) fn run_check_allowlist(path: Option<PathBuf>) -> anyhow::Result<()> {
    let root = root::find(path, &root::default_markers())?;
    let file = root.join(ALLOWLIST_FILE);
    let text = match fs::read_to_string(&file) {
        Ok(t) => t,
        Err(e) if e.kind() == ErrorKind::NotFound => {
            writeln!(io::stdout(), "no {ALLOWLIST_FILE} — nothing to check")?;
            return Ok(());
        }
        Err(e) => return Err(e).with_context(|| format!("read {}", file.display())),
    };

    // Parse errors (`!`/anchoring/bad-glob) fail closed via `?`.
    let allow = parse_allowlist(&text).map_err(|e| anyhow::anyhow!("{}: {e}", file.display()))?;

    let violations = allowlist_violations(&allow);
    if violations.is_empty() {
        writeln!(
            io::stdout(),
            "ok — no allowlist pattern names a withheld tier"
        )?;
        return Ok(());
    }
    for v in &violations {
        writeln!(
            io::stderr(),
            "violation: pattern `{}` names the withheld {} tier",
            v.pattern,
            v.tier
        )?;
    }
    bail!(
        "{} allowlist pattern(s) name a withheld tier",
        violations.len()
    )
}

/// Peel a base/head ref to its canonical commit sha for the stationarity compare.
/// `rev-parse --verify <ref>^{commit}` resolves a sha, `HEAD`, a branch, or a
/// (lightweight/annotated) tag down to the commit it names; an unresolvable ref
/// errors, so the guard *bails* rather than comparing an unresolved symbol
/// (ISS-002 / SL-041). Impure (the git read); the comparison stays in [`matches`].
fn resolve_commit(root: &Path, reference: &str) -> anyhow::Result<String> {
    Ok(git::git_text(
        root,
        &["rev-parse", "--verify", &format!("{reference}^{{commit}}")],
    )?)
}

/// `doctrine worktree branch-point-check --base <REF> [--head <REF>]` — the
/// funnel's one tested seam (SL-031 §5.2). Asserts coordination HEAD has not moved
/// off the orchestrator's pre-spawn base before the batch commit.
///
/// **Both** ends are resolved to a commit sha in the shell via [`resolve_commit`]
/// before the compare (`--head` absent ⇒ `HEAD`); a symbolic ref is never trusted
/// verbatim, and an unresolvable ref makes the verb bail (ISS-002 / SL-041). Exit
/// **0** on stationarity (resolved `base == head`), **1** otherwise (the
/// orchestrator re-dispatches the batch onto the moved HEAD — never commits on a
/// moved base). Read-classed (no authored write): callable under worker-mode,
/// though only the orchestrator drives it. C-V: ref-equality, not a merge-base —
/// see [`matches`].
pub(crate) fn run_branch_point_check(
    path: Option<PathBuf>,
    base: &str,
    head: Option<String>,
) -> anyhow::Result<()> {
    let root = root::find(path, &root::default_markers())?;
    let head = head.unwrap_or_else(|| "HEAD".to_owned());
    let base_sha = resolve_commit(&root, base)?;
    let head_sha = resolve_commit(&root, &head)?;
    if matches(&base_sha, &head_sha) {
        writeln!(io::stdout(), "stationary: HEAD == base {base_sha}")?;
        Ok(())
    } else {
        bail!("HEAD moved: base {base_sha} != HEAD {head_sha}");
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // --- branch-point-check pure compare (SL-031 PHASE-02, VT-1) ---

    #[test]
    fn matches_is_ref_equality() {
        assert!(matches("abc123", "abc123"), "equal shas ⇒ stationary");
        assert!(!matches("abc123", "def456"), "differing shas ⇒ moved");
        assert!(!matches("abc123", ""), "empty head ⇒ moved");
        assert!(
            matches("", ""),
            "degenerate equal ⇒ stationary (caller guards emptiness)"
        );
    }

    // --- T1: WITHHELD authority + .gitignore parity (VT-4) ---

    #[test]
    fn withheld_globs_all_compile() {
        for item in WITHHELD {
            Pattern::new(item.glob).unwrap();
        }
        for g in DERIVED_RUNTIME {
            Pattern::new(g).unwrap();
        }
    }

    /// A concrete sample path for a `.gitignore` runtime line: trailing-slash dirs
    /// gain a file; wildcards collapse to a literal segment.
    fn gitignore_representative(line: &str) -> String {
        let base = line
            .strip_suffix('/')
            .map_or_else(|| line.to_string(), |dir| format!("{dir}/f"));
        base.replace('*', "x")
    }

    fn classified(rep: &str) -> bool {
        WITHHELD
            .iter()
            .any(|item| glob_matches(&Pattern::new(item.glob).unwrap(), rep))
            || DERIVED_RUNTIME
                .iter()
                .any(|g| glob_matches(&Pattern::new(g).unwrap(), rep))
    }

    #[test]
    fn every_runtime_gitignore_glob_is_classified() {
        let gitignore = fs::read_to_string(".gitignore").unwrap();
        for raw in gitignore.lines() {
            let line = raw.trim();
            // Runtime-tier globs: `.doctrine/`-prefixed, non-negated, more specific
            // than the broad `.doctrine/*` exclude (the authored-tier negations are
            // `!`-prefixed and filtered here).
            if !line.starts_with(".doctrine/") || line == ".doctrine/*" {
                continue;
            }
            let rep = gitignore_representative(line);
            assert!(
                classified(&rep),
                "unclassified runtime gitignore glob `{line}` (rep `{rep}`) — \
                 add it to WITHHELD or DERIVED_RUNTIME"
            );
        }
    }

    // --- T2: parse_allowlist (VT-1) ---

    #[test]
    fn parse_allowlist_accepts_each_supported_class() {
        let text = "# a comment\n\nsrc/main.rs\nconfig/*.toml\n**/*.md\nfile?.txt\n";
        let allow = parse_allowlist(text).unwrap();
        assert_eq!(allow.patterns.len(), 4);
    }

    #[test]
    fn parse_allowlist_rejects_negation() {
        let err = parse_allowlist("src/*\n!secret").unwrap_err();
        assert!(matches!(err, ParseError::Negation { .. }));
    }

    #[test]
    fn parse_allowlist_rejects_anchoring() {
        let err = parse_allowlist("/anchored").unwrap_err();
        assert!(matches!(err, ParseError::Anchoring { .. }));
    }

    #[test]
    fn parse_allowlist_rejects_bad_glob() {
        let err = parse_allowlist("a[b").unwrap_err();
        assert!(matches!(err, ParseError::BadGlob { .. }));
    }

    // --- T3: is_withheld + select_copies (VT-3) ---

    #[test]
    fn is_withheld_classifies_each_tier() {
        assert_eq!(is_withheld(".doctrine/state/boot.md"), Some(Tier::State));
        assert_eq!(
            is_withheld(".doctrine/state/slice/029/phases/phase-01.md"),
            Some(Tier::State)
        );
        assert_eq!(
            is_withheld(".doctrine/slice/029/phases"),
            Some(Tier::PhaseLink)
        );
        assert_eq!(
            is_withheld(".doctrine/slice/029/handover.md"),
            Some(Tier::Handover)
        );
        assert_eq!(
            is_withheld(".doctrine/memory/index/foo"),
            Some(Tier::MemoryCache)
        );
        assert_eq!(is_withheld("src/main.rs"), None);
        // derived, not withheld
        assert_eq!(is_withheld(".doctrine/skills/code-review/SKILL.md"), None);
    }

    #[test]
    fn select_copies_withholds_tier_files_under_a_broad_glob() {
        let allow = parse_allowlist("**").unwrap();
        let candidates = vec![
            "src/main.rs".to_string(),
            ".doctrine/state/boot.md".to_string(),
            ".doctrine/slice/029/handover.md".to_string(),
        ];
        let sel = select_copies(&allow, &candidates);
        assert_eq!(sel.copy, ["src/main.rs"]);
        let held: Vec<&str> = sel.withheld.iter().map(|h| h.path.as_str()).collect();
        assert!(held.contains(&".doctrine/state/boot.md"));
        assert!(held.contains(&".doctrine/slice/029/handover.md"));
    }

    #[test]
    fn select_copies_skips_unallowlisted_candidates() {
        let allow = parse_allowlist("docs/**").unwrap();
        let candidates = vec!["src/main.rs".to_string(), "docs/guide.md".to_string()];
        let sel = select_copies(&allow, &candidates);
        assert_eq!(sel.copy, ["docs/guide.md"]);
        assert!(sel.withheld.is_empty());
    }

    // --- T4: allowlist_violations (VT-2) ---

    #[test]
    fn allowlist_violations_flags_a_tier_naming_pattern() {
        let allow = parse_allowlist(".doctrine/state/*").unwrap();
        let v = allowlist_violations(&allow);
        assert!(!v.is_empty());
        assert_eq!(v[0].tier, Tier::State);
    }

    #[test]
    fn allowlist_violations_passes_benign_patterns() {
        let allow = parse_allowlist("src/**\nconfig/app.toml").unwrap();
        assert!(allowlist_violations(&allow).is_empty());
    }

    #[test]
    fn allowlist_violations_flags_a_broad_wildcard() {
        // `**` names every tier — the static gate fails closed even though
        // select_copies would still protect at copy time.
        let allow = parse_allowlist("**").unwrap();
        assert!(!allowlist_violations(&allow).is_empty());
    }

    // --- T1: is_linked_worktree self-detection (SL-032 PHASE-04, VT-1) ---

    fn git(dir: &Path, args: &[&str]) {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .expect("spawn git");
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    /// A primary git repo with a base commit; returns the canonical root.
    fn init_repo(dir: &Path) -> PathBuf {
        fs::create_dir_all(dir).unwrap();
        git(dir, &["init", "-q", "-b", "main"]);
        git(dir, &["config", "user.email", "t@example.com"]);
        git(dir, &["config", "user.name", "Test"]);
        fs::write(dir.join("seed"), "x").unwrap();
        git(dir, &["add", "."]);
        git(dir, &["commit", "-q", "-m", "base"]);
        fs::canonicalize(dir).unwrap()
    }

    #[test]
    fn is_linked_worktree_true_for_a_fork_false_for_the_primary_tree() {
        let tmp = tempfile::tempdir().unwrap();
        let primary = init_repo(&tmp.path().join("src"));
        let fork = tmp.path().join("fork");
        git(
            &primary,
            &[
                "worktree",
                "add",
                "-q",
                "-b",
                "feat",
                fork.to_str().unwrap(),
            ],
        );
        let fork = fs::canonicalize(&fork).unwrap();

        assert!(is_linked_worktree(&fork).unwrap(), "a linked worktree");
        assert!(!is_linked_worktree(&primary).unwrap(), "the primary tree");
    }
}