mati 0.1.0

Engineering knowledge that survives turnover
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
//! Shared enforcement core for `mati hook-decide`.
//!
//! Pure functions — no I/O, no daemon calls. Testable without a running daemon.
//! Platform adapters in `cli::hook_decide` map these semantic outcomes to
//! protocol-specific output (Claude JSON, Codex exit codes).

use std::collections::HashMap;

// ── Types ───────────────────────────────────────────────────────────────────

/// Which class of file-reading command was detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandClass {
    /// cat, less, head, tail, bat — file path is first non-flag arg.
    CatLike,
    /// grep, rg, sed, awk — file path is last non-flag arg.
    GrepLike,
}

/// Semantic enforcement decision. Adapters map these to platform output.
///
/// `FailOpen` is intentionally absent — it's a daemon-readiness outcome
/// handled by the adapter before calling `evaluate()`.
#[derive(Debug, Clone, PartialEq)]
pub enum Decision {
    /// No enforcement needed — allow unconditionally.
    Allow,
    /// Confirmed gotcha, agent has NOT consulted — block the read.
    Deny { file_key: String, reason: String },
    /// Confirmed gotcha, agent already consulted — allow with awareness.
    AlreadyConsulted { context: String },
    /// Medium confidence (0.3–0.6), quality >= 0.4 — advisory context.
    Advisory { context: String },
    /// Record too stale to trust — adapter decides whether to inject warning.
    Liability { staleness: f32, context: String },
    /// Record fully excluded from enforcement.
    Tombstone,
    /// No file record exists in the store.
    NoRecord,
    /// Command is not a file-reading operation.
    NotFileRead,
}

/// Side-effect events the adapter should fire after the decision.
/// Each variant maps 1:1 to an existing daemon socket command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookEvent {
    /// Record accessed — daemon `log_hit`.
    Hit { key: String },
    /// No record found — daemon `log_miss`.
    Miss { key: String },
    /// Pre-read/pre-bash denied an unconsulted read — daemon `log_compliance_miss`.
    BlockedUnconsultedRead { key: String },
    /// Codex shell command blocked — daemon `log_codex_shell_miss`.
    CodexShellBlocked { key: String },
    /// Post-bash confirmed a consulted read — daemon `log_compliance_hit`.
    ComplianceHit { key: String },
}

/// Input to the enforcement decision engine.
pub struct EnforcementInput {
    /// Repo-relative file path (e.g. `"src/main.rs"`).
    pub rel_path: String,
    /// File record JSON from `hook_evaluate`, or `None` if no record.
    pub file_record: Option<serde_json::Value>,
    /// Gotcha records keyed by gotcha key, from `hook_evaluate`.
    pub gotcha_records: HashMap<String, serde_json::Value>,
    /// Whether this file was already consulted via `mem_get` this session.
    pub already_consulted: bool,
}

/// Result of `evaluate()`.
pub struct EnforcementResult {
    pub decision: Decision,
    pub events: Vec<HookEvent>,
}

// ── Command Classification ──────────────────────────────────────────────────

const CAT_LIKE: &[&str] = &["cat", "less", "head", "tail", "bat"];
const GREP_LIKE: &[&str] = &["grep", "rg", "sed", "awk"];

/// Returns true if `trimmed` starts with `word` followed by whitespace
/// (or is exactly `word`). Prevents `"catch"` matching `"cat"`.
fn matches_command_word(trimmed: &str, word: &str) -> bool {
    if trimmed.len() < word.len() {
        return false;
    }
    if !trimmed.starts_with(word) {
        return false;
    }
    if trimmed.len() == word.len() {
        return true;
    }
    trimmed.as_bytes()[word.len()].is_ascii_whitespace()
}

/// Classify a bash command string. Returns `None` for non-file-read commands.
pub fn classify_command(cmd: &str) -> Option<CommandClass> {
    let trimmed = cmd.trim_start();
    for &word in CAT_LIKE {
        if matches_command_word(trimmed, word) {
            return Some(CommandClass::CatLike);
        }
    }
    for &word in GREP_LIKE {
        if matches_command_word(trimmed, word) {
            return Some(CommandClass::GrepLike);
        }
    }
    None
}

// ── File Path Extraction ────────────────────────────────────────────────────

/// Extract the target file path from a classified command.
///
/// Replicates the bash hook heuristic:
/// - CatLike: prefer first double-quoted path, fallback to first non-flag arg.
/// - GrepLike: prefer last double-quoted path, fallback to last non-flag arg
///   (strip surrounding single quotes).
///
/// Stops at pipe (`|`), semicolon (`;`), `&&`, `||`.
pub fn extract_file_path(cmd: &str, class: CommandClass) -> Option<String> {
    let trimmed = cmd.trim_start();

    // Isolate the command portion before shell operators.
    let cmd_part = split_at_shell_operator(trimmed);

    match class {
        CommandClass::CatLike => {
            if let Some(q) = extract_first_double_quoted(cmd_part) {
                return Some(q);
            }
            positional_arg(cmd_part, true)
        }
        CommandClass::GrepLike => {
            if let Some(q) = extract_last_double_quoted(cmd_part) {
                return Some(q);
            }
            positional_arg(cmd_part, false).map(|s| {
                // Strip surrounding single quotes (grep patterns).
                s.trim_start_matches('\'')
                    .trim_end_matches('\'')
                    .to_string()
            })
        }
    }
}

/// Split at the first shell operator (`|`, `;`, `&&`, `||`), returning the
/// portion before the operator.
fn split_at_shell_operator(s: &str) -> &str {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'|' => {
                // Could be `|` (pipe) or `||` — both mean stop.
                return &s[..i];
            }
            b';' => return &s[..i],
            b'&' if i + 1 < bytes.len() && bytes[i + 1] == b'&' => {
                return &s[..i];
            }
            b'"' => {
                // Skip quoted strings so we don't split on operators inside quotes.
                i += 1;
                while i < bytes.len() && bytes[i] != b'"' {
                    i += 1;
                }
            }
            b'\'' => {
                i += 1;
                while i < bytes.len() && bytes[i] != b'\'' {
                    i += 1;
                }
            }
            _ => {}
        }
        i += 1;
    }
    s
}

/// Extract the content of the first double-quoted string.
fn extract_first_double_quoted(s: &str) -> Option<String> {
    let start = s.find('"')? + 1;
    let end = s[start..].find('"')? + start;
    let inner = &s[start..end];
    if inner.is_empty() {
        None
    } else {
        Some(inner.to_string())
    }
}

/// Extract the content of the last double-quoted string.
fn extract_last_double_quoted(s: &str) -> Option<String> {
    let mut last: Option<String> = None;
    let mut pos = 0;
    while pos < s.len() {
        if let Some(offset) = s[pos..].find('"') {
            let abs_start = pos + offset + 1;
            if let Some(end_offset) = s[abs_start..].find('"') {
                let inner = &s[abs_start..abs_start + end_offset];
                if !inner.is_empty() {
                    last = Some(inner.to_string());
                }
                pos = abs_start + end_offset + 1;
            } else {
                break;
            }
        } else {
            break;
        }
    }
    last
}

/// Extract first or last positional (non-flag) argument after the command word.
fn positional_arg(cmd_part: &str, first: bool) -> Option<String> {
    let words: Vec<&str> = cmd_part.split_whitespace().collect();
    if words.len() < 2 {
        return None;
    }
    let args: Vec<&str> = words[1..]
        .iter()
        .filter(|w| !w.starts_with('-'))
        .copied()
        .collect();
    if args.is_empty() {
        return None;
    }
    let picked = if first { args[0] } else { args[args.len() - 1] };
    if picked.is_empty() {
        None
    } else {
        Some(picked.to_string())
    }
}

// ── apply_patch envelope parsing ────────────────────────────────────────────

/// Maximum number of files a single `apply_patch` is gated against. A patch
/// touching more than this is rare; the cap bounds per-file daemon round-trips
/// so the hook stays well inside its deadline. Files beyond the cap are NOT
/// gated (fail-open bias for the edit path) and the caller logs the truncation.
pub const MAX_APPLY_PATCH_FILES: usize = 50;

/// Extract the target file paths from a Codex `apply_patch` envelope.
///
/// Codex delivers the patch as a single string in `tool_input.command`:
///
/// ```text
/// *** Begin Patch
/// *** Update File: src/a.rs
/// @@ ...
///  context
/// -old
/// +new
/// *** Add File: src/b.rs
/// +contents
/// *** Delete File: src/c.rs
/// *** Move to: src/a_renamed.rs
/// *** End Patch
/// ```
///
/// Markers are matched only at column 0. Diff body lines are prefixed with a
/// space/`+`/`-`/`@@`, so a content line that happens to contain
/// `*** Update File:` (e.g. `+*** Update File: x`) does NOT collide with a real
/// envelope marker. Returns paths in first-seen order with duplicates removed;
/// the caller normalizes each. Add/Update/Delete and the rename source +
/// destination are all included — `evaluate()` allows any path with no
/// confirmed gotcha, so over-collecting is harmless.
pub fn extract_apply_patch_files(patch: &str) -> Vec<String> {
    const MARKERS: &[&str] = &[
        "*** Update File: ",
        "*** Add File: ",
        "*** Delete File: ",
        "*** Move to: ",
    ];
    let mut files: Vec<String> = Vec::new();
    for line in patch.lines() {
        for marker in MARKERS {
            if let Some(rest) = line.strip_prefix(marker) {
                let path = rest.trim();
                if !path.is_empty() && !files.iter().any(|f| f == path) {
                    files.push(path.to_string());
                }
                break;
            }
        }
    }
    files
}

// ── Path Normalization ──────────────────────────────────────────────────────

/// Normalize `file_path` to a lexical repo-relative path.
///
/// - Strips `repo_root` prefix (with trailing `/`).
/// - Collapses `.` and `..` components lexically (no filesystem access).
/// - Does NOT resolve symlinks — memory keys are lexical paths.
pub fn normalize_path(file_path: &str, repo_root: Option<&str>) -> String {
    let stripped = match repo_root {
        Some(root) => file_path
            .strip_prefix(root)
            .and_then(|s| s.strip_prefix('/'))
            .unwrap_or(file_path),
        None => file_path,
    };

    let mut components: Vec<&str> = Vec::new();
    for part in stripped.split('/') {
        match part {
            "" | "." => continue,
            ".." => {
                if components.pop().is_none() {
                    // Path escapes above root — out of scope.
                    // Return as-is; it won't match any store key.
                    return stripped.to_string();
                }
            }
            c => components.push(c),
        }
    }

    if components.is_empty() {
        ".".to_string()
    } else {
        components.join("/")
    }
}

// ── Core Decision Engine ────────────────────────────────────────────────────

/// Evaluate the enforcement decision for a file access.
///
/// Pure function — all data comes from `input`, no I/O. The decision matrix
/// matches ARCHITECTURE.md §10.1.
pub fn evaluate(input: &EnforcementInput) -> EnforcementResult {
    let file_key = format!("file:{}", input.rel_path);

    // ── No record ───────────────────────────────────────────────────────
    let file_record = match &input.file_record {
        Some(r) if r.is_object() => r,
        _ => {
            return EnforcementResult {
                decision: Decision::NoRecord,
                events: vec![HookEvent::Miss { key: file_key }],
            };
        }
    };

    // ── Extract scores ──────────────────────────────────────────────────
    let confidence = json_f32(file_record, "/confidence/value");
    let quality = json_f32(file_record, "/quality/value");
    let staleness = json_f32(file_record, "/staleness/value");
    let staleness_tier = json_str(file_record, "/staleness/tier");

    // ── Tombstone — fully excluded ──────────────────────────────────────
    if staleness_tier == "tombstone" {
        return EnforcementResult {
            decision: Decision::Tombstone,
            events: vec![],
        };
    }

    // ── Liability — too stale to trust ──────────────────────────────────
    if staleness_tier == "liability" {
        return EnforcementResult {
            decision: Decision::Liability {
                staleness,
                context: format!(
                    "WARNING: STALE record for {} is a liability (staleness {:.2}). \
                     Read the file directly — the cached record is too stale to trust.",
                    input.rel_path, staleness
                ),
            },
            events: vec![HookEvent::Hit { key: file_key }],
        };
    }

    // ── Build context + check gotchas ───────────────────────────────────
    let purpose = json_str(file_record, "/value");
    let mut context_lines: Vec<String> = Vec::new();
    if !purpose.is_empty() {
        context_lines.push(format!("Purpose: {purpose}"));
    }

    let mut deny_signal = false;
    let gotcha_keys = json_string_array(file_record, "/payload/gotcha_keys");

    for gkey in &gotcha_keys {
        let grec = match input.gotcha_records.get(gkey.as_str()) {
            Some(r) if r.is_object() => r,
            _ => continue,
        };

        let confirmed = json_bool(grec, "/payload/confirmed");
        let gconfidence = json_f32(grec, "/confidence/value");
        let gquality = json_f32(grec, "/quality/value");
        let rule = json_str(grec, "/value");

        // Only confirmed, injectable gotchas contribute to the injected
        // context (P4: unconfirmed gotchas never influence injection). Gating
        // the rule push here also bounds the payload — without it, every
        // attached gotcha, including unconfirmed Layer-0 stubs, was dumped into
        // the context (a single hotspot file with 1k+ stubs produced ~47 KB).
        if confirmed && gconfidence >= 0.6 && gquality >= 0.4 {
            deny_signal = true;
            if !rule.is_empty() {
                context_lines.push(format!("\u{26a0} {rule}"));
            }
        }
    }

    // Staleness warning for moderately stale records.
    if staleness >= 0.4 {
        context_lines.push(format!(
            "Warning: record staleness {staleness:.2} — verify critical details."
        ));
    }

    // Blast radius warning for high-impact files.
    {
        let blast_tier = json_str(file_record, "/payload/blast_radius/tier");
        if blast_tier == "high" || blast_tier == "critical" {
            let blast_direct = file_record
                .pointer("/payload/blast_radius/direct")
                .and_then(|v| v.as_u64())
                .unwrap_or(0);
            context_lines.push(format!(
                "\u{26a0} Blast radius: {blast_direct} direct importers ({blast_tier}) — modify carefully"
            ));
        }
    }

    // ── Deny path ───────────────────────────────────────────────────────
    if deny_signal {
        if input.already_consulted {
            let context = if context_lines.is_empty() {
                format!(
                    "Gotcha exists for {} — proceed with awareness",
                    input.rel_path
                )
            } else {
                context_lines.join("\n")
            };
            // AllowAfterReceipt enforcement event: the read is being allowed
            // because a valid consultation receipt exists. ComplianceHit
            // (SessionLog v2) triggers the AllowAfterReceipt record.
            return EnforcementResult {
                decision: Decision::AlreadyConsulted { context },
                events: vec![HookEvent::ComplianceHit { key: file_key }],
            };
        }

        let safe_path = input.rel_path.replace('\\', "\\\\").replace('"', "\\\"");
        let staleness_note = if staleness >= 0.4 {
            format!(" (staleness {staleness:.2} — verify critical details)")
        } else {
            String::new()
        };

        return EnforcementResult {
            decision: Decision::Deny {
                file_key: file_key.clone(),
                reason: format!(
                    "[mati] Confirmed gotcha on {safe_path}\
                     call mem_get(\"file:{safe_path}\") and read the record \
                     before accessing this file.{staleness_note}"
                ),
            },
            events: vec![HookEvent::BlockedUnconsultedRead { key: file_key }],
        };
    }

    // ── Advisory path (medium confidence) ───────────────────────────────
    if confidence >= 0.3 && quality >= 0.4 {
        let context = if context_lines.is_empty() {
            format!(
                "Record exists for {} — confidence {confidence:.2}",
                input.rel_path
            )
        } else {
            context_lines.join("\n")
        };
        return EnforcementResult {
            decision: Decision::Advisory { context },
            events: vec![HookEvent::Hit { key: file_key }],
        };
    }

    // ── Default: allow, no injection ────────────────────────────────────
    EnforcementResult {
        decision: Decision::Allow,
        events: vec![],
    }
}

// ── JSON helpers ────────────────────────────────────────────────────────────

fn json_f32(val: &serde_json::Value, pointer: &str) -> f32 {
    val.pointer(pointer)
        .and_then(|v| v.as_f64())
        .map(|f| f as f32)
        .unwrap_or(0.0)
}

fn json_str(val: &serde_json::Value, pointer: &str) -> String {
    val.pointer(pointer)
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string()
}

fn json_bool(val: &serde_json::Value, pointer: &str) -> bool {
    val.pointer(pointer)
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
}

fn json_string_array(val: &serde_json::Value, pointer: &str) -> Vec<String> {
    val.pointer(pointer)
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default()
}

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

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

    // ── extract_apply_patch_files ────────────────────────────────────────

    #[test]
    fn apply_patch_single_update() {
        let patch =
            "*** Begin Patch\n*** Update File: src/main.rs\n@@\n-old\n+new\n*** End Patch\n";
        assert_eq!(extract_apply_patch_files(patch), vec!["src/main.rs"]);
    }

    #[test]
    fn apply_patch_multi_file_add_update_delete() {
        let patch = "*** Begin Patch\n\
            *** Update File: src/a.rs\n@@\n+x\n\
            *** Add File: src/b.rs\n+y\n\
            *** Delete File: src/c.rs\n\
            *** End Patch\n";
        assert_eq!(
            extract_apply_patch_files(patch),
            vec!["src/a.rs", "src/b.rs", "src/c.rs"]
        );
    }

    #[test]
    fn apply_patch_rename_includes_source_and_destination() {
        let patch =
            "*** Begin Patch\n*** Update File: src/old.rs\n*** Move to: src/new.rs\n@@\n+x\n*** End Patch\n";
        assert_eq!(
            extract_apply_patch_files(patch),
            vec!["src/old.rs", "src/new.rs"]
        );
    }

    #[test]
    fn apply_patch_ignores_marker_inside_diff_body() {
        // A diff line that ADDS text resembling a marker must NOT be parsed as
        // an envelope marker: diff body lines are prefixed (+/-/space), so they
        // never begin at column 0 with "*** ".
        let patch = "*** Begin Patch\n\
            *** Update File: src/real.rs\n@@\n\
            +*** Update File: src/fake.rs\n\
            + *** Add File: src/also_fake.rs\n\
            *** End Patch\n";
        assert_eq!(extract_apply_patch_files(patch), vec!["src/real.rs"]);
    }

    #[test]
    fn apply_patch_dedups_repeated_path() {
        let patch =
            "*** Begin Patch\n*** Update File: src/a.rs\n*** Update File: src/a.rs\n*** End Patch\n";
        assert_eq!(extract_apply_patch_files(patch), vec!["src/a.rs"]);
    }

    #[test]
    fn apply_patch_empty_or_no_markers() {
        assert!(extract_apply_patch_files("").is_empty());
        assert!(extract_apply_patch_files("just some text\nno markers here").is_empty());
        assert!(extract_apply_patch_files("*** Begin Patch\n*** End Patch\n").is_empty());
    }

    #[test]
    fn apply_patch_trims_trailing_whitespace() {
        let patch = "*** Update File: src/spaced.rs   \n";
        assert_eq!(extract_apply_patch_files(patch), vec!["src/spaced.rs"]);
    }

    // ── classify_command ─────────────────────────────────────────────────

    #[test]
    fn classify_cat() {
        assert_eq!(
            classify_command("cat src/main.rs"),
            Some(CommandClass::CatLike)
        );
    }

    #[test]
    fn classify_head_with_flag() {
        assert_eq!(
            classify_command("head -n 10 file.rs"),
            Some(CommandClass::CatLike)
        );
    }

    #[test]
    fn classify_leading_whitespace() {
        assert_eq!(classify_command("  cat file"), Some(CommandClass::CatLike));
    }

    #[test]
    fn classify_less() {
        assert_eq!(
            classify_command("less README.md"),
            Some(CommandClass::CatLike)
        );
    }

    #[test]
    fn classify_tail() {
        assert_eq!(
            classify_command("tail -f log.txt"),
            Some(CommandClass::CatLike)
        );
    }

    #[test]
    fn classify_bat() {
        assert_eq!(
            classify_command("bat src/lib.rs"),
            Some(CommandClass::CatLike)
        );
    }

    #[test]
    fn classify_grep() {
        assert_eq!(
            classify_command("grep -rn pattern src/"),
            Some(CommandClass::GrepLike)
        );
    }

    #[test]
    fn classify_rg() {
        assert_eq!(
            classify_command("rg TODO src/"),
            Some(CommandClass::GrepLike)
        );
    }

    #[test]
    fn classify_sed() {
        assert_eq!(
            classify_command("sed -i 's/a/b/' file.rs"),
            Some(CommandClass::GrepLike)
        );
    }

    #[test]
    fn classify_awk() {
        assert_eq!(
            classify_command("awk '{print $1}' file.rs"),
            Some(CommandClass::GrepLike)
        );
    }

    #[test]
    fn classify_ls_is_none() {
        assert_eq!(classify_command("ls -la"), None);
    }

    #[test]
    fn classify_cd_is_none() {
        assert_eq!(classify_command("cd /tmp"), None);
    }

    #[test]
    fn classify_catch_is_none() {
        assert_eq!(classify_command("catch errors"), None);
    }

    #[test]
    fn classify_catalog_is_none() {
        assert_eq!(classify_command("catalog"), None);
    }

    #[test]
    fn classify_grep_bare_is_none() {
        // "grep" with no args — still classifies (extraction returns None later)
        assert_eq!(classify_command("grep"), Some(CommandClass::GrepLike));
    }

    // ── extract_file_path ───────────────────────────────────────────────

    #[test]
    fn extract_cat_simple() {
        assert_eq!(
            extract_file_path("cat src/main.rs", CommandClass::CatLike),
            Some("src/main.rs".into())
        );
    }

    #[test]
    fn extract_cat_with_flag() {
        assert_eq!(
            extract_file_path("cat -n src/main.rs", CommandClass::CatLike),
            Some("src/main.rs".into())
        );
    }

    #[test]
    fn extract_cat_quoted_path() {
        assert_eq!(
            extract_file_path(r#"cat "path with spaces/file.rs""#, CommandClass::CatLike),
            Some("path with spaces/file.rs".into())
        );
    }

    #[test]
    fn extract_cat_with_pipe() {
        assert_eq!(
            extract_file_path("cat file.rs | grep foo", CommandClass::CatLike),
            Some("file.rs".into())
        );
    }

    #[test]
    fn extract_cat_with_semicolon() {
        assert_eq!(
            extract_file_path("cat file.rs; echo done", CommandClass::CatLike),
            Some("file.rs".into())
        );
    }

    #[test]
    fn extract_cat_with_and() {
        assert_eq!(
            extract_file_path("cat file.rs && echo ok", CommandClass::CatLike),
            Some("file.rs".into())
        );
    }

    #[test]
    fn extract_grep_last_arg() {
        assert_eq!(
            extract_file_path("grep -rn pattern src/main.rs", CommandClass::GrepLike),
            Some("src/main.rs".into())
        );
    }

    #[test]
    fn extract_grep_quoted_file() {
        assert_eq!(
            extract_file_path(r#"grep pattern "src/main.rs""#, CommandClass::GrepLike),
            Some("src/main.rs".into())
        );
    }

    #[test]
    fn extract_grep_strips_single_quotes() {
        assert_eq!(
            extract_file_path("grep 'pattern' file.rs", CommandClass::GrepLike),
            Some("file.rs".into())
        );
    }

    #[test]
    fn extract_no_args() {
        assert_eq!(extract_file_path("cat", CommandClass::CatLike), None);
    }

    #[test]
    fn extract_only_flags() {
        assert_eq!(extract_file_path("cat -n -v", CommandClass::CatLike), None);
    }

    // ── normalize_path ──────────────────────────────────────────────────

    #[test]
    fn normalize_strips_prefix() {
        assert_eq!(
            normalize_path("/home/user/project/src/main.rs", Some("/home/user/project")),
            "src/main.rs"
        );
    }

    #[test]
    fn normalize_dot_slash() {
        assert_eq!(normalize_path("./src/main.rs", None), "src/main.rs");
    }

    #[test]
    fn normalize_dotdot() {
        assert_eq!(normalize_path("src/../src/main.rs", None), "src/main.rs");
    }

    #[test]
    fn normalize_already_relative() {
        assert_eq!(normalize_path("src/main.rs", None), "src/main.rs");
    }

    #[test]
    fn normalize_no_repo_root() {
        assert_eq!(
            normalize_path("/abs/path/file.rs", None),
            "abs/path/file.rs"
        );
    }

    #[test]
    fn normalize_trailing_slash_root() {
        // repo_root should not have trailing slash, but handle it gracefully.
        assert_eq!(
            normalize_path("/project/src/file.rs", Some("/project")),
            "src/file.rs"
        );
    }

    #[test]
    fn normalize_leading_dotdot_returns_unchanged() {
        // Path escaping above root is out-of-scope — return as-is.
        assert_eq!(normalize_path("../other/file.rs", None), "../other/file.rs");
    }

    #[test]
    fn normalize_deep_dotdot_escape_returns_unchanged() {
        assert_eq!(normalize_path("foo/../../bar.rs", None), "foo/../../bar.rs");
    }

    #[test]
    fn normalize_dotdot_within_scope_ok() {
        // src/../lib/file.rs stays within the repo — collapses fine.
        assert_eq!(normalize_path("src/../lib/file.rs", None), "lib/file.rs");
    }

    // ── evaluate ────────────────────────────────────────────────────────

    fn make_file_record(
        confidence: f32,
        quality: f32,
        staleness: f32,
        staleness_tier: &str,
        gotcha_keys: &[&str],
    ) -> serde_json::Value {
        json!({
            "value": "Test file purpose",
            "confidence": { "value": confidence },
            "quality": { "value": quality },
            "staleness": { "value": staleness, "tier": staleness_tier },
            "payload": {
                "gotcha_keys": gotcha_keys,
            }
        })
    }

    fn make_gotcha(confirmed: bool, confidence: f32, quality: f32) -> serde_json::Value {
        json!({
            "value": "Do not use unwrap here",
            "confidence": { "value": confidence },
            "quality": { "value": quality },
            "payload": { "confirmed": confirmed }
        })
    }

    #[test]
    fn eval_no_record() {
        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: None,
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert_eq!(result.decision, Decision::NoRecord);
        assert_eq!(result.events.len(), 1);
        assert!(matches!(&result.events[0], HookEvent::Miss { key } if key == "file:src/main.rs"));
    }

    #[test]
    fn eval_tombstone() {
        let input = EnforcementInput {
            rel_path: "src/old.rs".into(),
            file_record: Some(make_file_record(0.8, 0.5, 0.95, "tombstone", &[])),
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert_eq!(result.decision, Decision::Tombstone);
        assert!(result.events.is_empty());
    }

    #[test]
    fn eval_liability() {
        let input = EnforcementInput {
            rel_path: "src/stale.rs".into(),
            file_record: Some(make_file_record(0.8, 0.5, 0.85, "liability", &[])),
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert!(
            matches!(&result.decision, Decision::Liability { staleness, .. } if *staleness > 0.8)
        );
        assert_eq!(result.events.len(), 1);
        assert!(matches!(&result.events[0], HookEvent::Hit { .. }));
    }

    #[test]
    fn eval_confirmed_gotcha_denies() {
        let mut gotchas = HashMap::new();
        gotchas.insert("gotcha:test".to_string(), make_gotcha(true, 0.7, 0.5));

        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.7, 0.5, 0.1, "fresh", &["gotcha:test"])),
            gotcha_records: gotchas,
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert!(matches!(&result.decision, Decision::Deny { .. }));
        assert!(matches!(
            &result.events[0],
            HookEvent::BlockedUnconsultedRead { key } if key == "file:src/main.rs"
        ));
    }

    #[test]
    fn eval_unconfirmed_gotcha_allows() {
        let mut gotchas = HashMap::new();
        gotchas.insert("gotcha:test".to_string(), make_gotcha(false, 0.7, 0.5));

        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.7, 0.5, 0.1, "fresh", &["gotcha:test"])),
            gotcha_records: gotchas,
            already_consulted: false,
        };
        let result = evaluate(&input);
        // No deny signal — falls through to advisory (confidence 0.7 >= 0.3, quality 0.5 >= 0.4).
        // P4: the unconfirmed gotcha's rule must NOT leak into the injected
        // context — only confirmed gotchas contribute to injection.
        match &result.decision {
            Decision::Advisory { context } => assert!(
                !context.contains("Do not use unwrap here"),
                "unconfirmed gotcha rule leaked into injected context: {context:?}"
            ),
            other => panic!("expected Advisory, got {other:?}"),
        }
    }

    #[test]
    fn eval_low_confidence_gotcha_allows() {
        let mut gotchas = HashMap::new();
        gotchas.insert("gotcha:test".to_string(), make_gotcha(true, 0.4, 0.5));

        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.7, 0.5, 0.1, "fresh", &["gotcha:test"])),
            gotcha_records: gotchas,
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert!(matches!(&result.decision, Decision::Advisory { .. }));
    }

    #[test]
    fn eval_low_quality_gotcha_allows() {
        let mut gotchas = HashMap::new();
        gotchas.insert("gotcha:test".to_string(), make_gotcha(true, 0.7, 0.2));

        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.7, 0.5, 0.1, "fresh", &["gotcha:test"])),
            gotcha_records: gotchas,
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert!(matches!(&result.decision, Decision::Advisory { .. }));
    }

    #[test]
    fn eval_consulted_downgrades_deny() {
        let mut gotchas = HashMap::new();
        gotchas.insert("gotcha:test".to_string(), make_gotcha(true, 0.7, 0.5));

        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.7, 0.5, 0.1, "fresh", &["gotcha:test"])),
            gotcha_records: gotchas,
            already_consulted: true,
        };
        let result = evaluate(&input);
        assert!(matches!(
            &result.decision,
            Decision::AlreadyConsulted { .. }
        ));
        // AlreadyConsulted emits ComplianceHit so the v2 SessionLog dispatch
        // records an AllowAfterReceipt enforcement event (not a fresh receipt).
        assert!(matches!(&result.events[0], HookEvent::ComplianceHit { .. }));
    }

    #[test]
    fn eval_medium_confidence_advisory() {
        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.45, 0.5, 0.1, "fresh", &[])),
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert!(matches!(&result.decision, Decision::Advisory { .. }));
        assert!(matches!(&result.events[0], HookEvent::Hit { .. }));
    }

    #[test]
    fn eval_low_everything_allows() {
        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.1, 0.1, 0.1, "fresh", &[])),
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert_eq!(result.decision, Decision::Allow);
        assert!(result.events.is_empty());
    }

    #[test]
    fn eval_staleness_warning_appended() {
        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.5, 0.5, 0.5, "stale", &[])),
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        if let Decision::Advisory { context } = &result.decision {
            assert!(context.contains("staleness 0.50"));
        } else {
            panic!("expected Advisory, got {:?}", result.decision);
        }
    }

    #[test]
    fn eval_multiple_gotchas_one_deny() {
        let mut gotchas = HashMap::new();
        gotchas.insert("gotcha:safe".to_string(), make_gotcha(false, 0.7, 0.5));
        gotchas.insert("gotcha:danger".to_string(), make_gotcha(true, 0.8, 0.6));

        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(
                0.7,
                0.5,
                0.1,
                "fresh",
                &["gotcha:safe", "gotcha:danger"],
            )),
            gotcha_records: gotchas,
            already_consulted: false,
        };
        let result = evaluate(&input);
        assert!(matches!(&result.decision, Decision::Deny { .. }));
    }

    #[test]
    fn eval_deny_includes_staleness_note() {
        let mut gotchas = HashMap::new();
        gotchas.insert("gotcha:test".to_string(), make_gotcha(true, 0.7, 0.5));

        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.7, 0.5, 0.5, "stale", &["gotcha:test"])),
            gotcha_records: gotchas,
            already_consulted: false,
        };
        let result = evaluate(&input);
        if let Decision::Deny { reason, .. } = &result.decision {
            assert!(reason.contains("staleness"));
        } else {
            panic!("expected Deny");
        }
    }

    #[test]
    fn eval_invalid_json_allows() {
        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(json!("not an object")),
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        // Invalid record treated as no-record.
        assert_eq!(result.decision, Decision::NoRecord);
    }

    #[test]
    fn eval_never_produces_fail_open() {
        // FailOpen is NOT in the Decision enum at all — this test documents the contract.
        // The enum has no FailOpen variant, so this is a compile-time guarantee.
        // This test verifies the doc comment claim by testing boundary cases.
        let cases: Vec<EnforcementInput> = vec![
            EnforcementInput {
                rel_path: "x".into(),
                file_record: None,
                gotcha_records: HashMap::new(),
                already_consulted: false,
            },
            EnforcementInput {
                rel_path: "x".into(),
                file_record: Some(json!(null)),
                gotcha_records: HashMap::new(),
                already_consulted: false,
            },
            EnforcementInput {
                rel_path: "x".into(),
                file_record: Some(json!({})),
                gotcha_records: HashMap::new(),
                already_consulted: false,
            },
        ];
        for input in cases {
            let result = evaluate(&input);
            // If Decision had a FailOpen variant, we'd match against it here.
            // Since it doesn't, this documents that the pure core never fails open.
            assert!(matches!(
                result.decision,
                Decision::Allow
                    | Decision::Deny { .. }
                    | Decision::AlreadyConsulted { .. }
                    | Decision::Advisory { .. }
                    | Decision::Liability { .. }
                    | Decision::Tombstone
                    | Decision::NoRecord
                    | Decision::NotFileRead
            ));
        }
    }

    #[test]
    fn eval_context_includes_purpose_and_rules() {
        let mut gotchas = HashMap::new();
        gotchas.insert("gotcha:test".to_string(), make_gotcha(true, 0.7, 0.5));

        let input = EnforcementInput {
            rel_path: "src/main.rs".into(),
            file_record: Some(make_file_record(0.7, 0.5, 0.1, "fresh", &["gotcha:test"])),
            gotcha_records: gotchas,
            already_consulted: true,
        };
        let result = evaluate(&input);
        if let Decision::AlreadyConsulted { context } = &result.decision {
            assert!(context.contains("Purpose: Test file purpose"));
            assert!(context.contains("Do not use unwrap here"));
        } else {
            panic!("expected AlreadyConsulted, got {:?}", result.decision);
        }
    }

    #[test]
    fn eval_blast_radius_warning_for_critical_file() {
        let mut file_record = make_file_record(0.5, 0.5, 0.1, "fresh", &[]);
        // Inject blast_radius into payload
        file_record
            .as_object_mut()
            .unwrap()
            .get_mut("payload")
            .unwrap()
            .as_object_mut()
            .unwrap()
            .insert(
                "blast_radius".into(),
                json!({ "direct": 45, "transitive": 10, "score": 48.0, "tier": "critical" }),
            );

        let input = EnforcementInput {
            rel_path: "src/core.rs".into(),
            file_record: Some(file_record),
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        if let Decision::Advisory { context } = &result.decision {
            assert!(
                context.contains("Blast radius"),
                "advisory context must include blast radius warning, got: {context}"
            );
            assert!(context.contains("45"), "warning must include direct count");
            assert!(context.contains("critical"), "warning must include tier");
        } else {
            panic!("expected Advisory, got {:?}", result.decision);
        }
    }

    #[test]
    fn eval_no_blast_warning_for_low_file() {
        let mut file_record = make_file_record(0.5, 0.5, 0.1, "fresh", &[]);
        file_record
            .as_object_mut()
            .unwrap()
            .get_mut("payload")
            .unwrap()
            .as_object_mut()
            .unwrap()
            .insert(
                "blast_radius".into(),
                json!({ "direct": 2, "transitive": 0, "score": 2.0, "tier": "low" }),
            );

        let input = EnforcementInput {
            rel_path: "src/leaf.rs".into(),
            file_record: Some(file_record),
            gotcha_records: HashMap::new(),
            already_consulted: false,
        };
        let result = evaluate(&input);
        if let Decision::Advisory { context } = &result.decision {
            assert!(
                !context.contains("Blast radius"),
                "low blast radius file should NOT have warning, got: {context}"
            );
        } else {
            panic!("expected Advisory, got {:?}", result.decision);
        }
    }
}