pushkin 0.2.0

Schema-first enforcement harness that gates AI coding agents' file writes against project contracts
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
//! The agent adapter registry (addendum §4): payload normalization into one
//! `ToolAction`, and per-agent verdict encoding. One brain, five mouths —
//! adapters translate, never decide (spec §6.1).

use anyhow::{bail, Result};
use pushkin_core::edits::Replacement;
use serde_json::Value;

pub const AGENTS: &[&str] = &["claude", "codex", "auggie", "hermes", "opencode"];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Agent {
    Claude,
    Codex,
    Auggie,
    Hermes,
    Opencode,
}

impl Agent {
    /// Every adapter, in registry order — doctor dispatches over this
    /// exhaustively so a new agent cannot be forgotten silently.
    pub const ALL: [Agent; 5] = [
        Agent::Claude,
        Agent::Codex,
        Agent::Auggie,
        Agent::Hermes,
        Agent::Opencode,
    ];

    /// Resolves an agent name, rejecting unknowns with near-miss candidates
    /// (design principle: ambiguity is an error with suggestions, spec §7.1).
    pub fn parse(name: &str) -> Result<Self> {
        match name {
            "claude" => Ok(Agent::Claude),
            "codex" => Ok(Agent::Codex),
            "auggie" => Ok(Agent::Auggie),
            "hermes" => Ok(Agent::Hermes),
            "opencode" => Ok(Agent::Opencode),
            unknown => {
                let candidates = nearest_agents(unknown).join(", ");
                bail!("unknown agent '{unknown}'; did you mean: {candidates}?")
            }
        }
    }

    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Agent::Claude => "claude",
            Agent::Codex => "codex",
            Agent::Auggie => "auggie",
            Agent::Hermes => "hermes",
            Agent::Opencode => "opencode",
        }
    }
}

/// One file write extracted from a tool call.
#[derive(Debug, Clone)]
pub struct FileWrite {
    pub path: String,
    pub content: String,
    /// F48 Phase B — the edit operations, for a mutation that carries them
    /// instead of content. Empty for a `Write`, and empty for any family whose
    /// Phase B arm has not landed: an empty list means "no reconstruction is
    /// possible", which routes to Phase A's interim refusal.
    pub edits: Vec<Replacement>,
}

/// SPIKE — what the agent is trying to DO with the paths in a
/// `ToolAction`. Writes carry content and meet the contract pipeline;
/// reads carry a range instead and meet the read contract only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Intent {
    Write,
    /// An unbounded whole-file read — no `offset`/`limit` in the payload.
    ReadWhole,
    /// A read naming an explicit range: the deliberate shape, and the one
    /// that satisfies a host's read-before-edit requirement.
    ReadRange,
    /// A shell invocation. Its target is not a declared path but text inside
    /// a command string, so it is matched by substring against the gated
    /// globs rather than parsed — see `gate_shell_read`.
    Shell,
    /// F48 Phase A — a MUTATION that names a target but carries no content:
    /// `Edit`'s `old_string`/`new_string`, `MultiEdit`'s `edits[]`. It is a
    /// write in every sense that matters to a path rule, and unevaluable by
    /// every rule that needs bytes. Recognizing it is the whole fix: it used
    /// to be classified malformed, and the malformed fallback consults only
    /// `is_protected`, so `read_only_paths` and mapped-contract rules fell
    /// through to a silent allow on the two tools agents use most.
    ///
    /// Carries the tool's name so the refusal can say which one it refused —
    /// a `&'static str` from a fixed set, which keeps `Intent` `Copy`.
    MutateNoContent(&'static str),
    /// F58 — a DELETE. Decidable by the path rules and by nothing else: there
    /// is no content now and there never will be, so unlike `MutateNoContent`
    /// it must NOT refuse under `content_unavailable`. That rule says a content
    /// requirement could not be EVALUATED; for a file that is going away, no
    /// content requirement applies at all.
    Delete,
}

/// The normalized action every adapter feeds the pipeline (addendum §4).
/// `files` is usually one entry; Codex `apply_patch` may carry several.
#[derive(Debug, Clone)]
pub struct ToolAction {
    pub session: String,
    pub files: Vec<FileWrite>,
    pub is_stop: bool,
    pub intent: Intent,
    /// The raw shell command, present only for `Intent::Shell`. Carried
    /// verbatim and never parsed: a shell grammar is an adversarial surface,
    /// and a wrong parse either blocks real work or admits a crafted command.
    pub command: Option<String>,
}

/// Parse outcome mirroring the check-verb contract: `Err(Some(path))` is a
/// partial parse that still revealed a target (fail-closed candidate).
pub type ParseOutcome = Result<ToolAction, Option<String>>;

/// Normalizes one agent-native hook payload into a `ToolAction`.
pub fn normalize(agent: Agent, raw: &str) -> ParseOutcome {
    let value: Value = serde_json::from_str(raw).map_err(|_| None)?;
    match agent {
        Agent::Claude => normalize_claude_family(&value),
        Agent::Codex => normalize_codex(&value),
        Agent::Auggie => normalize_auggie(&value),
        Agent::Hermes => normalize_hermes(&value),
        Agent::Opencode => normalize_opencode(&value),
    }
}

/// Claude, Codex, and Auggie share the Claude hook payload shape
/// (addendum §3.2/§3.4: `tool_name` + `tool_input.file_path`/`content`).
fn normalize_claude_family(value: &Value) -> ParseOutcome {
    let session = session_from(value, "session_id");
    let Some(tool_input) = value.get("tool_input") else {
        if value.get("stop_hook_active").is_some() {
            return Ok(ToolAction {
                session,
                files: vec![],
                is_stop: true,
                intent: Intent::Write,
                command: None,
            });
        }
        return Err(None);
    };
    let tool_name = value.get("tool_name").and_then(Value::as_str);

    // Option C (hook-matcher-gap charter) — a shell call carries `command`,
    // never `file_path`, so it must be recognized BEFORE the path extraction
    // below, which treats a payload naming no target as unparseable. The
    // command travels intact: matching it against the gated globs needs the
    // manifest, which the normalizer does not have and should not grow.
    if tool_name == Some("Bash") {
        if let Some(command) = tool_input.get("command").and_then(Value::as_str) {
            return Ok(ToolAction {
                session,
                files: vec![],
                is_stop: false,
                intent: Intent::Shell,
                command: Some(command.to_owned()),
            });
        }
    }

    let path = tool_input
        .get("file_path")
        .and_then(Value::as_str)
        .map(relativize)
        .ok_or(None)?;

    // SPIKE — a read carries no `content`, so it must be recognized by name
    // BEFORE the write parse, which treats missing content as malformed.
    if matches!(tool_name, Some("Read" | "NotebookRead")) {
        let bounded = tool_input.get("offset").is_some() || tool_input.get("limit").is_some();
        return Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: String::new(),
                edits: Vec::new(),
            }],
            is_stop: false,
            intent: if bounded {
                Intent::ReadRange
            } else {
                Intent::ReadWhole
            },
            command: None,
        });
    }

    // F48 Phase A — the same ordering rule as the read arm above, for the same
    // reason. `Edit` and `MultiEdit` name a target and carry no `content`, so
    // the write parse below would call them malformed; the malformed fallback
    // then consults only `is_protected`, and every other rule falls through to
    // a silent allow. Recognized here as what they are: mutations whose content
    // is ABSENT, not payloads that failed to parse.
    let mutation_tool = match tool_name {
        Some("Edit") => Some("Edit"),
        Some("MultiEdit") => Some("MultiEdit"),
        _ => None,
    };
    if let Some(tool) = mutation_tool {
        // F48 Phase B — carry the edit operations through so the gate can
        // reconstruct the post-edit file. An empty list is not an error here:
        // it means no faithful reconstruction is possible, and the gate falls
        // back to Phase A's interim refusal.
        return Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: String::new(),
                edits: claude_replacements(tool_input),
            }],
            is_stop: false,
            intent: Intent::MutateNoContent(tool),
            command: None,
        });
    }

    let content = tool_input.get("content").and_then(Value::as_str);
    match (tool_name.is_some(), content) {
        (true, Some(content)) => Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: content.to_owned(),
                edits: Vec::new(),
            }],
            is_stop: false,
            intent: Intent::Write,
            command: None,
        }),
        _ => Err(Some(path)),
    }
}

/// F48 Phase B — the replacements a Claude `Edit` or `MultiEdit` describes.
///
/// `Edit` carries one `old_string`/`new_string` pair with an optional
/// `replace_all`; `MultiEdit` carries `edits[]` of the same shape, applied in
/// order. Anything that does not parse yields an empty list, which the gate
/// reads as "cannot reconstruct" and refuses on — never as "no changes".
pub fn claude_replacements(tool_input: &Value) -> Vec<Replacement> {
    if let Some(edits) = tool_input.get("edits").and_then(Value::as_array) {
        return edits.iter().filter_map(one_replacement).collect();
    }
    one_replacement(tool_input).into_iter().collect()
}

fn one_replacement(value: &Value) -> Option<Replacement> {
    Some(Replacement {
        old: value.get("old_string").and_then(Value::as_str)?.to_owned(),
        new: value.get("new_string").and_then(Value::as_str)?.to_owned(),
        replace_all: value
            .get("replace_all")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        // Claude's Edit locates purely by string search — it sends no line
        // numbers, so a repeated target is genuinely ambiguous here.
        anchor: None,
    })
}

/// F48 Phase B, auggie arm — the replacements an `str-replace-editor` call
/// describes.
///
/// The fields are NUMBERED (`old_str_1`, `new_str_1`, `old_str_2`, …) rather
/// than arrayed, so collection walks 1, 2, 3 … explicitly. Iterating the JSON
/// object instead would take the map's key order, which is not the edit order
/// and is not guaranteed to be anything in particular.
///
/// Each fragment also carries `old_str_start_line_number_N` /
/// `old_str_end_line_number_N`, which become the edit's ANCHOR. That is the
/// difference from the Claude arm and it is a real one: a fragment occurring
/// many times in the file occurs once inside its anchored lines, so edits the
/// Claude arm must refuse as ambiguous resolve exactly here.
///
/// Returns an empty list — which the gate reads as "cannot reconstruct", never
/// as "no changes" — for any payload that is not the shape above.
pub fn auggie_replacements(tool_input: &Value) -> Vec<Replacement> {
    let mut replacements = Vec::new();
    let mut index = 1;
    while let Some(old) = string_field(tool_input, "old_str", index) {
        let Some(new) = string_field(tool_input, "new_str", index) else {
            return Vec::new();
        };
        replacements.push(Replacement {
            old,
            new,
            replace_all: false,
            anchor: line_anchor(tool_input, index),
        });
        index += 1;
    }
    // A GAP in the numbering (`old_str_1` and `old_str_3`, no `old_str_2`)
    // stops the walk above with a fragment still unaccounted for. Returning the
    // prefix would synthesize a file missing one of the edits and then judge it
    // confidently — a false verdict, not a partial one.
    if names_fragment_at_or_beyond(tool_input, index) {
        return Vec::new();
    }
    replacements
}

fn string_field(tool_input: &Value, prefix: &str, index: usize) -> Option<String> {
    tool_input
        .get(format!("{prefix}_{index}"))
        .and_then(Value::as_str)
        .map(str::to_owned)
}

/// Both bounds or neither: half an anchor is a payload we do not recognize, and
/// silently treating it as unanchored would hand the edit to a string search
/// the family never intended.
fn line_anchor(tool_input: &Value, index: usize) -> Option<pushkin_core::edits::LineSpan> {
    let bound = |name: &str| {
        tool_input
            .get(format!("old_str_{name}_line_number_{index}"))
            .and_then(Value::as_u64)
            .and_then(|value| usize::try_from(value).ok())
    };
    Some(pushkin_core::edits::LineSpan {
        start: bound("start")?,
        end: bound("end")?,
    })
}

/// Whether any `old_str_<n>` with `n >= from` is present. Deliberately parses
/// the suffix rather than matching a prefix: `old_str_start_line_number_1`
/// also begins with `old_str_` and is not a fragment.
fn names_fragment_at_or_beyond(tool_input: &Value, from: usize) -> bool {
    tool_input
        .as_object()
        .into_iter()
        .flatten()
        .filter_map(|(key, _)| key.strip_prefix("old_str_"))
        .filter_map(|suffix| suffix.parse::<usize>().ok())
        .any(|index| index >= from)
}

/// Codex `PreToolUse` (learn.chatgpt.com/docs/hooks): `apply_patch` carries
/// the patch text in `tool_input.command`; each `*** Add File:` /
/// `*** Update File:` section is one gated write. The recorded-payload
/// shape (`tool_input.file_path`/`content`) is accepted first for
/// conformance-suite compatibility.
fn normalize_codex(value: &Value) -> ParseOutcome {
    if value
        .get("tool_input")
        .and_then(|input| input.get("file_path"))
        .is_some()
    {
        return normalize_claude_family(value);
    }
    let session = session_from(value, "session_id");
    let Some(tool_input) = value.get("tool_input") else {
        if value.get("stop_hook_active").is_some() {
            return Ok(ToolAction {
                session,
                files: vec![],
                is_stop: true,
                intent: Intent::Write,
                command: None,
            });
        }
        return Err(None);
    };
    let command = tool_input
        .get("command")
        .and_then(Value::as_str)
        .ok_or(None)?;
    patch_action(session, command)
}

/// F59 — the shared `apply_patch` verdict path. ONE grammar, one
/// implementation, for every family that speaks it.
///
/// codex sends this format in `tool_input.command`; opencode sends the
/// identical format in `args.patchText`. Giving each adapter its own copy of
/// the parse-and-classify logic is how two adapters drift apart on one format,
/// and the drift shows up as a verdict difference on the same bytes — so the
/// two call this instead.
fn patch_action(session: String, command: &str) -> ParseOutcome {
    let PatchSections {
        files,
        has_update,
        has_add,
        has_delete,
    } = parse_apply_patch(command);
    if files.is_empty() {
        // A patch we cannot parse still names no target: fail-open path.
        return Err(None);
    }
    // F52 — an Update section is a HUNK, so its `+` lines are a fragment of the
    // resulting file, not the file. Judging them as content produced a live
    // SILENT ALLOW on a mapped path whose handler was unvalidated (2026-08-17).
    //
    // A patch mixing Add and Update refuses on ALL its paths: a `ToolAction`
    // carries one intent for every file it names, and for an interim
    // fail-closed posture over-refusing is the correct direction. Phase B,
    // which synthesizes per file, is where the compromise ends.
    //
    // F58 — the order below is by how much each intent JUDGES, not by which
    // marker appeared first, because one `ToolAction` carries one intent for
    // every file it names. `Delete` is last for that reason: it runs the path
    // rules alone, so choosing it for a patch that also ADDS a file would let
    // the added content skip the content rules entirely — trading one fail-open
    // for another. A delete inside an Add or Update patch still gets its path
    // rules, since those run on every file under every intent here.
    let intent = if has_update {
        Intent::MutateNoContent("apply_patch")
    } else if has_add || !has_delete {
        Intent::Write
    } else {
        Intent::Delete
    };
    Ok(ToolAction {
        session,
        files,
        is_stop: false,
        intent,
        command: None,
    })
}

/// F48 Phase B, opencode arm — the replacement an `edit` call describes.
///
/// opencode's `edit` is Claude's `Edit` under different field names:
/// `oldString` / `newString` / optional `replaceAll`, defaulting to false, with
/// a not-found target and a non-unique target both errors. Established from
/// opencode's own tool schema and prompt text, not inferred from a capture.
///
/// `replaceAll` therefore defaults to FALSE here and must keep doing so.
/// Defaulting it to true would make an ambiguous edit succeed by replacing every
/// occurrence — synthesizing a file opencode itself would have refused to write,
/// and then judging it confidently. That is the F51 false-verdict class, and it
/// would arrive through a one-word mistake.
///
/// Returns an empty list — read by the gate as "cannot reconstruct", never as
/// "no changes" — for any payload that is not this shape.
fn opencode_replacements(args: &Value) -> Vec<Replacement> {
    let Some(old) = args.get("oldString").and_then(Value::as_str) else {
        return Vec::new();
    };
    let Some(new) = args.get("newString").and_then(Value::as_str) else {
        return Vec::new();
    };
    vec![Replacement {
        old: old.to_owned(),
        new: new.to_owned(),
        replace_all: args
            .get("replaceAll")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        // Located by string search alone: opencode sends no line numbers, so a
        // repeated target genuinely is ambiguous, exactly as for Claude.
        anchor: None,
    }]
}

/// Parses (path, added-content) pairs from a Codex `apply_patch` command string.
/// F52 — whether a patch carries whole files or hunks.
///
/// `*** Add File:` sections are entirely `+` lines, so the collected text IS
/// the new file and the content rules can judge it. `*** Update File:` sections
/// are HUNKS: the `+` lines are a fragment of the resulting file, and judging
/// them as though they were the file is the same false-verdict class as F51 —
/// observed live as a SILENT ALLOW on a mapped path whose real handler was
/// unvalidated.
struct PatchSections {
    files: Vec<FileWrite>,
    has_update: bool,
    has_add: bool,
    has_delete: bool,
}

/// A write target carrying no body of its own: a deleted file, or a rename
/// DESTINATION. Both are gated on their path alone (F58).
fn bare_target(path: &str) -> FileWrite {
    FileWrite {
        path: relativize(path.trim()),
        content: String::new(),
        edits: Vec::new(),
    }
}

/// The lines one hunk expects to find, and the lines it leaves behind (F52).
#[derive(Default)]
struct Hunk {
    old: Vec<String>,
    new: Vec<String>,
}

/// One `*** ... File:` section as it is being read.
struct Section {
    path: String,
    /// `*** Add File:` sections only — the whole new file, from its `+` lines.
    /// An Update section leaves this EMPTY: a hunk's `+` lines are a fragment,
    /// and treating them as the file was the original F52 defect.
    content: String,
    is_add: bool,
    edits: Vec<Replacement>,
    hunk: Option<Hunk>,
    /// A rename withholds CONTENT synthesis: the reconstructed bytes land at
    /// the destination while the source ceases to exist, so judging them
    /// against either path alone is a false verdict. F58's path rules still
    /// gate both ends.
    moved: bool,
    /// A line inside the section that fits none of the format's shapes. The
    /// section is then not understood, and silently dropping the line would
    /// reconstruct a file missing part of the change.
    malformed: bool,
}

impl Section {
    fn new(path: &str, is_add: bool) -> Self {
        Self {
            path: relativize(path.trim()),
            content: String::new(),
            is_add,
            edits: Vec::new(),
            hunk: None,
            moved: false,
            malformed: false,
        }
    }

    /// F52 — a hunk is a REPLACEMENT in disguise. Codex carries no line
    /// numbers, so a hunk is located by context: the lines it expects to find
    /// (context + deletions, in order) are the target, and the lines it leaves
    /// behind (context + additions, in order) are the replacement.
    fn close_hunk(&mut self) {
        let Some(hunk) = self.hunk.take() else {
            return;
        };
        if hunk.old.is_empty() && hunk.new.is_empty() {
            return;
        }
        self.edits.push(Replacement {
            old: hunk.old.join("\n"),
            new: hunk.new.join("\n"),
            // A hunk names one site. `apply_edits` refuses a target that is not
            // unique, which is exactly the right answer once the `@@` scope
            // header has been discarded as a locator rather than as text.
            replace_all: false,
            anchor: None,
        });
    }

    fn read(&mut self, line: &str) {
        // `@@[ scope]` opens a hunk. Anything after the marker NAMES an
        // enclosing scope to disambiguate — a locator hint, never text adjacent
        // to the hunk — so it is dropped. A hunk left ambiguous without it
        // refuses rather than picking an occurrence.
        if line.starts_with("@@") {
            self.close_hunk();
            self.hunk = Some(Hunk::default());
            return;
        }
        if let Some(added) = line.strip_prefix('+') {
            if self.is_add {
                self.content.push_str(added);
                self.content.push('\n');
            } else {
                self.hunk
                    .get_or_insert_with(Hunk::default)
                    .new
                    .push(added.to_owned());
            }
            return;
        }
        if self.is_add {
            // An Add section is entirely `+` lines by construction.
            self.malformed = !line.is_empty();
            return;
        }
        if let Some(removed) = line.strip_prefix('-') {
            self.hunk
                .get_or_insert_with(Hunk::default)
                .old
                .push(removed.to_owned());
            return;
        }
        // Context: present on BOTH sides. An empty line is an empty context
        // line — the format's leading space is often trimmed off a blank one.
        if let Some(context) = line.strip_prefix(' ') {
            let hunk = self.hunk.get_or_insert_with(Hunk::default);
            hunk.old.push(context.to_owned());
            hunk.new.push(context.to_owned());
            return;
        }
        if line.is_empty() {
            let hunk = self.hunk.get_or_insert_with(Hunk::default);
            hunk.old.push(String::new());
            hunk.new.push(String::new());
            return;
        }
        self.malformed = true;
    }

    fn finish(mut self) -> FileWrite {
        self.close_hunk();
        let edits = if self.moved || self.malformed {
            Vec::new()
        } else {
            self.edits
        };
        FileWrite {
            path: self.path,
            content: self.content,
            edits,
        }
    }
}

fn close_section(files: &mut Vec<FileWrite>, section: Option<Section>) {
    if let Some(section) = section {
        files.push(section.finish());
    }
}

fn parse_apply_patch(command: &str) -> PatchSections {
    let mut files = Vec::new();
    let mut section: Option<Section> = None;
    let mut has_update = false;
    let mut has_add = false;
    let mut has_delete = false;
    for line in command.lines() {
        if let Some(path) = line.strip_prefix("*** Add File: ") {
            close_section(&mut files, section.take());
            has_add = true;
            section = Some(Section::new(path, true));
        } else if let Some(path) = line.strip_prefix("*** Update File: ") {
            close_section(&mut files, section.take());
            has_update = true;
            section = Some(Section::new(path, false));
        } else if let Some(path) = line.strip_prefix("*** Delete File: ") {
            // F58 — a delete names its target and carries no body, so it is
            // pushed immediately rather than opening a section. Before that
            // finding it matched no marker at all and the whole patch fell open.
            close_section(&mut files, section.take());
            has_delete = true;
            files.push(bare_target(path));
        } else if let Some(path) = line.strip_prefix("*** Move to: ") {
            // F58 — the rename DESTINATION is a write target in its own right.
            // F52 — and it withholds this section's content synthesis.
            files.push(bare_target(path));
            if let Some(open) = section.as_mut() {
                open.moved = true;
            }
        } else if line.starts_with("*** End of File") {
            // A locator marker: it says the hunk sits at EOF. Nothing to read.
        } else if line.starts_with("*** End Patch") {
            close_section(&mut files, section.take());
        } else if let Some(open) = section.as_mut() {
            open.read(line);
        }
    }
    close_section(&mut files, section.take());
    PatchSections {
        files,
        has_update,
        has_add,
        has_delete,
    }
}

/// Auggie `PreToolUse` (live-captured 0.35.0, docs.augmentcode.com/cli/hooks):
/// `conversation_id` + `tool_name` + `tool_input.path`/`file_content`
/// (`save-file`) or `tool_input.path` + edit fields (`str-replace-editor`).
fn normalize_auggie(value: &Value) -> ParseOutcome {
    let session = session_from(value, "conversation_id");
    let Some(tool_input) = value.get("tool_input") else {
        // F70 — Auggie's Stop payload carries no `tool_input` at all, so this
        // early return used to make it malformed before the encoder was ever
        // reached. F68 had already encoded Auggie's Stop dialect correctly; it
        // was simply unreachable. This is the reachability half.
        //
        // The marker is `hook_event_name == "Stop"`, a COMMON base field on
        // every Auggie event. It is NOT `stop_hook_active` — that is Claude's
        // field and Auggie has no such key, which is the exact error F70 exists
        // to stop being inherited. `agent_stop_cause` ("end_turn" |
        // "interrupted" | "max_iterations" | "error") is deliberately not used:
        // it says WHY the agent stopped, not WHAT the event is, and keying on it
        // would make the branch fire on a shape that never claimed to be a Stop.
        //
        // Narrow on purpose: only a payload positively identifying itself as
        // Stop takes this branch. Anything else still returns `Err(None)` and
        // still routes to the existing malformed handling, which
        // `gate_unreadable_payload` depends on.
        if value.get("hook_event_name").and_then(Value::as_str) == Some("Stop") {
            return Ok(ToolAction {
                session,
                files: vec![],
                is_stop: true,
                intent: Intent::Write,
                command: None,
            });
        }
        return Err(None);
    };
    let path = tool_input
        .get("path")
        .or_else(|| tool_input.get("file_path"))
        .and_then(Value::as_str)
        .map(relativize)
        .ok_or(None)?;
    let tool_name = value.get("tool_name").and_then(Value::as_str);

    // SPIKE — Auggie reads through `view`, which carries a path and no
    // content. Its range fields are `view_range`/`search_query_regex`: both
    // narrow the read, so either counts as the bounded shape.
    if tool_name == Some("view") {
        let bounded = tool_input.get("view_range").is_some()
            || tool_input.get("search_query_regex").is_some();
        return Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: String::new(),
                edits: Vec::new(),
            }],
            is_stop: false,
            intent: if bounded {
                Intent::ReadRange
            } else {
                Intent::ReadWhole
            },
            command: None,
        });
    }

    // F51 — `str-replace-editor` sends REPLACEMENT FRAGMENTS
    // (`old_str_N`/`new_str_N`), never a file. Treating `new_str_1` as
    // `content` (as this chain used to) made the gate judge a fragment as
    // though it were the whole file, and it was wrong in BOTH directions: a
    // fragment with no boundary-relevant line passed vacuously, and one that
    // had a line was denied on content that never existed as a file. That is a
    // FALSE VERDICT, a worse failure than F48's fail-open, because the gate
    // sounds certain.
    //
    // Recognized here as what it is — a mutation whose content is absent —
    // BEFORE the write parse below, the same ordering rule the `view` arm above
    // uses.
    //
    // F48 Phase B (2026-08-17) now carries the fragments through, so the gate
    // reconstructs the post-edit file instead of refusing. The field family was
    // enumerated by the E1(b) capture the earlier note called for
    // (`docs/e1b-capture/fixtures/auggie-20260817T230314Z-0011.json`); an empty
    // list still means "cannot reconstruct" and still routes to the refusal.
    if tool_name == Some("str-replace-editor") {
        return Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: String::new(),
                edits: auggie_replacements(tool_input),
            }],
            is_stop: false,
            intent: Intent::MutateNoContent("str-replace-editor"),
            command: None,
        });
    }

    let well_formed = tool_name.is_some();
    // `new_str_1` is deliberately NOT in this chain — see above.
    let content = tool_input
        .get("file_content")
        .or_else(|| tool_input.get("content"))
        .and_then(Value::as_str);
    match (well_formed, content) {
        (true, Some(content)) => Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: content.to_owned(),
                edits: Vec::new(),
            }],
            is_stop: false,
            intent: Intent::Write,
            command: None,
        }),
        _ => Err(Some(path)),
    }
}

/// Hermes `pre_tool_call`: `tool_name` + `tool_input.path`/`content` (addendum §3.5).
fn normalize_hermes(value: &Value) -> ParseOutcome {
    let session = session_from(value, "session_id");
    let Some(tool_input) = value.get("tool_input") else {
        return Err(None);
    };
    let path = tool_input
        .get("path")
        .or_else(|| tool_input.get("file_path"))
        .and_then(Value::as_str)
        .map(relativize)
        .ok_or(None)?;
    let tool_name = value.get("tool_name").and_then(Value::as_str);

    // F49 — hermes edits through `patch`, which carries `old_string`/
    // `new_string` and no file content. Captured live 2026-08-17 (fixture
    // `docs/e1b-capture/fixtures/hermes-20260817T230624Z-0012.json`); the shape
    // was UNKNOWN in-repo until then, and the charter made building against a
    // guessed shape a stopping condition. Recognized before the write parse
    // below, which would otherwise call it malformed and fall through to a
    // silent allow.
    //
    // F48 Phase B (2026-08-18) now reconstructs from those fields — but on
    // NARROWER terms than any other family, because hermes matches fuzzily.
    // See `hermes_replacements`. The `mode` field remains unenumerated, so an
    // unknown mode yields no edits and routes to the refusal.
    if tool_name == Some("patch") {
        return Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: String::new(),
                edits: hermes_replacements(tool_input),
            }],
            is_stop: false,
            intent: Intent::MutateNoContent("patch"),
            command: None,
        });
    }

    let well_formed = tool_name.is_some();
    let content = tool_input.get("content").and_then(Value::as_str);
    match (well_formed, content) {
        (true, Some(content)) => Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: content.to_owned(),
                edits: Vec::new(),
            }],
            is_stop: false,
            intent: Intent::Write,
            command: None,
        }),
        _ => Err(Some(path)),
    }
}

/// F48 Phase B, hermes arm — the replacement a `patch` call describes, on
/// deliberately narrower terms than any other family gets.
///
/// **hermes matches FUZZILY, across nine strategies**, by design, so that
/// "minor whitespace/indentation differences won't break it". Every other
/// family locates its target by exact string match, which is reproducible byte
/// for byte; hermes' matcher is a component we do not have and will not
/// reimplement. So this arm reconstructs only what it can reproduce EXACTLY,
/// and `apply_edits` refuses the rest.
///
/// The cost is real and is accepted rather than hidden: pushkin refuses edits
/// hermes itself would have applied, whenever `old_string` drifts from the file
/// by so much as a space. Approximating instead would judge a file that never
/// existed — the F51 false-verdict class — which is worse in kind, not degree.
///
/// Two rules invert relative to the other arms, both toward refusal:
///
/// - `replace_all` yields NO edits here, where Claude's and opencode's arms
///   honor it. Under fuzzy matching "all" includes near-matches that cannot be
///   enumerated from here, so an exact replace-all would synthesize a file with
///   FEWER edits than hermes will actually make, and then judge it.
/// - An unknown `mode` yields no edits. The captured payload carries
///   `mode: "replace"`; the documented signature carries no mode at all; no
///   enumeration of the other values exists in the docs or in any capture.
///   Building against a guessed shape is the charter's stopping condition, so an
///   unestablished mode is refused rather than assumed to be a replacement.
fn hermes_replacements(tool_input: &Value) -> Vec<Replacement> {
    match tool_input.get("mode").and_then(Value::as_str) {
        // Absent is the documented signature; "replace" is what was captured.
        None | Some("replace") => {}
        Some(_) => return Vec::new(),
    }
    if tool_input.get("replace_all").and_then(Value::as_bool) == Some(true) {
        return Vec::new();
    }
    let Some(old) = tool_input.get("old_string").and_then(Value::as_str) else {
        return Vec::new();
    };
    let Some(new) = tool_input.get("new_string").and_then(Value::as_str) else {
        return Vec::new();
    };
    vec![Replacement {
        old: old.to_owned(),
        new: new.to_owned(),
        // Never true for hermes: see the `replace_all` note above.
        replace_all: false,
        // hermes sends no line numbers, so there is nothing to anchor to — the
        // exact-and-unique requirement is the whole of the location rule.
        anchor: None,
    }]
}

/// opencode plugin relay: `sessionID` + `tool` + `args.filePath`/`content`
/// (addendum §3.3 — the TS plugin forwards its hook input verbatim).
/// opencode hands the tool an ABSOLUTE `filePath`; manifest globs are
/// repo-relative, so relativize against the working directory (the plugin
/// sets `cwd` to the repo root), tolerating macOS's /tmp → /private/tmp.
fn normalize_opencode(value: &Value) -> ParseOutcome {
    let session = session_from(value, "sessionID");
    let Some(args) = value.get("args") else {
        return Err(None);
    };
    let tool = value.get("tool").and_then(Value::as_str);

    // F59 — opencode's OTHER native mutation tool. It carries `patchText` and
    // names no `filePath`, so the extraction below called it unparseable and the
    // gate answered `{"decision":"allow"}` — on this family the fail-open is an
    // AFFIRMED write, not merely an unnoticed one, because opencode's verdict
    // channel is explicit and its plugin acts on what it is handed.
    //
    // Recognized before the extraction, the same ordering rule every other arm
    // in this file uses, and routed through the SHARED patch path so codex and
    // opencode cannot reach different verdicts on identical patch text.
    if tool == Some("apply_patch") {
        if let Some(patch) = args.get("patchText").and_then(Value::as_str) {
            return patch_action(session, patch);
        }
    }

    let path = args
        .get("filePath")
        .and_then(Value::as_str)
        .map(relativize)
        .ok_or(None)?;

    // SPIKE — opencode's read tool is `read` with `args.filePath` (the
    // `.env`-protection example in the plugin docs is exactly this shape).
    // Same ordering rule as the Claude family: recognize the read before
    // the write parse, which treats absent content as malformed.
    if tool == Some("read") {
        let bounded = args.get("offset").is_some() || args.get("limit").is_some();
        return Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: String::new(),
                edits: Vec::new(),
            }],
            is_stop: false,
            intent: if bounded {
                Intent::ReadRange
            } else {
                Intent::ReadWhole
            },
            command: None,
        });
    }

    // F50 — opencode edits through `edit`, whose `args` carry
    // `oldString`/`newString` and no content. Captured live 2026-08-17
    // (fixture `docs/e1b-capture/fixtures/opencode-20260817T230641Z-0014.json`).
    // Same ordering rule as the `read` arm above, and for the same reason.
    if tool == Some("edit") {
        return Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: String::new(),
                edits: opencode_replacements(args),
            }],
            is_stop: false,
            intent: Intent::MutateNoContent("edit"),
            command: None,
        });
    }

    let well_formed = tool.is_some();
    let content = args.get("content").and_then(Value::as_str);
    match (well_formed, content) {
        (true, Some(content)) => Ok(ToolAction {
            session,
            files: vec![FileWrite {
                path,
                content: content.to_owned(),
                edits: Vec::new(),
            }],
            is_stop: false,
            intent: Intent::Write,
            command: None,
        }),
        _ => Err(Some(path)),
    }
}

/// Strips the current working directory (raw and canonicalized) from an
/// absolute path; relative paths pass through unchanged. Applied in every
/// normalizer: agents freely mix absolute and repo-relative paths (live
/// finding: Hermes retried a blocked write with the absolute path and the
/// glob missed it).
fn relativize(path: &str) -> String {
    let candidate = std::path::Path::new(path);
    if candidate.is_relative() {
        return path.to_owned();
    }
    let Ok(cwd) = std::env::current_dir() else {
        return path.to_owned();
    };
    if let Ok(stripped) = candidate.strip_prefix(&cwd) {
        return stripped.to_string_lossy().into_owned();
    }
    if let Ok(canonical_cwd) = cwd.canonicalize() {
        if let Ok(stripped) = candidate.strip_prefix(&canonical_cwd) {
            return stripped.to_string_lossy().into_owned();
        }
    }
    path.to_owned()
}

fn session_from(value: &Value, key: &str) -> String {
    value
        .get(key)
        .and_then(Value::as_str)
        .unwrap_or("anonymous-session")
        .to_owned()
}

fn nearest_agents(unknown: &str) -> Vec<&'static str> {
    let mut scored: Vec<(usize, &'static str)> = AGENTS
        .iter()
        .map(|&agent| (levenshtein(unknown, agent), agent))
        .collect();
    scored.sort_unstable();
    scored.truncate(2);
    scored.into_iter().map(|(_, agent)| agent).collect()
}

fn levenshtein(a: &str, b: &str) -> usize {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let mut previous: Vec<usize> = (0..=b_chars.len()).collect();
    let mut current = vec![0usize; b_chars.len() + 1];
    for (i, &a_char) in a_chars.iter().enumerate() {
        current[0] = i + 1;
        for (j, &b_char) in b_chars.iter().enumerate() {
            let substitution = usize::from(a_char != b_char);
            current[j + 1] = (previous[j] + substitution)
                .min(previous[j + 1] + 1)
                .min(current[j] + 1);
        }
        std::mem::swap(&mut previous, &mut current);
    }
    previous[b_chars.len()]
}