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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! `mati check` — verify the full hook enforcement pipeline is operational.
//!
//! Runs 7 checks in order, collects results, prints aligned output, then exits
//! with code 1 if any check failed. Warnings do not affect the exit code.
//!
//! Also exposes [`run_silent`] for use by `mati init` to surface warnings at
//! the end of the init flow without re-implementing all checks.

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

use anyhow::Result;
use mati_core::scaffold::codex::CODEX_HOOK_SCRIPTS;
use mati_core::scaffold::settings::HOOK_SCRIPTS;

use crate::cli::daemon::{daemon_result, mati_root_for, DaemonResult};

// ── Result types ─────────────────────────────────────────────────────────────

#[derive(Debug)]
pub struct CheckItem {
    /// Short label, padded to 15 chars when printed.
    pub label: &'static str,
    pub status: CheckStatus,
    /// Multi-line hints printed below the status line on Warn/Fail.
    pub hint: Option<String>,
}

#[derive(Debug)]
pub enum CheckStatus {
    Pass(Option<String>),
    Warn(String),
    Fail(String),
}

impl CheckItem {
    fn pass(label: &'static str, detail: Option<String>) -> Self {
        Self {
            label,
            status: CheckStatus::Pass(detail),
            hint: None,
        }
    }

    fn warn(label: &'static str, msg: impl Into<String>, hint: impl Into<Option<String>>) -> Self {
        Self {
            label,
            status: CheckStatus::Warn(msg.into()),
            hint: hint.into(),
        }
    }

    fn fail(label: &'static str, msg: impl Into<String>, hint: impl Into<Option<String>>) -> Self {
        Self {
            label,
            status: CheckStatus::Fail(msg.into()),
            hint: hint.into(),
        }
    }

    pub fn is_fail(&self) -> bool {
        matches!(self.status, CheckStatus::Fail(_))
    }
}

// ── Public entry points ───────────────────────────────────────────────────────

/// Run all checks, print aligned output, exit 1 if any FAIL.
pub async fn run() -> Result<()> {
    let cwd = std::env::current_dir()?;
    let items = run_silent(&cwd).await;
    print_results(&items);
    let failures = items.iter().filter(|i| i.is_fail()).count();
    if failures > 0 {
        std::process::exit(1);
    }
    Ok(())
}

/// Run all checks and return results without printing anything.
/// Used by `mati init` to surface warnings at the end of init.
pub async fn run_silent(cwd: &Path) -> Vec<CheckItem> {
    let mut items = Vec::with_capacity(10);

    // ── Check 1: git repo ────────────────────────────────────────────────────
    items.push(check_git_repo(cwd));

    // ── Check 2: store initialized ───────────────────────────────────────────
    let (store_item, mati_root_opt) = check_store(cwd);
    items.push(store_item);

    // ── Check 3: mati on PATH ────────────────────────────────────────────────
    items.push(check_mati_on_path());

    // ── Check 4: awk float math ──────────────────────────────────────────────
    items.push(check_awk_float_math());

    // ── Check 5: at least one agent host wired ───────────────────────────────
    items.push(check_agent_host(cwd));

    // ── Checks 6–9: per-host hook wiring (Claude + Codex) ─────────────────────
    // Each is gated on the host's directory. A project using only one agent
    // reports the other host as "not configured" (Pass), never a false failure
    // — Codex-only and Claude-only are both first-class (see `mati hooks`).
    items.push(check_claude_hooks(cwd));
    items.push(check_claude_config(cwd));
    items.push(check_codex_hooks(cwd));
    items.push(check_codex_config(cwd));

    // ── Check 10: daemon reachable ───────────────────────────────────────────
    items.push(check_daemon(mati_root_opt).await);

    items
}

// ── Individual checks ─────────────────────────────────────────────────────────

fn check_git_repo(cwd: &Path) -> CheckItem {
    match git2::Repository::discover(cwd) {
        Ok(_) => CheckItem::pass("git repo", None),
        Err(_) => CheckItem::fail(
            "git repo",
            "not a git repo",
            Some("Layer 0 analysis and slug derivation require git".to_string()),
        ),
    }
}

/// Returns the check item and, if the store path is derivable, the mati root
/// path (needed for check 7). Does NOT call `Store::open()` — just checks file
/// existence to avoid racing with a running daemon.
fn check_store(cwd: &Path) -> (CheckItem, Option<PathBuf>) {
    let root = match mati_root_for(cwd) {
        Ok(r) => r,
        Err(e) => {
            return (
                CheckItem::fail(
                    "store",
                    format!("cannot derive store path: {e}"),
                    None::<String>,
                ),
                None,
            );
        }
    };

    let db_path = root.join("knowledge.db");
    if !db_path.exists() {
        return (
            CheckItem::fail(
                "store",
                "store not initialized",
                Some("run: mati init".to_string()),
            ),
            Some(root),
        );
    }

    let detail = format!("{}", db_path.display());
    (CheckItem::pass("store", Some(detail)), Some(root))
}

fn check_mati_on_path() -> CheckItem {
    let result = std::process::Command::new("mati")
        .arg("--version")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output();

    match result {
        Ok(out) if out.status.success() => {
            let version = String::from_utf8_lossy(&out.stdout).trim().to_string();
            CheckItem::pass("mati in PATH", Some(version))
        }
        Ok(_) => CheckItem::fail(
            "mati in PATH",
            "mati --version returned non-zero",
            Some(
                "hooks call mati get/log-hit/etc. and will silently pass everything through"
                    .to_string(),
            ),
        ),
        Err(_) => CheckItem::fail(
            "mati in PATH",
            "mati not on PATH",
            Some(
                "hooks call mati get/log-hit/etc. and will silently pass everything through"
                    .to_string(),
            ),
        ),
    }
}

fn check_awk_float_math() -> CheckItem {
    // Hooks use awk for float comparison: `awk "BEGIN { exit !(0.7 >= 0.6) }"`
    // Exit code 0 = true, non-zero = false.
    let result = std::process::Command::new("sh")
        .arg("-c")
        .arg(r#"awk "BEGIN { exit !(0.7 >= 0.6) }" && echo ok"#)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output();

    match result {
        Ok(out) => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            if stdout.trim() == "ok" {
                CheckItem::pass("awk float math", None)
            } else {
                CheckItem::fail(
                    "awk float math",
                    "awk float math failed",
                    Some(
                        "pre-read hook decision matrix will silently allow all reads until fixed"
                            .to_string(),
                    ),
                )
            }
        }
        Err(_) => CheckItem::fail(
            "awk float math",
            "awk not found",
            Some(
                "pre-read hook decision matrix requires awk — install gawk or ensure awk is on PATH"
                    .to_string(),
            ),
        ),
    }
}

/// At least one agent host (`.claude/` or `.codex/`) must be wired, or there is
/// no enforcement at all. Fails only when neither is present — otherwise it is
/// the single signal that catches "store exists, but nothing is enforcing it".
fn check_agent_host(cwd: &Path) -> CheckItem {
    let has_claude = cwd.join(".claude").is_dir();
    let has_codex = cwd.join(".codex").is_dir();
    match (has_claude, has_codex) {
        (false, false) => CheckItem::fail(
            "agent host",
            "no agent host wired — neither .claude/ nor .codex/ present",
            Some("run: mati hooks --claude  (or --codex)".to_string()),
        ),
        (true, true) => CheckItem::pass("agent host", Some("claude + codex".to_string())),
        (true, false) => CheckItem::pass("agent host", Some("claude".to_string())),
        (false, true) => CheckItem::pass("agent host", Some("codex".to_string())),
    }
}

/// Claude hook scripts present + executable under `.claude/hooks/`.
/// Gated on `.claude/` existing so a Codex-only project isn't failed.
fn check_claude_hooks(cwd: &Path) -> CheckItem {
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    if !cwd.join(".claude").is_dir() {
        return CheckItem::pass("claude hooks", Some("not configured".to_string()));
    }

    let hooks_dir = cwd.join(".claude").join("hooks");
    let total = HOOK_SCRIPTS.len();
    let mut missing: Vec<String> = Vec::new();
    let mut not_exec: Vec<String> = Vec::new();

    for (name, _) in HOOK_SCRIPTS {
        let path = hooks_dir.join(name);
        if !path.exists() {
            missing.push(name.to_string());
            continue;
        }
        #[cfg(unix)]
        match std::fs::metadata(&path) {
            Ok(meta) => {
                let mode = meta.permissions().mode();
                if mode & 0o111 == 0 {
                    not_exec.push(name.to_string());
                }
            }
            Err(_) => {
                missing.push(name.to_string());
            }
        }
    }

    if missing.is_empty() && not_exec.is_empty() {
        return CheckItem::pass(
            "claude hooks",
            Some(format!("{total}/{total} installed, executable")),
        );
    }

    let mut problems = Vec::new();
    if !missing.is_empty() {
        problems.push(format!("missing: {}", missing.join(", ")));
    }
    if !not_exec.is_empty() {
        problems.push(format!("not executable: {}", not_exec.join(", ")));
    }

    CheckItem::fail(
        "claude hooks",
        format!(
            "{}/{total} ok — {}",
            total - missing.len() - not_exec.len(),
            problems.join("; ")
        ),
        Some("run: mati hooks --claude  to reinstall".to_string()),
    )
}

/// Codex hook scripts present + executable under `.codex/hooks/`.
/// Gated on `.codex/` existing so a Claude-only project isn't failed.
fn check_codex_hooks(cwd: &Path) -> CheckItem {
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    if !cwd.join(".codex").is_dir() {
        return CheckItem::pass("codex hooks", Some("not configured".to_string()));
    }

    let hooks_dir = cwd.join(".codex").join("hooks");
    let total = CODEX_HOOK_SCRIPTS.len();
    let mut missing: Vec<String> = Vec::new();
    let mut not_exec: Vec<String> = Vec::new();

    for (name, _) in CODEX_HOOK_SCRIPTS {
        let path = hooks_dir.join(name);
        if !path.exists() {
            missing.push(name.to_string());
            continue;
        }
        #[cfg(unix)]
        match std::fs::metadata(&path) {
            Ok(meta) => {
                let mode = meta.permissions().mode();
                if mode & 0o111 == 0 {
                    not_exec.push(name.to_string());
                }
            }
            Err(_) => {
                missing.push(name.to_string());
            }
        }
    }

    if missing.is_empty() && not_exec.is_empty() {
        return CheckItem::pass(
            "codex hooks",
            Some(format!("{total}/{total} installed, executable")),
        );
    }

    let mut problems = Vec::new();
    if !missing.is_empty() {
        problems.push(format!("missing: {}", missing.join(", ")));
    }
    if !not_exec.is_empty() {
        problems.push(format!("not executable: {}", not_exec.join(", ")));
    }

    CheckItem::fail(
        "codex hooks",
        format!(
            "{}/{total} ok — {}",
            total - missing.len() - not_exec.len(),
            problems.join("; ")
        ),
        Some("run: mati hooks --codex  to reinstall".to_string()),
    )
}

/// Claude `settings.json` registers every hook + the mati MCP server.
/// Gated on `.claude/` existing.
fn check_claude_config(cwd: &Path) -> CheckItem {
    if !cwd.join(".claude").is_dir() {
        return CheckItem::pass("claude config", Some("not configured".to_string()));
    }

    let path = cwd.join(".claude").join("settings.json");
    if !path.exists() {
        return CheckItem::fail(
            "claude config",
            "settings.json not found",
            Some("run: mati hooks --claude".to_string()),
        );
    }

    let content = match std::fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) => {
            return CheckItem::fail(
                "claude config",
                format!("cannot read settings.json: {e}"),
                None::<String>,
            );
        }
    };

    let json: serde_json::Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(e) => {
            return CheckItem::fail(
                "claude config",
                format!("invalid JSON: {e}"),
                Some("run: mati hooks --claude  to regenerate settings.json".to_string()),
            );
        }
    };

    // Check that each hook script path appears somewhere in the JSON content.
    let mut absent_hooks: Vec<&str> = Vec::new();
    for (name, _) in HOOK_SCRIPTS {
        let hook_path = format!(".claude/hooks/{name}");
        if !content.contains(&hook_path) {
            absent_hooks.push(name);
        }
    }

    // Check mcpServers.mati exists.
    let mcp_ok = json.get("mcpServers").and_then(|s| s.get("mati")).is_some();

    if absent_hooks.is_empty() && mcp_ok {
        return CheckItem::pass(
            "claude config",
            Some(format!(
                "{} hooks + mcpServers registered",
                HOOK_SCRIPTS.len()
            )),
        );
    }

    let mut problems = Vec::new();
    if !absent_hooks.is_empty() {
        problems.push(format!("hooks absent: {}", absent_hooks.join(", ")));
    }
    if !mcp_ok {
        problems.push("mcpServers.mati missing".to_string());
    }

    CheckItem::fail(
        "claude config",
        problems.join("; "),
        Some("run: mati hooks --claude  to regenerate settings.json".to_string()),
    )
}

/// Codex wiring: `.codex/hooks.json` registers every hook script and
/// `.codex/config.toml` registers the mati MCP server. Gated on `.codex/`.
fn check_codex_config(cwd: &Path) -> CheckItem {
    if !cwd.join(".codex").is_dir() {
        return CheckItem::pass("codex config", Some("not configured".to_string()));
    }

    let codex_dir = cwd.join(".codex");
    let mut problems: Vec<String> = Vec::new();

    // hooks.json — must parse and reference each hook script path.
    match std::fs::read_to_string(codex_dir.join("hooks.json")) {
        Ok(content) => {
            if serde_json::from_str::<serde_json::Value>(&content).is_err() {
                problems.push("hooks.json: invalid JSON".to_string());
            } else {
                let absent: Vec<&str> = CODEX_HOOK_SCRIPTS
                    .iter()
                    .map(|(n, _)| *n)
                    .filter(|n| !content.contains(&format!(".codex/hooks/{n}")))
                    .collect();
                if !absent.is_empty() {
                    problems.push(format!("hooks.json: scripts absent: {}", absent.join(", ")));
                }
            }
        }
        Err(_) => problems.push("hooks.json: not found".to_string()),
    }

    // config.toml — must register the mati MCP server. A substring match keeps
    // this dependency-free and mirrors the Claude settings.json check;
    // toml_edit writes the table header `[mcp_servers.mati]`.
    match std::fs::read_to_string(codex_dir.join("config.toml")) {
        Ok(content) => {
            if !content.contains("mcp_servers.mati") {
                problems.push("config.toml: mcp_servers.mati missing".to_string());
            }
        }
        Err(_) => problems.push("config.toml: not found".to_string()),
    }

    if problems.is_empty() {
        return CheckItem::pass(
            "codex config",
            Some("hooks.json + mcp_servers.mati registered".to_string()),
        );
    }

    CheckItem::fail(
        "codex config",
        problems.join("; "),
        Some("run: mati hooks --codex  to regenerate".to_string()),
    )
}

async fn check_daemon(mati_root_opt: Option<PathBuf>) -> CheckItem {
    let root = match mati_root_opt {
        Some(r) => r,
        None => {
            return CheckItem::warn("daemon", "skipped (store not initialized)", None::<String>);
        }
    };

    let t0 = std::time::Instant::now();
    let result = daemon_result(&root, "ping", serde_json::json!({})).await;
    let latency = t0.elapsed();

    match result {
        DaemonResult::Ok(_) => {
            let ms = latency.as_secs_f64() * 1000.0;
            CheckItem::pass("daemon", Some(format!("ping {ms:.1}ms")))
        }
        // Not running at rest is benign: the daemon idle-shuts-down after
        // 30min and auto-starts on demand via `ensure_daemon` when a hook or
        // `mati serve` next runs. Enforcement is not degraded — the first call
        // just pays ~150ms spawn latency. Mirror `mati doctor`, which treats
        // this as informational rather than a warning, so `mati check` doesn't
        // print a misleading "degraded" banner for the normal idle state.
        DaemonResult::NotRunning => CheckItem::pass(
            "daemon",
            Some("not running (OK — auto-starts on demand; ~150ms on first call)".to_string()),
        ),
        // A stale socket is a real anomaly (a dead daemon left its socket
        // behind), so it stays a warning with a cleanup hint.
        DaemonResult::StaleSocket => CheckItem::warn(
            "daemon",
            "stale socket detected",
            Some("run: mati daemon stop  to clean up".to_string()),
        ),
        DaemonResult::Unresponsive => CheckItem::fail(
            "daemon",
            "daemon unresponsive — may hold store lock",
            Some("fix: mati daemon stop && mati daemon start".to_string()),
        ),
    }
}

// ── Output ────────────────────────────────────────────────────────────────────

fn print_results(items: &[CheckItem]) {
    println!("\nmati check\n");

    for item in items {
        print_item(item);
    }

    println!();

    let failures = items.iter().filter(|i| i.is_fail()).count();
    let warnings = items
        .iter()
        .filter(|i| matches!(i.status, CheckStatus::Warn(_)))
        .count();

    if failures == 0 && warnings == 0 {
        println!("  All checks passed. Hook enforcement is active.");
    } else if failures == 0 {
        println!(
            "  {} warning(s). Hook enforcement is active but degraded.",
            warnings
        );
    } else {
        println!(
            "  {} blocker(s) found. Hook enforcement is NOT active.",
            failures
        );
    }
    println!();
}

/// Print a single check line, with continuation lines for hints.
fn print_item(item: &CheckItem) {
    // Label column: 15 chars, left-padded with 2 spaces for indent.
    let label = format!("  {:<15}", item.label);

    match &item.status {
        CheckStatus::Pass(extra) => {
            let extra_str = extra.as_deref().unwrap_or("");
            if extra_str.is_empty() {
                println!("{label}  ok");
            } else {
                println!("{label}  ok  ({extra_str})");
            }
        }
        CheckStatus::Warn(msg) => {
            println!("{label}  warn  {msg}");
            if let Some(hint) = &item.hint {
                for line in hint.lines() {
                    println!("{:19}       {line}", "");
                }
            }
        }
        CheckStatus::Fail(msg) => {
            println!("{label}  FAIL  {msg}");
            if let Some(hint) = &item.hint {
                for line in hint.lines() {
                    println!("{:19}       {line}", "");
                }
            }
        }
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── Check 4: awk float math ───────────────────────────────────────────────

    #[test]
    fn check_awk_float_math_passes() {
        // awk is available on all platforms where hooks run.
        let out = std::process::Command::new("sh")
            .arg("-c")
            .arg(r#"awk "BEGIN { exit !(0.7 >= 0.6) }" && echo ok"#)
            .output();

        match out {
            Ok(o) => {
                let stdout = String::from_utf8_lossy(&o.stdout);
                assert_eq!(
                    stdout.trim(),
                    "ok",
                    "awk should exit 0 for 0.7 >= 0.6; got: {stdout:?}"
                );
            }
            Err(e) => {
                eprintln!("awk not available on this machine, skipping test: {e}");
            }
        }
    }

    #[test]
    fn check_awk_fail_produces_non_ok_output() {
        // Simulate awk failing — exit code 1 means false.
        let result = std::process::Command::new("sh")
            .arg("-c")
            .arg(r#"awk "BEGIN { exit !(0.5 >= 0.6) }" && echo ok || echo fail"#)
            .output();

        if let Ok(out) = result {
            let stdout = String::from_utf8_lossy(&out.stdout);
            assert_eq!(
                stdout.trim(),
                "fail",
                "expected fail output for 0.5 >= 0.6; got: {stdout:?}"
            );
        }
    }

    // ── Check 5: hook executable detection ───────────────────────────────────

    #[test]
    fn check_hook_executable_detection_catches_missing_bit() {
        use std::os::unix::fs::PermissionsExt;

        let dir = TempDir::new().unwrap();
        let hooks_dir = dir.path().join(".claude").join("hooks");
        std::fs::create_dir_all(&hooks_dir).unwrap();

        // Write all hook scripts and make them all executable first.
        for (name, content) in HOOK_SCRIPTS {
            let path = hooks_dir.join(name);
            std::fs::write(&path, content).unwrap();
            let mut perms = std::fs::metadata(&path).unwrap().permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&path, perms).unwrap();
        }

        // Strip the executable bit from the first hook.
        if let Some((first_name, _)) = HOOK_SCRIPTS.first() {
            let first_path = hooks_dir.join(first_name);
            let mut perms = std::fs::metadata(&first_path).unwrap().permissions();
            perms.set_mode(0o644);
            std::fs::set_permissions(&first_path, perms).unwrap();
        }

        let item = check_claude_hooks(dir.path());
        assert!(
            item.is_fail(),
            "expected FAIL when first hook is not executable: {:?}",
            item.status
        );
    }

    #[test]
    fn check_hook_passes_when_all_installed_and_executable() {
        use std::os::unix::fs::PermissionsExt;

        let dir = TempDir::new().unwrap();
        let hooks_dir = dir.path().join(".claude").join("hooks");
        std::fs::create_dir_all(&hooks_dir).unwrap();

        for (name, content) in HOOK_SCRIPTS {
            let path = hooks_dir.join(name);
            std::fs::write(&path, content).unwrap();
            let mut perms = std::fs::metadata(&path).unwrap().permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&path, perms).unwrap();
        }

        let item = check_claude_hooks(dir.path());
        assert!(
            !item.is_fail(),
            "expected PASS when all hooks are present and executable: {:?}",
            item.status
        );
    }

    // ── Check 6: settings.json parsing ───────────────────────────────────────

    #[test]
    fn check_settings_json_valid_passes() {
        let dir = TempDir::new().unwrap();
        let claude_dir = dir.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();

        // Build a settings.json that contains all hook script paths and mati mcp.
        let hook_entries: Vec<String> = HOOK_SCRIPTS
            .iter()
            .map(|(name, _)| format!("\".claude/hooks/{name}\""))
            .collect();
        let hooks_array = hook_entries.join(", ");

        let json = format!(
            r#"{{
  "hooks": {{ "PreToolUse": [{}] }},
  "mcpServers": {{ "mati": {{ "command": "mati", "args": ["serve"] }} }}
}}"#,
            hooks_array
        );

        std::fs::write(claude_dir.join("settings.json"), &json).unwrap();

        let item = check_claude_config(dir.path());
        assert!(
            !item.is_fail(),
            "expected PASS for valid settings.json: {:?}",
            item.status
        );
    }

    #[test]
    fn check_settings_json_missing_hook_fails() {
        let dir = TempDir::new().unwrap();
        let claude_dir = dir.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();

        // Only include the first hook entry — the rest are absent.
        let first_hook = HOOK_SCRIPTS
            .first()
            .map(|(n, _)| *n)
            .unwrap_or("pre-read.sh");

        let json = format!(
            r#"{{
  "hooks": {{ "PreToolUse": [".claude/hooks/{first_hook}"] }},
  "mcpServers": {{ "mati": {{ "command": "mati", "args": ["serve"] }} }}
}}"#
        );

        std::fs::write(claude_dir.join("settings.json"), &json).unwrap();

        let item = check_claude_config(dir.path());
        // Should fail because not all hooks are referenced.
        if HOOK_SCRIPTS.len() > 1 {
            assert!(
                item.is_fail(),
                "expected FAIL when hooks are missing from settings.json: {:?}",
                item.status
            );
        }
    }

    #[test]
    fn check_settings_json_missing_mcp_fails() {
        let dir = TempDir::new().unwrap();
        let claude_dir = dir.path().join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();

        // Include all hook paths but no mcpServers entry.
        let hook_entries: Vec<String> = HOOK_SCRIPTS
            .iter()
            .map(|(name, _)| format!("\".claude/hooks/{name}\""))
            .collect();
        let hooks_array = hook_entries.join(", ");

        let json = format!(r#"{{ "hooks": {{ "PreToolUse": [{}] }} }}"#, hooks_array);

        std::fs::write(claude_dir.join("settings.json"), &json).unwrap();

        let item = check_claude_config(dir.path());
        assert!(
            item.is_fail(),
            "expected FAIL when mcpServers.mati is absent: {:?}",
            item.status
        );
    }

    // ── Agent-host guard ─────────────────────────────────────────────────────

    #[test]
    fn check_agent_host_fails_when_neither_wired() {
        let dir = TempDir::new().unwrap();
        let item = check_agent_host(dir.path());
        assert!(
            item.is_fail(),
            "neither .claude/ nor .codex/ should FAIL: {:?}",
            item.status
        );
    }

    #[test]
    fn check_agent_host_passes_with_one_host() {
        let dir = TempDir::new().unwrap();
        std::fs::create_dir_all(dir.path().join(".codex")).unwrap();
        let item = check_agent_host(dir.path());
        assert!(
            !item.is_fail(),
            "one wired host (.codex/) should pass: {:?}",
            item.status
        );
    }

    // ── Host gating (Claude-only / Codex-only must not cross-fail) ───────────

    #[test]
    fn check_claude_hooks_not_configured_passes() {
        // A Codex-only project has no .claude/ — must read as "not configured",
        // not a failure.
        let dir = TempDir::new().unwrap();
        let item = check_claude_hooks(dir.path());
        assert!(
            !item.is_fail(),
            "absent .claude/ should be 'not configured', not FAIL: {:?}",
            item.status
        );
    }

    #[test]
    fn check_codex_hooks_not_configured_passes() {
        // A Claude-only project has no .codex/.
        let dir = TempDir::new().unwrap();
        let item = check_codex_hooks(dir.path());
        assert!(
            !item.is_fail(),
            "absent .codex/ should be 'not configured', not FAIL: {:?}",
            item.status
        );
    }

    // ── Codex hook scripts ───────────────────────────────────────────────────

    #[test]
    fn check_codex_hooks_missing_scripts_fails() {
        // .codex/ exists but the hook scripts aren't installed → FAIL.
        let dir = TempDir::new().unwrap();
        std::fs::create_dir_all(dir.path().join(".codex").join("hooks")).unwrap();
        let item = check_codex_hooks(dir.path());
        assert!(
            item.is_fail(),
            "missing codex hook scripts should FAIL: {:?}",
            item.status
        );
    }

    #[test]
    fn check_codex_hooks_complete_passes() {
        use std::os::unix::fs::PermissionsExt;
        let dir = TempDir::new().unwrap();
        let hooks_dir = dir.path().join(".codex").join("hooks");
        std::fs::create_dir_all(&hooks_dir).unwrap();
        for (name, content) in CODEX_HOOK_SCRIPTS {
            let path = hooks_dir.join(name);
            std::fs::write(&path, content).unwrap();
            let mut perms = std::fs::metadata(&path).unwrap().permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&path, perms).unwrap();
        }
        let item = check_codex_hooks(dir.path());
        assert!(
            !item.is_fail(),
            "all codex hooks present + executable should pass: {:?}",
            item.status
        );
    }

    // ── Codex config (hooks.json + config.toml) ──────────────────────────────

    fn write_codex_hooks_json(codex_dir: &std::path::Path) {
        let refs: String = CODEX_HOOK_SCRIPTS
            .iter()
            .map(|(n, _)| format!("\"bash .codex/hooks/{n}\""))
            .collect::<Vec<_>>()
            .join(", ");
        std::fs::write(
            codex_dir.join("hooks.json"),
            format!("{{ \"hooks\": [{refs}] }}"),
        )
        .unwrap();
    }

    #[test]
    fn check_codex_config_complete_passes() {
        let dir = TempDir::new().unwrap();
        let codex_dir = dir.path().join(".codex");
        std::fs::create_dir_all(&codex_dir).unwrap();
        write_codex_hooks_json(&codex_dir);
        std::fs::write(
            codex_dir.join("config.toml"),
            "[mcp_servers.mati]\ncommand = \"mati\"\n",
        )
        .unwrap();
        let item = check_codex_config(dir.path());
        assert!(
            !item.is_fail(),
            "complete codex config should pass: {:?}",
            item.status
        );
    }

    #[test]
    fn check_codex_config_missing_mcp_fails() {
        let dir = TempDir::new().unwrap();
        let codex_dir = dir.path().join(".codex");
        std::fs::create_dir_all(&codex_dir).unwrap();
        write_codex_hooks_json(&codex_dir);
        // config.toml present but no mati MCP server registered.
        std::fs::write(codex_dir.join("config.toml"), "[other]\nx = 1\n").unwrap();
        let item = check_codex_config(dir.path());
        assert!(
            item.is_fail(),
            "missing mcp_servers.mati should FAIL: {:?}",
            item.status
        );
    }

    #[test]
    fn check_codex_config_missing_hooks_json_fails() {
        let dir = TempDir::new().unwrap();
        let codex_dir = dir.path().join(".codex");
        std::fs::create_dir_all(&codex_dir).unwrap();
        // config.toml is fine, but hooks.json is absent.
        std::fs::write(
            codex_dir.join("config.toml"),
            "[mcp_servers.mati]\ncommand = \"mati\"\n",
        )
        .unwrap();
        let item = check_codex_config(dir.path());
        assert!(
            item.is_fail(),
            "missing hooks.json should FAIL: {:?}",
            item.status
        );
    }
}