mati 0.1.2

An enforcement layer for codebase knowledge: confirmed gotchas gate what AI agents read and edit at the hook level. Not a passive memory store.
Documentation
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! Output regression tests — protect user-facing CLI wording and structure.
//!
//! These tests verify the stable parts of mati's command output that define
//! the product experience: workflow framing, trust/provenance vocabulary,
//! section headers, guidance text, and "what next?" hints.
//!
//! Design principles:
//! - Assert on structural elements (section headers, guidance phrases), not exact counts/timing
//! - All commands run in non-TTY mode (piped stdout), so ANSI codes are stripped automatically
//! - Each test uses an isolated HOME + tempdir git repo for full store isolation
//! - Tests are fast: tiny repos, no network, no LLM calls
//!
//! # Running
//!
//! ```sh
//! cargo test --test output_regression
//! ```

use std::path::{Path, PathBuf};
use std::process::Command;

use tempfile::TempDir;

// ── Helpers ─────────────────────────────────────────────────────────────────

fn mati_bin() -> PathBuf {
    let env_key = "CARGO_BIN_EXE_MATI";
    if let Ok(p) = std::env::var(env_key) {
        return PathBuf::from(p);
    }
    let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
    PathBuf::from(manifest)
        .join("target")
        .join("debug")
        .join("mati")
}

/// Run mati with the given args, isolating HOME to `home` and CWD to `repo`.
fn run(bin: &Path, repo: &Path, home: &Path, args: &[&str]) -> (String, String, bool) {
    let out = Command::new(bin)
        .args(args)
        .current_dir(repo)
        .env("HOME", home)
        .env("NO_COLOR", "1") // belt-and-suspenders: some CLIs respect this
        .output()
        .expect("failed to run mati");
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
    (stdout, stderr, out.status.success())
}

/// Create a minimal git repo with one Rust file and one commit.
/// Returns (repo_dir, home_dir) — both are TempDirs that must be kept alive.
fn setup_repo() -> (TempDir, TempDir) {
    let repo_dir = TempDir::new().expect("create repo dir");
    let home_dir = TempDir::new().expect("create home dir");
    let repo = repo_dir.path();

    // git init + configure identity
    Command::new("git")
        .args(["init"])
        .current_dir(repo)
        .output()
        .expect("git init");
    Command::new("git")
        .args(["config", "user.email", "test@test.com"])
        .current_dir(repo)
        .output()
        .expect("git config email");
    Command::new("git")
        .args(["config", "user.name", "Test"])
        .current_dir(repo)
        .output()
        .expect("git config name");

    // Create src/main.rs
    std::fs::create_dir_all(repo.join("src")).expect("mkdir src");
    std::fs::write(
        repo.join("src/main.rs"),
        r#"fn main() {
    println!("hello");
}

fn helper() -> Result<(), Box<dyn std::error::Error>> {
    // TODO: handle error properly
    let x = std::fs::read_to_string("config.toml")?;
    Ok(())
}
"#,
    )
    .expect("write main.rs");

    // Create src/lib.rs (for co-change / multi-file tests)
    std::fs::write(
        repo.join("src/lib.rs"),
        r#"pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
"#,
    )
    .expect("write lib.rs");

    // Create Cargo.toml
    std::fs::write(
        repo.join("Cargo.toml"),
        r#"[package]
name = "test-project"
version = "0.1.0"
edition = "2021"
"#,
    )
    .expect("write Cargo.toml");

    // Initial commit
    Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo)
        .output()
        .expect("git add");
    Command::new("git")
        .args(["commit", "-m", "initial commit"])
        .current_dir(repo)
        .output()
        .expect("git commit");

    (repo_dir, home_dir)
}

/// Run `mati init --no-hooks` and return stdout.
fn init_repo(bin: &Path, repo: &Path, home: &Path) -> String {
    let (stdout, stderr, ok) = run(bin, repo, home, &["init", "--no-hooks"]);
    if !ok {
        panic!("mati init failed:\nstdout: {stdout}\nstderr: {stderr}");
    }
    stdout
}

/// Run `mati init --codex` after creating a repo-local `.codex/` dir.
fn init_repo_codex(bin: &Path, repo: &Path, home: &Path) -> String {
    std::fs::create_dir_all(repo.join(".codex")).expect("mkdir .codex");
    let (stdout, stderr, ok) = run(bin, repo, home, &["init", "--codex"]);
    if !ok {
        panic!("mati init --codex failed:\nstdout: {stdout}\nstderr: {stderr}");
    }
    stdout
}

/// Run plain `mati init` in a repo that already has `.codex/`.
fn init_repo_autodetect_codex(bin: &Path, repo: &Path, home: &Path) -> String {
    std::fs::create_dir_all(repo.join(".codex")).expect("mkdir .codex");
    let (stdout, stderr, ok) = run(bin, repo, home, &["init"]);
    if !ok {
        panic!("mati init failed in codex repo:\nstdout: {stdout}\nstderr: {stderr}");
    }
    stdout
}

// Strip ANSI escape codes (safety net if NO_COLOR isn't respected)
fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut in_escape = false;
    for c in s.chars() {
        if c == '\x1b' {
            in_escape = true;
            continue;
        }
        if in_escape {
            if c.is_ascii_alphabetic() {
                in_escape = false;
            }
            continue;
        }
        out.push(c);
    }
    out
}

fn assert_contains(haystack: &str, needle: &str) {
    let clean = strip_ansi(haystack);
    assert!(
        clean.contains(needle),
        "Expected output to contain: {needle:?}\n\n--- Actual output ---\n{clean}"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

// ── 1. Top-level help: workflow framing ─────────────────────────────────────

#[test]
fn help_workflow_framing() {
    let bin = mati_bin();
    let (stdout, _stderr, ok) = run(&bin, Path::new("."), Path::new("/tmp"), &["--help"]);
    assert!(ok, "mati --help should succeed");
    let out = strip_ansi(&stdout);

    // Product identity (long_about shown with --help)
    assert_contains(&out, "persistent, queryable knowledge store");

    // Core workflow commands must appear
    assert_contains(&out, "mati init");
    assert_contains(&out, "mati explain <file>");
    assert_contains(&out, "mati diff <range>");
    assert_contains(&out, "mati status");

    // Workflow role descriptions
    assert_contains(&out, "build project memory");
    assert_contains(&out, "file briefing");
    assert_contains(&out, "pre-merge check");
    assert_contains(&out, "project memory dashboard");
}

#[test]
fn help_subcommands_present() {
    let bin = mati_bin();
    let (stdout, _stderr, ok) = run(&bin, Path::new("."), Path::new("/tmp"), &["--help"]);
    assert!(ok);
    let out = strip_ansi(&stdout);

    // Core workflow
    for cmd in &["init", "explain", "diff", "status"] {
        assert_contains(&out, cmd);
    }

    // Knowledge management
    for cmd in &["gotcha", "show", "gaps", "stats"] {
        assert_contains(&out, cmd);
    }

    // Maintenance
    for cmd in &["review", "repair", "stale"] {
        assert_contains(&out, cmd);
    }

    // Infrastructure
    for cmd in &["serve", "daemon", "ping"] {
        assert_contains(&out, cmd);
    }
}

// ── 2. Init: summary structure and next steps ──────────────────────────────

#[test]
fn init_next_steps_guidance() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    let stdout = init_repo(&bin, repo_dir.path(), home_dir.path());

    // Project header
    assert_contains(&stdout, "mati");

    // Summary metrics (labels, not values — values vary)
    assert_contains(&stdout, "file records:");
    assert_contains(&stdout, "graph edges:");

    // Zero-token claim
    assert_contains(&stdout, "0 tokens");
    assert_contains(&stdout, "0 Claude calls");

    // Next steps — the most important product guidance
    assert_contains(&stdout, "Next steps");
    assert_contains(&stdout, "mati explain");
    assert_contains(&stdout, "mati review");
    assert_contains(&stdout, "mati status");

    // Next steps descriptions (setup_repo always has a hotspot, so explain shows hotspot path)
    assert_contains(&stdout, "start here");
    assert_contains(&stdout, "candidates for hook enforcement");
    assert_contains(&stdout, "project knowledge dashboard");
}

#[test]
fn init_summary_has_candidate_categories() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    let stdout = init_repo(&bin, repo_dir.path(), home_dir.path());

    // Layer 0 candidate categories
    assert_contains(&stdout, "gotcha candidates:");
    assert_contains(&stdout, "dep records:");
    assert_contains(&stdout, "hotspot files:");
}

#[test]
fn init_codex_reports_platform_capability() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    let stdout = init_repo_codex(&bin, repo_dir.path(), home_dir.path());

    assert_contains(&stdout, "integration:");
    assert_contains(&stdout, "Codex");
    assert_contains(&stdout, "Enforcement");
    assert_contains(&stdout, "Bash reads blocked");
    assert_contains(&stdout, "gotchas injected on prompt submit");
}

#[test]
fn init_autodetects_codex_without_forcing_claude() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    let stdout = init_repo_autodetect_codex(&bin, repo_dir.path(), home_dir.path());

    assert_contains(&stdout, "integration:");
    assert_contains(&stdout, "Codex");
    assert!(
        !strip_ansi(&stdout).contains("Claude + Codex"),
        "plain init in a codex-only repo should not force Claude installation\n--- stdout ---\n{}",
        strip_ansi(&stdout)
    );
}

// ── 3. Explain: output sections and trust cues ─────────────────────────────

#[test]
fn explain_output_structure() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    let (stdout, _stderr, ok) = run(
        &bin,
        repo_dir.path(),
        home_dir.path(),
        &["explain", "src/main.rs"],
    );
    assert!(ok, "mati explain should succeed");

    // Header: filename + purpose line
    assert_contains(&stdout, "main.rs");

    // Trust cues present in metadata line
    assert_contains(&stdout, "confidence");
    assert_contains(&stdout, "quality");
    assert_contains(&stdout, "source:");

    // Guidance for uncaptured state — file has no gotchas after init
    // Should suggest adding one
    assert_contains(&stdout, "mati gotcha add");
}

#[test]
fn explain_todo_section() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    let (stdout, _stderr, ok) = run(
        &bin,
        repo_dir.path(),
        home_dir.path(),
        &["explain", "src/main.rs"],
    );
    assert!(ok);

    // Our test file has a TODO comment — explain should surface it
    assert_contains(&stdout, "TODOs");
    assert_contains(&stdout, "handle error");
}

#[test]
fn explain_missing_file_suggests_init() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    let (stdout, stderr, _ok) = run(
        &bin,
        repo_dir.path(),
        home_dir.path(),
        &["explain", "nonexistent/file.rs"],
    );
    let combined = format!("{stdout}{stderr}");

    // Should tell the user what to do
    assert_contains(&combined, "mati init");
}

// ── 4. Diff: symbols, summary, and guidance ────────────────────────────────

#[test]
fn diff_output_structure() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    let repo = repo_dir.path();
    init_repo(&bin, repo, home_dir.path());

    // Add a second commit so we have a diff range
    std::fs::write(
        repo.join("src/main.rs"),
        r#"fn main() {
    println!("updated");
}
"#,
    )
    .expect("update main.rs");
    Command::new("git")
        .args(["add", "src/main.rs"])
        .current_dir(repo)
        .output()
        .expect("git add");
    Command::new("git")
        .args(["commit", "-m", "update main"])
        .current_dir(repo)
        .output()
        .expect("git commit");

    let (stdout, _stderr, ok) = run(&bin, repo, home_dir.path(), &["diff", "HEAD~1"]);
    assert!(ok, "mati diff should succeed");

    // Header per README: "PRE-MERGE CHECK — N files changed"
    assert_contains(&stdout, "PRE-MERGE CHECK");
    assert_contains(&stdout, "changed");

    // Status vocabulary (at least one of these per file)
    let has_symbol = stdout.contains("documented")
        || stdout.contains("no file record")
        || stdout.contains("gotcha");
    assert!(
        has_symbol,
        "diff output should classify files\n--- stdout ---\n{stdout}"
    );

    // Severity column appears for every file
    let has_severity = stdout.contains("CRITICAL")
        || stdout.contains("HIGH")
        || stdout.contains("NORMAL")
        || stdout.contains("UNKNOWN");
    assert!(
        has_severity,
        "diff output should show a severity marker per file\n--- stdout ---\n{stdout}"
    );
}

#[test]
fn diff_summary_line_format() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    let repo = repo_dir.path();
    init_repo(&bin, repo, home_dir.path());

    // Second commit
    std::fs::write(
        repo.join("src/lib.rs"),
        "pub fn sub(a: i32, b: i32) -> i32 { a - b }\n",
    )
    .expect("update lib.rs");
    Command::new("git")
        .args(["add", "src/lib.rs"])
        .current_dir(repo)
        .output()
        .expect("git add");
    Command::new("git")
        .args(["commit", "-m", "update lib"])
        .current_dir(repo)
        .output()
        .expect("git commit");

    let (stdout, _stderr, ok) = run(&bin, repo, home_dir.path(), &["diff", "HEAD~1"]);
    assert!(ok);

    // Summary line must include all three counters per README
    assert_contains(&stdout, "Summary:");
    assert_contains(&stdout, "warned");
    assert_contains(&stdout, "documented");
    assert_contains(&stdout, "unknown");
}

// ── 5. Status: dashboard sections and trust vocabulary ─────────────────────

#[test]
fn status_dashboard_sections() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    let (stdout, _stderr, ok) = run(&bin, repo_dir.path(), home_dir.path(), &["status"]);
    assert!(ok, "mati status should succeed");

    // Dashboard header
    assert_contains(&stdout, "mati status");

    // Core sections
    assert_contains(&stdout, "Records");
    assert_contains(&stdout, "Confirmed");
    assert_contains(&stdout, "Confidence");
    assert_contains(&stdout, "Hotspots");

    // Record type vocabulary
    assert_contains(&stdout, "files");
    assert_contains(&stdout, "gotchas");
}

#[test]
fn status_trust_section_with_unconfirmed() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    let (stdout, _stderr, ok) = run(&bin, repo_dir.path(), home_dir.path(), &["status"]);
    assert!(ok);

    // After init, there are unconfirmed candidates — trust section should appear
    // with guidance to run review. If no gotcha candidates were generated,
    // the "No gotchas yet" guidance should appear instead.
    let has_trust_guidance = stdout.contains("mati review") || stdout.contains("No gotchas yet");
    assert!(
        has_trust_guidance,
        "status should show trust guidance or no-gotchas hint\n--- stdout ---\n{stdout}"
    );
}

// ── 6. Repair: check mode output ───────────────────────────────────────────

#[test]
fn repair_check_clean_state() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    let (stdout, _stderr, ok) = run(
        &bin,
        repo_dir.path(),
        home_dir.path(),
        &["repair", "--check"],
    );
    // After a clean init, there should be no drift → exit 0
    assert!(ok, "repair --check should succeed on clean state");

    // Must report what was scanned
    assert_contains(&stdout, "mati repair --check");
    assert_contains(&stdout, "gotchas");
    assert_contains(&stdout, "files");

    // Clean state message
    assert_contains(&stdout, "No drift detected");
    assert_contains(&stdout, "consistent");
}

#[test]
fn repair_check_json_output() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    let (stdout, _stderr, ok) = run(
        &bin,
        repo_dir.path(),
        home_dir.path(),
        &["repair", "--check", "--json"],
    );
    assert!(ok, "repair --check --json should succeed on clean state");

    // Output should be valid JSON with expected fields
    let v: serde_json::Value = serde_json::from_str(stdout.trim())
        .expect("repair --check --json should produce valid JSON");
    assert!(
        v.get("scanned_gotchas").is_some(),
        "JSON should have scanned_gotchas"
    );
    assert!(
        v.get("scanned_files").is_some(),
        "JSON should have scanned_files"
    );
}

// ── 7. Review help: explains the workflow ──────────────────────────────────

#[test]
fn review_help_explains_workflow() {
    let bin = mati_bin();
    let (stdout, _stderr, ok) = run(
        &bin,
        Path::new("."),
        Path::new("/tmp"),
        &["review", "--help"],
    );
    assert!(ok, "mati review --help should succeed");

    // Must explain what candidates are and what confirmation enables
    assert_contains(&stdout, "auto-detected");
    assert_contains(&stdout, "hook enforcement");
    assert_contains(&stdout, "candidates");
}

// ── 8. Repair help: explains trust semantics ───────────────────────────────

#[test]
fn repair_help_explains_semantics() {
    let bin = mati_bin();
    let (stdout, _stderr, ok) = run(
        &bin,
        Path::new("."),
        Path::new("/tmp"),
        &["repair", "--help"],
    );
    assert!(ok, "mati repair --help should succeed");

    // Must reference canonical records
    assert_contains(&stdout, "canonical");

    // --check flag documented with CI mention
    assert_contains(&stdout, "--check");
    assert_contains(&stdout, "CI");

    // --fast flag documented with integrity caveat
    assert_contains(&stdout, "--fast");
    assert_contains(&stdout, "integrity");
}

#[test]
fn status_shows_codex_platform_mode() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    let repo = repo_dir.path();
    init_repo_codex(&bin, repo, home_dir.path());

    let (stdout, _stderr, ok) = run(&bin, repo, home_dir.path(), &["status"]);
    assert!(ok, "mati status should succeed");

    assert_contains(&stdout, "Platform");
    assert_contains(&stdout, "Codex");
    assert_contains(&stdout, "hard Bash enforcement");
    assert_contains(&stdout, "soft native-read enforcement");
}

// ── 9. Explain help: describes the briefing ────────────────────────────────

#[test]
fn explain_help_describes_briefing() {
    let bin = mati_bin();
    let (stdout, _stderr, ok) = run(
        &bin,
        Path::new("."),
        Path::new("/tmp"),
        &["explain", "--help"],
    );
    assert!(ok);

    assert_contains(&stdout, "briefing");
    assert_contains(&stdout, "gotchas");
    assert_contains(&stdout, "decisions");
    assert_contains(&stdout, "co-change");
}

// ── 10. Diff help: describes pre-merge use case ────────────────────────────

#[test]
fn diff_help_describes_premerge() {
    let bin = mati_bin();
    let (stdout, _stderr, ok) = run(&bin, Path::new("."), Path::new("/tmp"), &["diff", "--help"]);
    assert!(ok);

    assert_contains(&stdout, "Pre-merge");
    assert_contains(&stdout, "gotchas");

    // Range argument with examples
    assert_contains(&stdout, "main");
}

// ── 11. History --enforcement: formatted timeline output ───────────────────

/// Empty enforcement log produces a clear "no events" message — never the
/// raw `gotcha_above_threshold` repetition or `ERROR/WARN: None found.` shape
/// from earlier internal builds.
#[test]
fn history_enforcement_empty_state_is_explicit() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    let (stdout, _stderr, ok) = run(
        &bin,
        repo_dir.path(),
        home_dir.path(),
        &["history", "--enforcement", "--limit", "10"],
    );
    assert!(ok, "mati history --enforcement should succeed on empty log");

    let clean = strip_ansi(&stdout);
    assert!(
        clean.contains("No enforcement events"),
        "empty enforcement log must use the explicit 'No enforcement events' \
         message, never the legacy 'None found' / 'No errors or warnings' wording.\n\
         --- stdout ---\n{clean}"
    );
    assert!(
        !clean.contains("None found"),
        "legacy 'None found' wording leaked back in:\n{clean}"
    );
    assert!(
        !clean.contains("No errors or warnings"),
        "legacy summary wording leaked back in:\n{clean}"
    );
}

/// `--type config_changed` filters events by the documented label, even on
/// an empty log. Guards against the legacy fallback that ignored the filter
/// and dumped every gotcha-above-threshold event verbatim.
#[test]
fn history_enforcement_type_filter_accepts_documented_labels() {
    let bin = mati_bin();
    let (repo_dir, home_dir) = setup_repo();
    init_repo(&bin, repo_dir.path(), home_dir.path());

    for label in &[
        "deny",
        "allow_receipt",
        "control_changed",
        "config_changed",
        "gap",
    ] {
        let (stdout, stderr, ok) = run(
            &bin,
            repo_dir.path(),
            home_dir.path(),
            &["history", "--enforcement", "--type", label, "--limit", "5"],
        );
        assert!(
            ok,
            "history --enforcement --type {label} should succeed\n\
             stdout: {stdout}\nstderr: {stderr}"
        );
    }
}

/// `--enforcement` help advertises the documented event-type vocabulary and
/// the file-filter so users can find the typed filters from the CLI.
#[test]
fn history_enforcement_help_lists_event_types() {
    let bin = mati_bin();
    let (stdout, _stderr, ok) = run(
        &bin,
        Path::new("."),
        Path::new("/tmp"),
        &["history", "--help"],
    );
    assert!(ok);
    let clean = strip_ansi(&stdout);

    // The flag itself
    assert!(
        clean.contains("--enforcement"),
        "history --help should advertise --enforcement:\n{clean}"
    );

    // Type filter and at least the labels referenced in the smoke test
    assert!(
        clean.contains("--type"),
        "history --help should advertise --type:\n{clean}"
    );
    for label in &["control_changed", "config_changed"] {
        assert!(
            clean.contains(label),
            "history --help should mention type label {label}:\n{clean}"
        );
    }
}