mati 0.1.4

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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
//! Install hooks into `.claude/` (M-06-J).
//!
//! Writes `.claude/settings.json` with hook registration and creates
//! the real hook scripts in `.claude/hooks/`.
//!
//! Only writes if `.claude/` already exists — if the user isn't using Claude
//! Code, hooks are skipped.

use std::path::Path;

use anyhow::{Context, Result};
use serde_json::Value;

/// Hook and MCP server registration for `.claude/settings.json`.
///
/// Contains two top-level keys:
/// - `hooks` — PreToolUse / PostToolUse / PreCompact / PostCompact / SessionEnd / SubagentStart / SubagentStop / InstructionsLoaded / SessionStart / FileChanged / Stop (ARCHITECTURE.md section 10)
/// - `mcpServers` — registers `mati serve` as an MCP stdio server (M-07-I)
///
/// `timeout` is in SECONDS, and Claude Code's own default is 600. The `4` on the
/// blocking hooks is mati's self-imposed budget, not a platform limit: it is the
/// outer backstop for a wedge that `HOOK_DEADLINE_MS` (2500ms) cannot interrupt,
/// since that timer only fires at an await point.
///
/// The 1500ms between them is not slack. `HOOK_DEADLINE_MS` starts counting
/// inside `run()`, so spawn, dynamic linking, and runtime init all land before
/// it — measured at ~115ms warm but ~1050ms for a binary not yet in the page
/// cache (first call after an install or a reboot). At `3` that cold case put
/// the internal deadline at ~3.5s, past the ceiling, so the host killed the
/// process before it could write the fail-open entry the deadline exists for.
///
/// The non-enforcement blocking hooks use their own budgets: pre-compact gets
/// 5000ms for one durable session transaction, while post-compact and
/// subagent-start get 3000ms for best-effort cleanup/context work. Their
/// scaffold backstops are 7s, 5s, and 5s respectively: even cold startup is
/// about 1050ms before the internal timer starts, so 5000 + 1050 < 7000 and
/// 3000 + 1050 < 5000. This leaves the hooks time to log fail-open evidence.
const SETTINGS_JSON: &str = r#"{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Glob|Grep",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/pre-read.sh",
            "timeout": 4
          }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/pre-bash.sh",
            "timeout": 4
          }
        ]
      },
      {
        "matcher": "Edit|Write|NotebookEdit",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/pre-edit.sh",
            "timeout": 4
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Read|Glob|Grep",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/post-read-compliance.sh",
            "async": true
          }
        ]
      },
      {
        "matcher": "Edit|Write|NotebookEdit",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/post-edit.sh",
            "async": true
          }
        ]
      },
      {
        "matcher": "mcp__mati__mem_get",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/post-memget.sh" }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/post-bash.sh", "async": true }
        ]
      },
      {
        "matcher": "Task|Agent",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/post-task.sh", "async": true }
        ]
      }
    ],
    "PreCompact": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/pre-compact.sh",
            "timeout": 7
          }
        ]
      }
    ],
    "PostCompact": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/post-compact.sh",
            "timeout": 5
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/session-end.sh",
            "timeout": 4
          }
        ]
      }
    ],
    "SubagentStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/subagent-start.sh",
            "timeout": 5
          }
        ]
      }
    ],
    "SubagentStop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/subagent-stop.sh",
            "timeout": 4
          }
        ]
      }
    ],
    "InstructionsLoaded": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/instructions-loaded.sh",
            "timeout": 4
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/session-start.sh",
            "timeout": 5
          }
        ]
      }
    ],
    "FileChanged": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/file-changed.sh",
            "timeout": 4
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/stop.sh",
            "async": true
          }
        ]
      }
    ],
    "ConfigChange": [
      {
        "matcher": "user_settings|project_settings|local_settings|policy_settings|skills",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/config-change.sh",
            "timeout": 4
          }
        ]
      }
    ]
  },
  "mcpServers": {
    "mati": {
      "command": "mati",
      "args": ["serve"]
    }
  }
}
"#;

/// All hook scripts to install, with their content.
///
/// Each script is a Rust string constant defined in `crate::hooks::*`.
/// Replaces the pass-through stubs from M-06-J with real hook logic (M-09).
pub const HOOK_SCRIPTS: &[(&str, &str)] = &[
    ("config-change.sh", crate::hooks::config_change::SCRIPT),
    ("pre-read.sh", crate::hooks::pre_read::SCRIPT),
    ("pre-edit.sh", crate::hooks::pre_edit::SCRIPT),
    ("pre-bash.sh", crate::hooks::pre_bash::SCRIPT),
    (
        "post-read-compliance.sh",
        crate::hooks::post_compliance::SCRIPT,
    ),
    ("post-edit.sh", crate::hooks::post_edit::SCRIPT),
    ("pre-compact.sh", crate::hooks::pre_compact::SCRIPT),
    ("post-compact.sh", crate::hooks::post_compact::SCRIPT),
    ("session-end.sh", crate::hooks::session_end::SCRIPT),
    ("subagent-start.sh", crate::hooks::subagent_start::SCRIPT),
    ("subagent-stop.sh", crate::hooks::subagent_stop::SCRIPT),
    (
        "instructions-loaded.sh",
        crate::hooks::instructions_loaded::SCRIPT,
    ),
    ("session-start.sh", crate::hooks::session_start::SCRIPT),
    ("file-changed.sh", crate::hooks::file_changed::SCRIPT),
    ("stop.sh", crate::hooks::claude_stop::SCRIPT),
    ("post-memget.sh", crate::hooks::post_memget::SCRIPT),
    ("post-bash.sh", crate::hooks::post_bash::SCRIPT),
    ("post-task.sh", crate::hooks::post_task::SCRIPT),
];

/// Return the exact project settings template whose hook registrations are
/// checked by the pure ConfigChange invariant logic.
pub fn settings_template() -> Value {
    settings_template_with_mcp(false)
}

fn settings_template_with_mcp(mcp_tool: bool) -> Value {
    let mut settings: Value =
        serde_json::from_str(SETTINGS_JSON).expect("mati scaffold settings template is valid JSON");
    if mcp_tool {
        settings["hooks"]["PreToolUse"]
            .as_array_mut()
            .expect("PreToolUse scaffold hook list is an array")
            .push(serde_json::json!({
                "matcher": "Read|Glob|Grep",
                "hooks": [{
                    "type": "mcp_tool",
                    "server": "mati",
                    "tool": "mem_get",
                    "input": {
                        "key": "file:${tool_input.file_path}",
                        "decision": true,
                        "agent_id": "${agent_id}"
                    },
                    "timeout": 4
                }]
            }));
    }
    settings
}

/// Outcome of the hook installation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstallResult {
    /// Hooks and settings.json written successfully.
    Installed {
        /// Number of hook scripts written.
        scripts: usize,
        /// Missing runtime dependencies required by the installed hooks.
        missing_deps: Vec<&'static str>,
    },
    /// `.claude/` directory doesn't exist — user isn't using Claude Code.
    NoClaude,
}

/// Install hook registration and hook scripts into `.claude/`.
///
/// - Merges mati's `hooks` key into existing `.claude/settings.json`,
///   preserving any user-defined settings (permissions, env vars, etc.).
/// - Writes `.mcp.json` to the project root for MCP server registration.
///   Claude Code reads `mcpServers` from `.mcp.json` at the project root;
///   the `mcpServers` key in `.claude/settings.json` is kept as a fallback.
/// - Creates `.claude/hooks/` and writes the real hook scripts.
/// - Existing scripts are overwritten (mati owns these files).
/// - Only proceeds if `.claude/` already exists.
pub fn install_hooks(project_root: &Path) -> Result<InstallResult> {
    install_hooks_with_options(project_root, false)
}

/// Install hooks with the optional mcp_tool transport prototype. The shell
/// hook remains installed even when the prototype is enabled: MCP startup and
/// daemon readiness are not prerequisites the enforcement path may depend on.
pub fn install_hooks_with_options(
    project_root: &Path,
    mcp_tool_prototype: bool,
) -> Result<InstallResult> {
    let claude_dir = project_root.join(".claude");
    if !claude_dir.is_dir() {
        return Ok(InstallResult::NoClaude);
    }

    // Merge hooks into settings.json, preserving existing user settings.
    let settings_path = claude_dir.join("settings.json");
    merge_hooks_into_settings(&settings_path, mcp_tool_prototype)
        .with_context(|| format!("failed to update {}", settings_path.display()))?;

    // Write .mcp.json to project root — Claude Code's primary MCP config location.
    let mcp_json_path = project_root.join(".mcp.json");
    write_mcp_json(&mcp_json_path, project_root)
        .with_context(|| format!("failed to write {}", mcp_json_path.display()))?;

    // Create hooks directory and write scripts.
    let hooks_dir = claude_dir.join("hooks");
    std::fs::create_dir_all(&hooks_dir)
        .with_context(|| format!("failed to create {}", hooks_dir.display()))?;

    for (name, content) in HOOK_SCRIPTS {
        let path = hooks_dir.join(name);
        write_if_changed(&path, content)
            .with_context(|| format!("failed to write {}", path.display()))?;
        make_executable(&path)?;
    }

    // Write mati binary wrapper so hooks resolve the same binary as MCP.
    super::write_mati_wrapper(&hooks_dir)?;

    let missing_deps = missing_hook_dependencies();

    Ok(InstallResult::Installed {
        scripts: HOOK_SCRIPTS.len(),
        missing_deps,
    })
}

/// Build the mati MCP server registration (`{command, args[, env]}`).
///
/// When MATI_HOME is set in the environment at init time, capture it into the
/// server's `env` so the MCP server opens the same store the hooks do. Claude
/// Code normally inherits the session env (unlike Codex, which spawns MCP
/// servers with a clean environment), so for Claude this is belt-and-suspenders
/// — but it makes a non-default MATI_HOME robust regardless of how the client
/// launches the server, instead of silently reading ~/.mati while the hooks use
/// MATI_HOME. A default install (no MATI_HOME) writes no env and stays on
/// ~/.mati.
fn mati_server_json() -> Value {
    let mut server = serde_json::json!({
        "command": "mati",
        "args": ["serve"],
    });
    if let Some(mati_home) = std::env::var_os("MATI_HOME") {
        server["env"] = serde_json::json!({ "MATI_HOME": mati_home.to_string_lossy() });
    }
    server
}

/// Merge mati's hook and MCP server registration into an existing settings.json.
///
/// If the file doesn't exist, writes the full settings. If it exists,
/// parses it, replaces only the `hooks` and `mcpServers` keys, and writes
/// back — preserving all other user settings.
/// Merge mati's entries back into a settings file that lost them.
///
/// The `ConfigChange` guard calls this after detecting tamper. Claude Code
/// writes the settings file before asking the hook, so blocking alone leaves the
/// stripped file on disk and the next session starts with no enforcement.
/// Repairing closes that: the merge adds only mati's own entries and leaves
/// every other hook and setting untouched.
///
/// Idempotent by construction — `write_if_changed` means a repair that already
/// satisfies the invariant writes nothing, so the repair cannot drive an endless
/// write / `ConfigChange` / repair cycle.
pub fn restore_mati_entries(path: &Path) -> Result<()> {
    merge_hooks_into_settings(path, false)
}

fn merge_hooks_into_settings(path: &Path, mcp_tool_prototype: bool) -> Result<()> {
    let mut mati_settings = settings_template_with_mcp(mcp_tool_prototype);
    // Bare command name (portable across machines) plus a captured MATI_HOME
    // env when set — see `mati_server_json`.
    mati_settings["mcpServers"]["mati"] = mati_server_json();

    let merged = if path.exists() {
        let existing_str = std::fs::read_to_string(path)?;
        let mut existing: Value = serde_json::from_str(&existing_str)
            .unwrap_or_else(|_| Value::Object(serde_json::Map::new()));

        if let Value::Object(ref mut map) = existing {
            merge_hooks(map, &mati_settings["hooks"]);
            // Merge mcpServers: add "mati" entry without clobbering other servers.
            let mati_server = mati_settings["mcpServers"]["mati"].clone();
            if let Some(Value::Object(ref mut servers)) = map.get_mut("mcpServers") {
                servers.insert("mati".to_string(), mati_server);
            } else {
                map.insert(
                    "mcpServers".to_string(),
                    mati_settings["mcpServers"].clone(),
                );
            }
        }
        existing
    } else {
        mati_settings
    };

    let output = serde_json::to_string_pretty(&merged)?;
    write_if_changed(path, &output)?;
    Ok(())
}

fn merge_hooks(root: &mut serde_json::Map<String, Value>, mati_hooks: &Value) {
    let Some(mati_events) = mati_hooks.as_object() else {
        root.insert("hooks".to_string(), mati_hooks.clone());
        return;
    };

    let hooks_value = root
        .entry("hooks".to_string())
        .or_insert_with(|| Value::Object(serde_json::Map::new()));

    let Value::Object(existing_events) = hooks_value else {
        *hooks_value = mati_hooks.clone();
        return;
    };

    for (event_name, mati_entries_value) in mati_events {
        let Some(mati_entries) = mati_entries_value.as_array() else {
            existing_events.insert(event_name.clone(), mati_entries_value.clone());
            continue;
        };

        let owned_commands = mati_hook_commands(mati_entries);
        let existing_entries = existing_events
            .entry(event_name.clone())
            .or_insert_with(|| Value::Array(Vec::new()));

        let Value::Array(existing_entries) = existing_entries else {
            *existing_entries = Value::Array(mati_entries.clone());
            continue;
        };

        existing_entries.retain(|entry| {
            !entry_contains_owned_command(entry, &owned_commands) && !entry_is_owned_mcp_tool(entry)
        });
        existing_entries.extend(mati_entries.clone());
    }
}

fn entry_is_owned_mcp_tool(entry: &Value) -> bool {
    entry
        .get("hooks")
        .and_then(Value::as_array)
        .is_some_and(|hooks| {
            hooks.iter().any(|hook| {
                hook.get("type").and_then(Value::as_str) == Some("mcp_tool")
                    && hook.get("server").and_then(Value::as_str) == Some("mati")
                    && hook.get("tool").and_then(Value::as_str) == Some("mem_get")
            })
        })
}

fn mati_hook_commands(entries: &[Value]) -> Vec<String> {
    entries.iter().flat_map(entry_hook_commands).collect()
}

fn entry_hook_commands(entry: &Value) -> Vec<String> {
    entry
        .get("hooks")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|hook| hook.get("command").and_then(Value::as_str))
        .map(ToOwned::to_owned)
        .collect()
}

fn entry_contains_owned_command(entry: &Value, owned_commands: &[String]) -> bool {
    entry_hook_commands(entry)
        .iter()
        .any(|command| owned_commands.iter().any(|owned| owned == command))
}

/// Write `.mcp.json` to the project root with the mati MCP server registration.
///
/// Claude Code reads MCP server configuration from `.mcp.json` at the project
/// root — this is the primary mechanism; `mcpServers` in `.claude/settings.json`
/// is kept as a fallback for older Claude Code versions.
///
/// Uses the bare `mati` command (PATH-resolved) so the config is portable
/// across machines. Claude Code sets cwd to the project root when spawning
/// MCP servers, so `mati serve` detects the project automatically.
fn write_mcp_json(path: &Path, _project_root: &Path) -> Result<()> {
    let mati_server = mati_server_json();

    let mut mcp_config = if path.exists() {
        let existing_str = std::fs::read_to_string(path)?;
        serde_json::from_str(&existing_str)
            .unwrap_or_else(|_| Value::Object(serde_json::Map::new()))
    } else {
        Value::Object(serde_json::Map::new())
    };

    if let Value::Object(ref mut map) = mcp_config {
        if let Some(Value::Object(ref mut servers)) = map.get_mut("mcpServers") {
            servers.insert("mati".to_string(), mati_server);
        } else {
            map.insert(
                "mcpServers".to_string(),
                serde_json::json!({ "mati": mati_server }),
            );
        }
    } else {
        mcp_config = serde_json::json!({
            "mcpServers": {
                "mati": mati_server
            }
        });
    }

    let output = serde_json::to_string_pretty(&mcp_config)?;
    write_if_changed(path, &output)?;
    Ok(())
}

fn command_available(cmd: &str) -> bool {
    std::process::Command::new(cmd)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

fn missing_hook_dependencies() -> Vec<&'static str> {
    missing_hook_dependencies_with(command_available)
}

fn missing_hook_dependencies_with<F>(mut has_cmd: F) -> Vec<&'static str>
where
    F: FnMut(&str) -> bool,
{
    let mut missing = Vec::new();
    if !has_cmd("jq") {
        missing.push("jq");
    }
    if !has_cmd("awk") {
        missing.push("awk");
    }
    missing
}

use super::{make_executable, write_if_changed};

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

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

    #[test]
    fn skips_when_no_claude_dir() {
        let dir = TempDir::new().unwrap();
        let result = install_hooks(dir.path()).unwrap();
        assert_eq!(result, InstallResult::NoClaude);
    }

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

        let result = install_hooks(dir.path()).unwrap();
        match result {
            InstallResult::Installed { scripts, .. } => assert_eq!(scripts, 18),
            other => panic!("expected Installed, got {other:?}"),
        }

        // settings.json exists and is valid JSON.
        let settings = std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&settings).unwrap();
        assert!(parsed["hooks"]["PreToolUse"].is_array());
        assert!(parsed["hooks"]["PostToolUse"].is_array());
        assert!(parsed["hooks"]["PreCompact"].is_array());
        assert!(parsed["hooks"]["PostCompact"].is_array());
        assert!(parsed["hooks"]["SessionEnd"].is_array());
        assert!(parsed["hooks"]["SubagentStart"].is_array());
        assert!(parsed["hooks"]["SubagentStop"].is_array());
        assert!(parsed["hooks"]["InstructionsLoaded"].is_array());
        assert!(parsed["hooks"]["SessionStart"].is_array());
        assert!(parsed["hooks"]["FileChanged"].is_array());
        assert!(parsed["hooks"]["Stop"].is_array());
        assert!(parsed["hooks"]["ConfigChange"].is_array());
        // MCP server registered with portable bare command.
        let cmd = parsed["mcpServers"]["mati"]["command"].as_str().unwrap();
        assert_eq!(cmd, "mati", "command must be bare 'mati' for portability");
        assert_eq!(parsed["mcpServers"]["mati"]["args"][0], "serve");
    }

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

        // Pre-existing settings with user config.
        let existing = r#"{"permissions": {"allow": ["npm test"]}, "env": {"DEBUG": "true"}}"#;
        std::fs::write(claude_dir.join("settings.json"), existing).unwrap();

        install_hooks(dir.path()).unwrap();

        let settings = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&settings).unwrap();

        // User settings preserved.
        assert_eq!(parsed["permissions"]["allow"][0], "npm test");
        assert_eq!(parsed["env"]["DEBUG"], "true");
        // Hooks added.
        assert!(parsed["hooks"]["PreToolUse"].is_array());
        // MCP server added with portable bare command.
        assert_eq!(parsed["mcpServers"]["mati"]["command"], "mati");
    }

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

        // Pre-existing settings with another MCP server.
        let existing = r#"{"mcpServers": {"other-tool": {"command": "other", "args": ["run"]}}}"#;
        std::fs::write(claude_dir.join("settings.json"), existing).unwrap();

        install_hooks(dir.path()).unwrap();

        let settings = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&settings).unwrap();

        // Existing server preserved.
        assert_eq!(parsed["mcpServers"]["other-tool"]["command"], "other");
        // mati server added alongside with portable bare command.
        assert_eq!(parsed["mcpServers"]["mati"]["command"], "mati");
        assert_eq!(parsed["mcpServers"]["mati"]["args"][0], "serve");
    }

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

        let existing = serde_json::json!({
            "hooks": {
                "PreToolUse": [
                    {
                        "matcher": "Write",
                        "hooks": [
                            {
                                "type": "command",
                                "command": ".claude/hooks/custom-pre-write.sh"
                            }
                        ]
                    }
                ]
            }
        });
        std::fs::write(
            claude_dir.join("settings.json"),
            serde_json::to_string_pretty(&existing).unwrap(),
        )
        .unwrap();

        install_hooks(dir.path()).unwrap();

        let settings = std::fs::read_to_string(claude_dir.join("settings.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&settings).unwrap();
        let pre_tool_use = parsed["hooks"]["PreToolUse"].as_array().unwrap();

        assert!(
            pre_tool_use.iter().any(|entry| {
                entry["hooks"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .any(|hook| hook["command"] == ".claude/hooks/custom-pre-write.sh")
            }),
            "custom existing hook should be preserved"
        );
        assert!(
            pre_tool_use.iter().any(|entry| {
                entry["hooks"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .any(|hook| hook["command"] == ".claude/hooks/pre-read.sh")
            }),
            "mati pre-read hook should be present"
        );
    }

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

        install_hooks(dir.path()).unwrap();

        let hooks_dir = dir.path().join(".claude/hooks");
        for (name, _) in HOOK_SCRIPTS {
            let path = hooks_dir.join(name);
            assert!(path.exists(), "missing hook script: {name}");

            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = std::fs::metadata(&path).unwrap().permissions().mode();
                assert_eq!(mode & 0o111, 0o111, "{name} should be executable");
            }
        }
    }

    #[test]
    fn pre_hooks_delegate_to_hook_decide() {
        // Enforcement logic is now in Rust (hooks::decide + cli::hook_decide).
        // Shell wrappers just exec the correct hook-decide variant.
        assert!(crate::hooks::pre_read::SCRIPT.contains("exec mati hook-decide claude-pre-read"));
        assert!(crate::hooks::pre_edit::SCRIPT.contains("exec mati hook-decide claude-pre-edit"));
        assert!(crate::hooks::pre_bash::SCRIPT.contains("exec mati hook-decide claude-pre-bash"));
        assert!(crate::hooks::post_bash::SCRIPT.contains("exec mati hook-decide claude-post-bash"));
    }

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

        install_hooks(dir.path()).unwrap();

        let mcp_json_path = dir.path().join(".mcp.json");
        assert!(
            mcp_json_path.exists(),
            ".mcp.json should be written to project root"
        );

        let content = std::fs::read_to_string(&mcp_json_path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["mcpServers"]["mati"]["command"], "mati");
        assert_eq!(parsed["mcpServers"]["mati"]["args"][0], "serve");
        // No --path arg — mati serve detects project from cwd.
        assert!(
            parsed["mcpServers"]["mati"]["args"]
                .as_array()
                .unwrap()
                .len()
                == 1,
            "args must only contain 'serve', no --path"
        );
    }

    #[test]
    fn write_mcp_json_preserves_existing_servers() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join(".mcp.json");
        let existing = serde_json::json!({
            "mcpServers": {
                "other-tool": {
                    "command": "other",
                    "args": ["run"]
                }
            }
        });
        std::fs::write(&path, serde_json::to_string_pretty(&existing).unwrap()).unwrap();

        write_mcp_json(&path, dir.path()).unwrap();

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["mcpServers"]["other-tool"]["command"], "other");
        assert_eq!(parsed["mcpServers"]["mati"]["command"], "mati");
        assert_eq!(parsed["mcpServers"]["mati"]["args"][0], "serve");
    }

    #[test]
    fn detects_all_hook_runtime_dependencies() {
        let missing = missing_hook_dependencies_with(|cmd| cmd == "jq");
        assert_eq!(missing, vec!["awk"]);

        let missing = missing_hook_dependencies_with(|_| false);
        assert_eq!(missing, vec!["jq", "awk"]);
    }

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

        install_hooks(dir.path()).unwrap();
        let first_content =
            std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        let first_mcp = std::fs::read_to_string(dir.path().join(".mcp.json")).unwrap();

        install_hooks(dir.path()).unwrap();
        let second_content =
            std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        let second_mcp = std::fs::read_to_string(dir.path().join(".mcp.json")).unwrap();

        assert_eq!(first_content, second_content);
        assert_eq!(first_mcp, second_mcp);
    }

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

        // Wrapper must exist
        let wrapper_path = dir.path().join(".claude/hooks/mati");
        assert!(
            wrapper_path.exists(),
            ".claude/hooks/mati wrapper must exist"
        );

        let wrapper = std::fs::read_to_string(&wrapper_path).unwrap();
        assert!(wrapper.contains("exec"), "wrapper must use exec");

        // Wrapper uses absolute path (hooks run in restricted shell without ~/.cargo/bin on PATH).
        let exec_line = wrapper.lines().find(|l| l.contains("exec")).unwrap();
        let exec_target = exec_line
            .strip_prefix("exec \"")
            .and_then(|s| s.strip_suffix("\" \"$@\""))
            .expect("exec line must follow format: exec \"<path>\" \"$@\"");
        assert!(
            exec_target.starts_with('/'),
            "wrapper must use absolute path, got: {exec_target}"
        );

        // MCP config uses portable bare command (resolved via PATH by Claude Code).
        let settings = std::fs::read_to_string(dir.path().join(".claude/settings.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&settings).unwrap();
        assert_eq!(
            parsed["mcpServers"]["mati"]["command"], "mati",
            "MCP config must use bare 'mati' for portability"
        );
    }

    #[test]
    fn settings_template_default_has_only_command_hooks() {
        let settings = settings_template_with_mcp(false);
        let pre = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(
            pre.len(),
            3,
            "shell hooks only — pre-read, pre-bash, pre-edit"
        );
        for entry in pre {
            for hook in entry["hooks"].as_array().unwrap() {
                assert_eq!(
                    hook["type"], "command",
                    "no mcp_tool entry unless mcp_tool is requested"
                );
            }
        }
    }

    #[test]
    fn settings_template_with_mcp_tool_adds_registration_beside_shell_hook() {
        let settings = settings_template_with_mcp(true);
        let pre = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(
            pre.len(),
            4,
            "the mcp_tool entry is additive, not a replacement"
        );
        // Shell pre-read is still first and unchanged.
        assert_eq!(pre[0]["matcher"], "Read|Glob|Grep");
        assert_eq!(pre[0]["hooks"][0]["type"], "command");
        assert_eq!(pre[0]["hooks"][0]["command"], ".claude/hooks/pre-read.sh");

        // Grounded against `mati hooks --claude --claude-mcp-tool`'s actual
        // written settings.json.
        let mcp_entry = &pre[3];
        assert_eq!(mcp_entry["matcher"], "Read|Glob|Grep");
        let hook = &mcp_entry["hooks"][0];
        assert_eq!(hook["type"], "mcp_tool");
        assert_eq!(hook["server"], "mati");
        assert_eq!(hook["tool"], "mem_get");
        assert_eq!(hook["input"]["key"], "file:${tool_input.file_path}");
        assert_eq!(hook["input"]["decision"], true);
        // F11 second half: agent_id must be interpolated too so the mcp_tool
        // path can compute the same actor scope as the shell hook.
        assert_eq!(hook["input"]["agent_id"], "${agent_id}");
        assert_eq!(hook["timeout"], 4);
    }

    #[test]
    fn entry_is_owned_mcp_tool_recognizes_own_entry_not_a_foreign_one() {
        let owned = serde_json::json!({
            "matcher": "Read|Glob|Grep",
            "hooks": [{
                "type": "mcp_tool",
                "server": "mati",
                "tool": "mem_get",
                "input": { "key": "file:${tool_input.file_path}", "decision": true }
            }]
        });
        assert!(entry_is_owned_mcp_tool(&owned));

        // Negative twin: a user's own mcp_tool entry for an unrelated
        // server/tool must not be claimed as mati's.
        let foreign = serde_json::json!({
            "matcher": "Read",
            "hooks": [{
                "type": "mcp_tool",
                "server": "other-server",
                "tool": "some_tool"
            }]
        });
        assert!(!entry_is_owned_mcp_tool(&foreign));

        // A plain command hook is not an mcp_tool entry at all.
        let command = serde_json::json!({
            "matcher": "Read",
            "hooks": [{ "type": "command", "command": ".claude/hooks/pre-read.sh" }]
        });
        assert!(!entry_is_owned_mcp_tool(&command));
    }

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

        for (name, _) in HOOK_SCRIPTS {
            let path = dir.path().join(".claude/hooks").join(name);
            let content = std::fs::read_to_string(&path)
                .unwrap_or_else(|_| panic!("hook script {name} must exist"));
            assert!(
                content.contains("HOOKS_DIR=") && content.contains("export PATH="),
                "hook script {name} must prepend HOOKS_DIR to PATH"
            );
        }
    }
}