pushkin 0.2.1

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
1053
1054
1055
1056
1057
1058
1059
1060
//! `pushkin init`: versioned consent + agent adapter install packs
//! (addendum §3), idempotent at the same consent version, marker-tagged so
//! doctor/uninstall can find every pushkin entry. `--remove-agent` strips
//! exactly our entries and nothing else.

use anyhow::{bail, Context, Result};
use pushkin_core::legacy;
use serde_json::{json, Value};

use crate::agents::Agent;

use super::{CLAUDE_SETTINGS, CONSENT_FILE, CONSENT_VERSION, PUSHKIN_MARKER};

const FOOTPRINT: &str = "pushkin init will touch exactly these files:\n  \
    <agent config>          — add gate hook entries (marker: pushkin-v1)\n  \
    .pushkin/consent.json  — record this consent\n\
    All data stays local; nothing leaves this machine.";

/// Entry point for the init verb with Phase 2 arguments.
pub fn run_with_args(agent: Option<&str>, remove_agent: Option<&str>) -> Result<i32> {
    if let Some(name) = remove_agent {
        return remove(name);
    }
    migrate_legacy_footprint()?;
    ensure_consent()?;
    match agent {
        // Bare `init` keeps its Phase 1 behavior: Claude pack.
        None | Some("claude") => install_claude()?,
        Some("codex") => install_codex()?,
        Some("auggie") => install_auggie()?,
        Some("hermes") => install_hermes()?,
        Some("opencode") => install_opencode()?,
        // The git-plane surfaces honor the [features] switch: while the
        // human has the plane off, install refuses loudly rather than
        // quietly re-arming a floor `pushkin disable git-hooks` removed.
        Some("lefthook") => {
            super::features::ensure_git_hooks_enabled()?;
            install_lefthook()?;
        }
        Some("git") => {
            super::features::ensure_git_hooks_enabled()?;
            install_git_shim()?;
        }
        Some("agents-md") => install_agents_md()?,
        Some(unknown) => {
            // Reuse the agent parser's candidate error; the extras are named.
            match Agent::parse(unknown) {
                Ok(_) => unreachable!("all agents handled above"),
                Err(error) => bail!(
                    "{error} (or 'lefthook' for the pre-commit floor, \
                     'agents-md' for the managed instructions block)"
                ),
            }
        }
    }
    Ok(0)
}

/// One-time pre-rename footprint migration (remediation pass 3, B2):
/// the legacy state and waiver dirs to their pushkin names when only the
/// old names exist; a coexisting pair is a loud refusal from the core.
/// Runs at `init` and `doctor --repair` — the verbs that own the install.
pub fn migrate_legacy_footprint() -> Result<()> {
    let renamed = legacy::migrate_dirs(std::path::Path::new("."))
        .context("legacy pre-rename state found but not migratable")?;
    for dir in renamed {
        println!(
            "pushkin: migrated legacy dir {} -> {} (one-time rename; contents preserved).",
            dir.old.display(),
            dir.new.display()
        );
    }
    Ok(())
}

fn ensure_consent() -> Result<()> {
    if let Ok(text) = std::fs::read_to_string(CONSENT_FILE) {
        if let Ok(existing) = serde_json::from_str::<Value>(&text) {
            if existing.get("version").and_then(Value::as_u64) == Some(u64::from(CONSENT_VERSION)) {
                println!("pushkin: consent already recorded; refreshing install.");
                return Ok(());
            }
        }
    }
    println!("{FOOTPRINT}");
    if let Some(parent) = std::path::Path::new(CONSENT_FILE).parent() {
        std::fs::create_dir_all(parent).context("cannot create .pushkin/")?;
    }
    let ack = json!({ "version": CONSENT_VERSION });
    std::fs::write(CONSENT_FILE, serde_json::to_string_pretty(&ack)?)
        .context("cannot write consent file")?;
    Ok(())
}

/// The command agents invoke, PATH-resolved (the L3(a) decision, applied to
/// the adapter packs). The Phase 0 lesson stands — hook environments make no
/// PATH promises — but its remedy, embedding `current_exe()`, is retired: a
/// stale absolute path produces the same silent no-op the lesson guards
/// against (field evidence: d75765f) while adding machine- and
/// build-specificity, and it worsens once binaries move on install/upgrade.
/// Residual risk is routed to doctor, which names an unresolvable `pushkin`.
fn hook_command(agent: &str) -> String {
    format!("{BINARY} hook {agent}")
}

/// The binary as generated artifacts must name it: resolved from PATH, never
/// an absolute path baked in at install time.
const BINARY: &str = "pushkin";

// ---------- Claude (addendum §3.1) ----------

/// Resolution-failure semantics (D6, ratified 2026-08-15): the hook is a
/// JSON command string executed by Claude Code, unguardable in-band; a
/// missing binary surfaces per the HOST's own hook rules. Deliberately
/// not wrapped in a shim — one enforcement layer per invariant; the
/// pre-commit floor is the hard gate.
pub fn install_claude() -> Result<()> {
    let command = hook_command("claude");
    let mut settings = read_json_or_empty(CLAUDE_SETTINGS)?;
    let hooks = ensure_object_entry(&mut settings, "hooks")?;
    set_marked_entry(
        hooks,
        "PreToolUse",
        json!({
            "_pushkin": PUSHKIN_MARKER,
            // Read/NotebookRead carry the read contract; Bash closes the
            // shell bypass of it. Without Bash here the hook process never
            // starts for a shell call, so there is no verdict to fail
            // closed — the gap is the matcher, not the gate.
            "matcher": "Write|Edit|MultiEdit|Read|NotebookRead|Bash",
            "hooks": [{ "type": "command", "command": command }]
        }),
    )?;
    set_marked_entry(
        hooks,
        "Stop",
        json!({
            "_pushkin": PUSHKIN_MARKER,
            "hooks": [{ "type": "command", "command": command }]
        }),
    )?;
    // Lifecycle injection (spec §7.2 channel 1): the digest rides
    // SessionStart, compaction-aware and deduplicated hook-side.
    set_marked_entry(
        hooks,
        "SessionStart",
        json!({
            "_pushkin": PUSHKIN_MARKER,
            "hooks": [{ "type": "command", "command": command }]
        }),
    )?;
    write_json(CLAUDE_SETTINGS, &settings)?;
    println!("pushkin: claude hooks installed ({CLAUDE_SETTINGS}).");
    Ok(())
}

// ---------- Codex (addendum §3.2: hooks + execpolicy floor) ----------

fn install_codex() -> Result<()> {
    let command = hook_command("codex");
    let path = ".codex/hooks.json";
    let mut settings = read_json_or_empty(path)?;
    let hooks = ensure_object_entry(&mut settings, "hooks")?;
    set_marked_entry(
        hooks,
        "PreToolUse",
        json!({
            "_pushkin": PUSHKIN_MARKER,
             "matcher": "apply_patch|write_file",
            "hooks": [{ "type": "command", "command": command }]
        }),
    )?;
    write_json(path, &settings)?;

    // execpolicy floor: Starlark prefix_rule syntax for Codex hooks.  These
    // gate shell-level mutations of Pushkin's own config (the PreToolUse hook
    // remains the primary gate for tool-level writes).
    // Resolution-failure semantics (D6): same as claude — a JSON command
    // string, host-owned failure mode, deliberately not wrapped.
    let rules = "prefix_rule([\"rm\", \"pushkin.toml\"], decision=\"forbidden\")\n\
                 prefix_rule([\"mv\", \".claude/settings.json\"], decision=\"forbidden\")\n\
                 prefix_rule([\"echo\"], decision=\"allow\")\n";
    std::fs::create_dir_all(".codex/rules").context("cannot create .codex/rules")?;
    std::fs::write(".codex/rules/pushkin.rules", rules).context("cannot write execpolicy floor")?;
    println!("pushkin: codex hooks + execpolicy floor installed (.codex/).");
    // F56 — "installed" is not "live" for codex, and the flat claim is what
    // makes the gap dangerous: it is the sentence an operator relies on.
    // Codex gates hook execution behind a persisted trust grant that pushkin
    // cannot establish, so a fresh install is silently ungated until a human
    // grants it. Say so here, at the only moment the operator is certain to
    // be reading.
    println!(
        "NOTE (F56): codex requires a persisted HOOK TRUST grant before it will run\n\
         this hook. Until it is granted the hook DOES NOT FIRE and this repo is\n\
         UNGATED for codex. pushkin cannot verify this grant from here. Establish it by\n\
         running codex once interactively and approving, or pass\n\
         --dangerously-bypass-hook-trust for automation that vets its hook sources.\n\
         Project trust (`trust_level` in ~/.codex/config.toml) is a DIFFERENT setting\n\
         and does not cover this. The execpolicy floor and the pre-commit floor are\n\
         unaffected."
    );
    Ok(())
}

// ---------- Auggie (addendum §3.4; docs.augmentcode.com/cli/hooks) ----------

fn install_auggie() -> Result<()> {
    // Auggie only executes hook commands that are scripts with a supported
    // extension (.sh on Unix) — a bare binary path is ignored. Write a thin
    // wrapper script and point the settings entry at it.
    std::fs::create_dir_all(".augment/hooks").context("cannot create .augment/hooks")?;
    let script_path = ".augment/hooks/pushkin.sh";
    // The wrapper resolves `pushkin` from PATH: baking an absolute path here
    // is what went stale in d75765f (A1). It carries the shared N13 guard
    // (D6): auggie's own missing-command semantics are undocumented, and
    // this script is the one adapter artifact pushkin owns end to end, so
    // absence fails open loudly here instead of as a bare exec 127.
    let script = format!(
        "#!/bin/sh\n# GENERATED by pushkin init — do not hand-edit. marker: {PUSHKIN_MARKER}\n{}",
        fail_open_guard(&hook_command("auggie"))
    );
    std::fs::write(script_path, script).context("cannot write hook script")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(script_path, std::fs::Permissions::from_mode(0o755))
            .context("cannot mark hook script executable")?;
    }

    let script_absolute =
        std::fs::canonicalize(script_path).context("cannot resolve hook script path")?;
    let path = ".augment/settings.json";
    let mut settings = read_json_or_empty(path)?;
    let hooks = ensure_object_entry(&mut settings, "hooks")?;
    set_marked_entry(
        hooks,
        "PreToolUse",
        json!({
            "_pushkin": PUSHKIN_MARKER,
            "matcher": "save-file|str-replace-editor",
            "hooks": [{ "type": "command", "command": script_absolute.to_string_lossy() }]
        }),
    )?;
    write_json(path, &settings)?;
    println!("pushkin: auggie hooks installed (.augment/settings.json + hooks/pushkin.sh).");
    Ok(())
}

// ---------- Hermes (addendum §3.5: plugin hook, advisory tier) ----------

fn install_hermes() -> Result<()> {
    // Hermes plugins live under $HERMES_HOME/plugins/<name>/ with a
    // plugin.yaml manifest and register() in __init__.py (docs:
    // user-guide/features/plugins). SELF-SCOPING (addendum §3.4 wrapper
    // pattern): gates only when the process cwd carries a pushkin.toml.
    let hermes_home = std::env::var("HERMES_HOME")
        .unwrap_or_else(|_| format!("{}/.hermes", std::env::var("HOME").unwrap_or_default()));
    let plugin_dir = format!("{hermes_home}/plugins/pushkin-gate");
    std::fs::create_dir_all(&plugin_dir).with_context(|| format!("cannot create {plugin_dir}"))?;

    let manifest = "# GENERATED by pushkin init — do not hand-edit. marker: pushkin-v1\n\
name: pushkin-gate\n\
version: 0.1.0\n\
description: Pushkin pre-write gate (self-scoping; active only in repos with pushkin.toml)\n\
entry: __init__.py\n";
    std::fs::write(format!("{plugin_dir}/plugin.yaml"), manifest)
        .context("cannot write plugin.yaml")?;

    let plugin = format!(
        "# GENERATED by pushkin init — do not hand-edit. marker: pushkin-v1\n\
         # Self-scoping Pushkin gate for Hermes (pre_tool_call).\n\
         import json\n\
         import os\n\
         import subprocess\n\n\
         PUSHKIN_BIN = {binary_quoted}\n\
         WRITE_TOOLS = {{\"write_file\", \"patch\"}}\n\n\n\
         def pushkin_gate(tool_name, args, task_id, **kwargs):\n\
         \x20\x20\x20\x20if tool_name not in WRITE_TOOLS:\n\
         \x20\x20\x20\x20\x20\x20\x20\x20return None\n\
         \x20\x20\x20\x20if not os.path.exists(\"pushkin.toml\"):\n\
         \x20\x20\x20\x20\x20\x20\x20\x20return None  # self-scoping: only gated repos\n\
         \x20\x20\x20\x20payload = json.dumps({{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\"session_id\": task_id or \"hermes-session\",\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\"tool_name\": tool_name,\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\"tool_input\": args,\n\
         \x20\x20\x20\x20}})\n\
         \x20\x20\x20\x20try:\n\
         \x20\x20\x20\x20\x20\x20\x20\x20result = subprocess.run(\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20[PUSHKIN_BIN, \"hook\", \"hermes\"],\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20input=payload, capture_output=True, text=True, timeout=20,\n\
         \x20\x20\x20\x20\x20\x20\x20\x20)\n\
         \x20\x20\x20\x20except (OSError, subprocess.TimeoutExpired) as error:\n\
         \x20\x20\x20\x20\x20\x20\x20\x20# Advisory tier is fail-open BY DESIGN, but never silently.\n\
         \x20\x20\x20\x20\x20\x20\x20\x20print(f\"pushkin plugin: gate invocation failed: {{error}}\")\n\
         \x20\x20\x20\x20\x20\x20\x20\x20return None\n\
         \x20\x20\x20\x20try:\n\
         \x20\x20\x20\x20\x20\x20\x20\x20verdict = json.loads(result.stdout or \"{{}}\")\n\
         \x20\x20\x20\x20except json.JSONDecodeError:\n\
         \x20\x20\x20\x20\x20\x20\x20\x20return None\n\
         \x20\x20\x20\x20if verdict.get(\"action\") == \"block\":\n\
         \x20\x20\x20\x20\x20\x20\x20\x20return verdict\n\
         \x20\x20\x20\x20return None\n\n\n\
         def register(ctx):\n\
         \x20\x20\x20\x20ctx.register_hook(\"pre_tool_call\", pushkin_gate)\n",
        binary_quoted = serde_json::json!(BINARY),
    );
    std::fs::write(format!("{plugin_dir}/__init__.py"), plugin)
        .context("cannot write hermes plugin")?;
    // Best-effort cleanup of the pre-rename locations: the manifest-less
    // Phase 2 draft and the pre-rename plugin dir (old names live in the
    // legacy module — sweep exclusion, remediation pass 3).
    let _ = std::fs::remove_dir_all(format!(
        "{hermes_home}/plugins/{}",
        legacy::HERMES_DRAFT_DIR
    ));
    let _ = std::fs::remove_dir_all(format!(
        "{hermes_home}/plugins/{}",
        legacy::HERMES_PLUGIN_DIR
    ));
    println!(
        "pushkin: hermes pre_tool_call plugin installed ({plugin_dir}).\n\
         Enable it once with `hermes plugins enable pushkin-gate` if not auto-enabled.\n\
         NOTE: the Hermes tier is advisory and fail-open — hooks are best-effort\n\
         there; pair with the lefthook pre-commit floor for hard enforcement."
    );
    Ok(())
}

// ---------- opencode (addendum §3.3: plugin + permission block) ----------

fn install_opencode() -> Result<()> {
    std::fs::create_dir_all(".opencode/plugin").context("cannot create .opencode/plugin")?;
    let plugin = format!(
        "// GENERATED by pushkin init — do not hand-edit. marker: {PUSHKIN_MARKER}\n\
         // Thin relay: invokes `{command}` on every\n\
         // tool.execute.before and throws on a deny verdict (throw = block).\n\
         import {{ spawnSync }} from \"node:child_process\";\n\n\
         export const PushkinPlugin = async (ctx: {{ directory?: string }}) => {{\n\
           const repoDir = ctx?.directory ?? process.cwd();\n\
           return {{\n\
             \"tool.execute.before\": async (input: unknown, output: unknown) => {{\n\
               const payload = JSON.stringify({{ ...(input as object), args: (output as {{ args?: unknown }}).args }});\n\
               const result = spawnSync({binary:?}, [\"hook\", \"opencode\"], {{ input: payload, encoding: \"utf8\", cwd: repoDir }});\n\
               if (result.error || result.status !== 0) {{\n\
                 // Broken relay must be loud, not a silent allow (charter conduct 4.4).\n\
                 console.error(`pushkin plugin: gate invocation failed: ${{result.error ?? result.stderr}}`);\n\
                 return;\n\
               }}\n\
               const verdict = JSON.parse(result.stdout || \"{{}}\");\n\
               if (verdict.decision === \"deny\") throw new Error(verdict.reason);\n\
             }},\n\
           }};\n\
         }};\n",
        binary = BINARY,
        command = hook_command("opencode"),
    );
    std::fs::write(".opencode/plugin/pushkin.ts", plugin).context("cannot write plugin")?;

    let mut config = read_json_or_empty("opencode.json")?;
    let permissions = ensure_object_entry(&mut config, "permission")?;
    permissions
        .as_object_mut()
        .context("permission must be an object")?
        .insert("task".to_owned(), json!("ask"));
    write_json("opencode.json", &config)?;
    println!("pushkin: opencode plugin + permission block installed (.opencode/, opencode.json).");
    Ok(())
}

// ---------- AGENTS.md managed block (spec §15 Phase 3; addendum §6) ----------

const AGENTS_MD: &str = "AGENTS.md";
const BLOCK_BEGIN: &str =
    "<!-- pushkin:begin pushkin-v1 — GENERATED from pushkin.toml; do not hand-edit -->";
const BLOCK_END: &str = "<!-- pushkin:end pushkin-v1 -->";

/// Writes the manifest-rendered digest between pushkin markers in
/// AGENTS.md — replace in place when markers exist, append otherwise,
/// user content outside the markers untouched.
fn install_agents_md() -> Result<()> {
    let manifest = super::load_manifest()?;
    let digest = super::instructions::render_digest(&manifest)?;
    let block = format!("{BLOCK_BEGIN}\n{digest}{BLOCK_END}\n");
    let existing = match std::fs::read_to_string(AGENTS_MD) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(error) => return Err(error).context("cannot read AGENTS.md"),
    };
    let updated = splice_managed_block(&existing, &block);
    std::fs::write(AGENTS_MD, updated).context("cannot write AGENTS.md")?;
    println!("pushkin: AGENTS.md managed block installed (between pushkin markers).");
    Ok(())
}

fn splice_managed_block(existing: &str, block: &str) -> String {
    if let Some((prefix, tail)) = split_around_block(existing) {
        return format!("{prefix}{block}{tail}");
    }
    if existing.is_empty() {
        return block.to_owned();
    }
    let separator = if existing.ends_with("\n\n") {
        ""
    } else if existing.ends_with('\n') {
        "\n"
    } else {
        "\n\n"
    };
    format!("{existing}{separator}{block}")
}

fn strip_managed_block(existing: &str) -> String {
    let Some((prefix, tail)) = split_around_block(existing) else {
        return existing.to_owned();
    };
    let mut head = prefix.to_owned();
    while head.ends_with("\n\n") {
        head.pop();
    }
    format!("{head}{tail}")
}

/// The text before and after the managed block (block's trailing newline
/// consumed), or `None` when no complete marker pair is present.
fn split_around_block(existing: &str) -> Option<(&str, &str)> {
    let begin = existing.find(BLOCK_BEGIN)?;
    let end_marker = existing.find(BLOCK_END)?;
    let end = end_marker + BLOCK_END.len();
    let tail = existing.get(end..)?;
    let tail = tail.strip_prefix('\n').unwrap_or(tail);
    Some((&existing[..begin], tail))
}

// ---------- lefthook (the agent-agnostic pre-commit floor) ----------

/// The floor's config file (spec §17).
pub const LEFTHOOK_FILE: &str = "lefthook.yml";

/// The command the floor runs, verbatim from spec §17 (DESIGN-FINDINGS
/// §17). PATH-resolved on purpose: an absolute `current_exe()` path is
/// machine- and build-specific, so a generated floor broke on every other
/// clone and after `cargo clean`. Doctor names the case where `pushkin`
/// is not resolvable, which is the tradeoff this makes visible.
pub const LEFTHOOK_COMMAND: &str = "pushkin check --staged --json";

/// The install hint carried by the fail-open notice — finalized per the
/// D3 ruling (crates.io as `pushkin`, 2026-08-15). `cargo install pushkin`
/// is actionable AND slash-free, so the committed floor invariant (no
/// `/` in generated output) holds with no carve-out. The marker stays v3:
/// hint wording does not make a floor stale.
const LEFTHOOK_INSTALL_HINT: &str = "install with: cargo install pushkin";

/// The guarded pre-commit body (N13, ratified NARROW rider).
///
/// Fails open ONLY on positively probed absence — the binary or the manifest
/// missing — so a teammate who has not installed pushkin is not blocked by a
/// hook they never opted into. A check that RUNS is never second-guessed:
/// `exec` replaces the shell, so the check's own exit code and stderr reach
/// git untouched (2 blocks; 1 from a broken manifest blocks loudly). There is
/// deliberately NO exit-code case analysis here — inspecting `$?` is what the
/// superseded wide "exit-1 fails open" scope did wrong.
///
/// `[ -n "$(command -v pushkin)" ]` is the required probe form: the obvious
/// `>/dev/null` redirect would bake a `/` into generated output and break the
/// floor's no-absolute-path invariant.
fn lefthook_guard() -> String {
    fail_open_guard(LEFTHOOK_COMMAND)
}

/// The same guard around an arbitrary command — shared by the lefthook
/// floor, the native git shim, and the auggie hook script (D6: guard
/// where the host has no fail-open story of its own), so every emitted
/// surface fails open identically and the notice stays one string.
fn fail_open_guard(command: &str) -> String {
    format!(
        "if [ -n \"$(command -v pushkin)\" ] && [ -f pushkin.toml ]; then\n  \
           exec {command}\n\
         else\n  \
           echo 'pushkin: not installed or no pushkin.toml; failing open \
         ({LEFTHOOK_INSTALL_HINT})' >&2\n  \
           exit 0\n\
         fi\n"
    )
}

/// Managed-block markers, the AGENTS.md precedent applied to YAML: our
/// block is replaced on re-run; anything outside is the user's and is
/// never touched.
const LEFTHOOK_BEGIN: &str =
    "  # pushkin:begin pushkin-v3 — GENERATED by pushkin init; do not hand-edit";
const LEFTHOOK_END: &str = "  # pushkin:end pushkin-v3";

/// Our block as it appears nested under `pre-commit: commands:`. The guard is
/// emitted as a literal block scalar (`run: |`) so the shell body survives
/// YAML parsing verbatim — quoting a multi-line `if` into a flow scalar is the
/// class of mistake that shipped an invalid config once already.
fn lefthook_block() -> String {
    let indented = lefthook_guard()
        .lines()
        .fold(String::new(), |mut acc, line| {
            use std::fmt::Write as _;
            let _ = writeln!(acc, "        {line}");
            acc
        });
    format!("{LEFTHOOK_BEGIN}\n    pushkin:\n      run: |\n{indented}{LEFTHOOK_END}\n")
}

/// The floor's own marker generation. Deliberately NOT `PUSHKIN_MARKER`:
/// that constant tags the JSON adapter entries, and this pass changes only
/// the lefthook format. v1 → v2 made the absolute-path/Stop-sweep floor
/// detectable; v2 → v3 marks the pre-guard floor, which blocked teammates
/// who had never installed pushkin (N13).
pub const LEFTHOOK_MARKER: &str = "pushkin-v3";

/// The whole file, for a repo that does not already run lefthook.
fn lefthook_full_file() -> String {
    format!(
        "# GENERATED by pushkin init — do not hand-edit. marker: {LEFTHOOK_MARKER}\n\
         pre-commit:\n  commands:\n{}",
        lefthook_block()
    )
}

/// Installs the floor without destroying a config the repo already has
/// (field evidence: a live install into a repo carrying a ruff pre-commit
/// command would have clobbered it). Absent file → write the generated
/// file; present file → splice ONLY our marker-bracketed block into its
/// `pre-commit: commands:` map.
pub fn install_lefthook() -> Result<()> {
    let existing = match std::fs::read_to_string(LEFTHOOK_FILE) {
        Ok(text) => Some(text),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => return Err(error).context("cannot read lefthook.yml"),
    };
    let updated = match existing {
        None => lefthook_full_file(),
        Some(text) => splice_lefthook_block(&text),
    };
    std::fs::write(LEFTHOOK_FILE, updated).context("cannot write lefthook.yml")?;
    println!(
        "pushkin: lefthook pre-commit floor installed ({LEFTHOOK_FILE}); \
         the hook runs `{LEFTHOOK_COMMAND}` when pushkin is on PATH, and \
         fails open with a notice when it is not."
    );
    Ok(())
}

/// Our block spliced into an existing config: replaces a previous pushkin
/// block (any marker generation) in place — scrubbing any stale generated
/// header or orphaned marker comment around it — else inserts under the
/// existing `pre-commit: commands:` at the config's own entry indent, else
/// appends a `pre-commit:` section.
fn splice_lefthook_block(existing: &str) -> String {
    let block = lefthook_block();
    if let Some((prefix, tail)) = split_around_lefthook_block(existing) {
        let prefix = without_pushkin_comment_lines(prefix, true);
        let tail = without_pushkin_comment_lines(tail, true);
        return format!("{prefix}{block}{tail}");
    }
    if let Some(stale) = strip_stale_pushkin_command(existing) {
        // A v1 floor: unmarked, one `pushkin:` command entry to replace.
        return splice_lefthook_block(&stale);
    }
    if let Some((insertion, entry_indent)) = commands_insertion_point(existing) {
        let (head, tail) = existing.split_at(insertion);
        let block = reindent_block(&block, entry_indent);
        return format!("{head}{block}{tail}");
    }
    let separator = if existing.ends_with('\n') { "" } else { "\n" };
    format!("{existing}{separator}pre-commit:\n  commands:\n{block}")
}

/// Tracks YAML block-scalar context across a line scan: a mapping value
/// introduced with `|` or `>` (any chomping indicator) swallows every
/// following line that is blank or more-indented than the introducing key.
/// Comment-shaped text inside such a scalar is the user's DATA, not YAML
/// structure — pushkin must neither match markers there nor scrub there
/// (PR #24 exit review, R2).
struct ScalarTracker {
    scalar_indent: Option<usize>,
}

impl ScalarTracker {
    fn new() -> Self {
        Self {
            scalar_indent: None,
        }
    }

    /// True when `line` is block-scalar CONTENT. The introducing key line
    /// itself is structure and returns false.
    fn content_line(&mut self, line: &str) -> bool {
        let trimmed = line.trim();
        if let Some(indent) = self.scalar_indent {
            if trimmed.is_empty() || line_indent(line) > indent {
                return true;
            }
            self.scalar_indent = None;
        }
        if introduces_block_scalar(trimmed) {
            self.scalar_indent = Some(line_indent(line));
        }
        false
    }
}

fn line_indent(line: &str) -> usize {
    line.len() - line.trim_start().len()
}

/// A mapping-value line ending in a block-scalar header (`run: |`,
/// `run: >-`, …). Comments never introduce scalars. Keyed on the FIRST
/// colon, deliberately conservative: an undetected scalar risks a scrub
/// inside it, so the plain `key: |` shapes lefthook actually uses are the
/// contract here.
fn introduces_block_scalar(trimmed: &str) -> bool {
    if trimmed.starts_with('#') {
        return false;
    }
    let Some((_, value)) = trimmed.split_once(':') else {
        return false;
    };
    matches!(value.trim(), "|" | "|-" | "|+" | ">" | ">-" | ">+")
}

/// Text before and after a marker-bracketed pushkin block, if present. The
/// pair is matched by PREFIX (`# pushkin:begin pushkin-v` / `# pushkin:end
/// pushkin-v`), so every marker generation — past and future — is replaced
/// in place. An enumerated version list here is what silently dropped v2
/// when the marker moved to v3 (PR #23 exit review, M1): the list was
/// authored as (current, v1) and did not move with the bump.
fn split_around_lefthook_block(existing: &str) -> Option<(&str, &str)> {
    let mut begin: Option<usize> = None;
    let mut offset = 0usize;
    let mut scalars = ScalarTracker::new();
    for line in existing.split_inclusive('\n') {
        if scalars.content_line(line) {
            // Marker-shaped text inside a foreign block scalar is the
            // user's data, never a block boundary (R2).
            offset += line.len();
            continue;
        }
        let trimmed = line.trim();
        match begin {
            None if trimmed.starts_with("# pushkin:begin pushkin-v") => begin = Some(offset),
            Some(at) if trimmed.starts_with("# pushkin:end pushkin-v") => {
                let tail = existing.get(offset + line.len()..).unwrap_or("");
                return Some((&existing[..at], tail));
            }
            _ => {}
        }
        offset += line.len();
    }
    None
}

/// Drops pushkin's own comment litter — begin/end marker lines and the
/// generated-file header — from user-owned text around the block, so no
/// prior generation's comment survives an upgrade (the C1 invariant:
/// nothing pushkin-generated exists outside the single current block).
/// `keep_current` retains lines carrying the current marker — an upgrade
/// leaves a current-generation header where it stands; uninstall passes
/// `false` so removal takes every generation's litter with it.
pub(crate) fn without_pushkin_comment_lines(text: &str, keep_current: bool) -> String {
    let mut kept = String::new();
    let mut scalars = ScalarTracker::new();
    for line in text.split_inclusive('\n') {
        let in_scalar = scalars.content_line(line);
        let trimmed = line.trim();
        let ours = !in_scalar
            && (trimmed.starts_with("# pushkin:begin pushkin-v")
                || trimmed.starts_with("# pushkin:end pushkin-v")
                || trimmed.starts_with("# GENERATED by pushkin init"));
        if ours && !(keep_current && trimmed.contains(LEFTHOOK_MARKER)) {
            continue;
        }
        kept.push_str(line);
    }
    kept
}

/// True when the text carries pushkin comment litter a splice would remove:
/// any pushkin marker or generated-header line of a prior generation
/// outside block scalars. Doctor keys its litter finding on exactly this
/// predicate (H1), so detection and repair can never disagree about what
/// counts as litter.
pub(crate) fn has_stale_pushkin_comments(text: &str) -> bool {
    without_pushkin_comment_lines(text, true) != text
}

/// A pre-marker (v1) floor carried a bare `pushkin:` command entry with
/// no markers. Drop that entry so the marked block can replace it;
/// `None` when there is nothing of ours to strip.
fn strip_stale_pushkin_command(existing: &str) -> Option<String> {
    if !existing.contains("pushkin") {
        return None;
    }
    let mut kept: Vec<&str> = Vec::new();
    let mut dropped = false;
    let mut skipping = false;
    for line in existing.lines() {
        let trimmed = line.trim();
        if trimmed == "pushkin:" {
            skipping = true;
            dropped = true;
            continue;
        }
        // Continuation lines of that entry are more-indented keys.
        if skipping {
            let indent = line.len() - line.trim_start().len();
            if trimmed.is_empty() || indent > 4 {
                continue;
            }
            skipping = false;
        }
        // The generated-file header comment is ours too.
        if trimmed.starts_with("# GENERATED by pushkin init") {
            dropped = true;
            continue;
        }
        kept.push(line);
    }
    if !dropped {
        return None;
    }
    let mut text = kept.join("\n");
    if !text.ends_with('\n') {
        text.push('\n');
    }
    Some(text)
}

/// Byte offset just after an existing `pre-commit:` → `commands:` line —
/// where our block belongs — paired with the indent the section's entries
/// use, read from the first existing entry (else `commands:` + 2), so the
/// spliced block matches the config's own style instead of assuming the
/// two-space house layout. `None` when the file has no such section.
fn commands_insertion_point(existing: &str) -> Option<(usize, usize)> {
    let mut offset = 0usize;
    let mut in_precommit = false;
    let mut found: Option<(usize, usize)> = None;
    for line in existing.split_inclusive('\n') {
        if let Some((at, commands_indent)) = found {
            // The first structural line after `commands:` fixes the entry
            // indent; a less-indented line means the section is empty.
            let trimmed = line.trim();
            if !trimmed.is_empty() && !trimmed.starts_with('#') {
                let indent = line_indent(line);
                let entry = if indent > commands_indent {
                    indent
                } else {
                    commands_indent + 2
                };
                return Some((at, entry));
            }
            offset += line.len();
            continue;
        }
        let trimmed = line.trim_end();
        if trimmed.starts_with("pre-commit:") {
            in_precommit = true;
        } else if in_precommit && trimmed.trim() == "commands:" {
            found = Some((offset + line.len(), line_indent(line)));
        } else if !line.starts_with(' ')
            && !trimmed.is_empty()
            && !trimmed.starts_with("pre-commit:")
        {
            in_precommit = false;
        }
        offset += line.len();
    }
    found.map(|(at, commands_indent)| (at, commands_indent + 2))
}

/// The canonical block re-based from its own entry indent to the config's,
/// preserving every internal offset. A no-op for the two-space house style,
/// so generated and standard-layout files stay byte-stable.
fn reindent_block(block: &str, entry_indent: usize) -> String {
    const CANONICAL_ENTRY_INDENT: usize = 4;
    if entry_indent == CANONICAL_ENTRY_INDENT {
        return block.to_owned();
    }
    let mut out = String::new();
    for line in block.split_inclusive('\n') {
        let body = line.trim_start_matches(' ');
        let base = line.len() - body.len();
        let shifted = (base + entry_indent).saturating_sub(CANONICAL_ENTRY_INDENT);
        out.push_str(&" ".repeat(shifted));
        out.push_str(body);
    }
    out
}

/// Uninstall: strip our block, and remove the file entirely when nothing
/// but our own scaffolding is left (a purely generated floor).
pub(crate) fn remove_lefthook() -> Result<()> {
    let Ok(existing) = std::fs::read_to_string(LEFTHOOK_FILE) else {
        println!("pushkin: lefthook floor not present; nothing to remove.");
        return Ok(());
    };
    let stripped = match split_around_lefthook_block(&existing) {
        Some((prefix, tail)) => without_pushkin_comment_lines(&format!("{prefix}{tail}"), false),
        None => strip_stale_pushkin_command(&existing).unwrap_or(existing),
    };
    if lefthook_is_only_scaffolding(&stripped) {
        std::fs::remove_file(LEFTHOOK_FILE).context("cannot remove lefthook.yml")?;
        println!("pushkin: lefthook floor removed (file was pushkin's alone).");
        return Ok(());
    }
    std::fs::write(LEFTHOOK_FILE, stripped).context("cannot write lefthook.yml")?;
    println!("pushkin: lefthook floor removed; other commands preserved.");
    Ok(())
}

/// True when what remains carries nothing of the user's own — only the
/// `pre-commit:`/`commands:` scaffolding and PUSHKIN-generated comments
/// from our full file. A comment the user wrote is the user's content, so
/// a file carrying one is never deleted on uninstall (PR #24 exit review,
/// carried observation).
fn lefthook_is_only_scaffolding(text: &str) -> bool {
    text.lines().all(|line| {
        let trimmed = line.trim();
        trimmed.is_empty()
            || trimmed == "pre-commit:"
            || trimmed == "commands:"
            || trimmed.starts_with("# GENERATED by pushkin init")
            || trimmed.starts_with("# pushkin:begin pushkin-v")
            || trimmed.starts_with("# pushkin:end pushkin-v")
    })
}

// ---------- native git shim (distribution stream S2b, D4) ----------

/// The shim as installed into `<git-dir>/hooks/pre-commit`: wholly
/// pushkin-owned (never merged), the generated-file header plus the SAME
/// N13 guard the lefthook floor emits — fail open only on positively
/// probed absence, loud notice, no exit-code case analysis.
fn git_shim_file() -> String {
    format!(
        "#!/bin/sh\n# GENERATED by pushkin init — do not hand-edit. marker: {PUSHKIN_MARKER}\n{}",
        lefthook_guard()
    )
}

/// True when an existing hook file is pushkin's own shim — ownership is
/// the header plus the marker, never a bare mention.
pub(crate) fn is_pushkin_shim(text: &str) -> bool {
    text.contains("GENERATED by pushkin init") && text.contains(PUSHKIN_MARKER)
}

/// Installs the native pre-commit shim (D4, IDEAS.md:11): no lefthook
/// binary in the loop, no baked paths. Detect-don't-clobber: a
/// `core.hooksPath` override or a foreign hook means a manager owns the
/// hooks — name what is recognizable, print the integration snippet,
/// write nothing.
pub fn install_git_shim() -> Result<()> {
    let Some(git_dir) = super::git::git_dir() else {
        anyhow::bail!(
            "not a git repository — the native shim installs into .git/hooks; run \
             inside a repo (or use `--agent lefthook` for a config-file floor)"
        );
    };
    if let Some(hooks_path) = super::git::hooks_path_override() {
        println!(
            "pushkin: hooks are owned by a hook manager (core.hooksPath = \
             {hooks_path}); nothing was written. Add this to that manager's \
             pre-commit stage to gate commits:\n  pushkin check --staged --json"
        );
        return Ok(());
    }
    let hooks_dir = git_dir.join("hooks");
    let target = hooks_dir.join("pre-commit");
    if let Ok(existing) = std::fs::read_to_string(&target) {
        if !is_pushkin_shim(&existing) {
            let manager = if existing.contains("lefthook") {
                " (this looks like lefthook — `pushkin init --agent lefthook` manages \
                 that floor)"
            } else if existing.contains("husky") {
                " (this looks like husky)"
            } else {
                ""
            };
            println!(
                "pushkin: an existing pre-commit hook is not pushkin's and was left \
                 untouched{manager}. Add this to it to gate commits:\n  \
                 pushkin check --staged --json"
            );
            return Ok(());
        }
    }
    std::fs::create_dir_all(&hooks_dir).context("cannot create the hooks directory")?;
    std::fs::write(&target, git_shim_file()).context("cannot write the pre-commit shim")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755))
            .context("cannot mark the shim executable")?;
    }
    println!(
        "pushkin: native git pre-commit shim installed ({}); the hook runs \
         `{LEFTHOOK_COMMAND}` when pushkin is on PATH, and fails open with a \
         notice when it is not.",
        target.display()
    );
    Ok(())
}

/// Uninstall: removes only a pushkin-owned shim; a foreign hook is the
/// user's and is left in place.
pub(crate) fn remove_git_shim() -> Result<()> {
    let Some(git_dir) = super::git::git_dir() else {
        println!("pushkin: not a git repository; no shim to remove.");
        return Ok(());
    };
    let target = git_dir.join("hooks").join("pre-commit");
    match std::fs::read_to_string(&target) {
        Ok(existing) if is_pushkin_shim(&existing) => {
            std::fs::remove_file(&target).context("cannot remove the pre-commit shim")?;
            println!("pushkin: native git shim removed.");
        }
        Ok(_) => println!("pushkin: the pre-commit hook is not pushkin's; left in place."),
        Err(_) => println!("pushkin: native git shim not present; nothing to remove."),
    }
    Ok(())
}

// ---------- uninstall ----------

fn remove(name: &str) -> Result<i32> {
    match name {
        "claude" => {
            let mut settings = read_json_or_empty(CLAUDE_SETTINGS)?;
            strip_marked_entries(&mut settings);
            write_json(CLAUDE_SETTINGS, &settings)?;
            println!("pushkin: claude entries removed; user hooks preserved.");
            Ok(0)
        }
        "codex" => {
            let _ = std::fs::remove_file(".codex/rules/pushkin.rules");
            let _ = std::fs::remove_file(legacy::CODEX_RULES);
            let mut settings = read_json_or_empty(".codex/hooks.json")?;
            strip_marked_entries(&mut settings);
            write_json(".codex/hooks.json", &settings)?;
            println!("pushkin: codex entries removed.");
            Ok(0)
        }
        "auggie" => {
            let _ = std::fs::remove_file(".augment/hooks/pushkin.sh");
            let _ = std::fs::remove_file(legacy::AUGGIE_SCRIPT);
            let mut settings = read_json_or_empty(".augment/settings.json")?;
            strip_marked_entries(&mut settings);
            write_json(".augment/settings.json", &settings)?;
            println!("pushkin: auggie entries removed.");
            Ok(0)
        }
        "hermes" => {
            let _ = std::fs::remove_file(".hermes/hooks/pushkin.json");
            let _ = std::fs::remove_file(legacy::HERMES_HOOK);
            println!("pushkin: hermes hook removed.");
            Ok(0)
        }
        "opencode" => {
            let _ = std::fs::remove_file(".opencode/plugin/pushkin.ts");
            let _ = std::fs::remove_file(legacy::OPENCODE_PLUGIN);
            println!(
                "pushkin: opencode plugin removed (permission block left; it is user policy)."
            );
            Ok(0)
        }
        "lefthook" => {
            remove_lefthook()?;
            Ok(0)
        }
        "git" => {
            remove_git_shim()?;
            Ok(0)
        }
        "agents-md" => {
            match std::fs::read_to_string(AGENTS_MD) {
                Err(_) => println!("pushkin: AGENTS.md not present; nothing to remove."),
                Ok(existing) => {
                    std::fs::write(AGENTS_MD, strip_managed_block(&existing))
                        .context("cannot write AGENTS.md")?;
                    println!("pushkin: AGENTS.md managed block removed; user content preserved.");
                }
            }
            Ok(0)
        }
        unknown => match Agent::parse(unknown) {
            Ok(_) => unreachable!("all agents handled above"),
            Err(error) => bail!("{error}"),
        },
    }
}

// ---------- shared JSON helpers ----------

/// Drops OUR hook entries from every event list — both marker
/// generations (`_pushkin`, and the pre-rename `legacy::MARKER_KEY`), any value.
/// User-owned entries carry neither key and are preserved.
fn strip_marked_entries(settings: &mut Value) {
    if let Some(hooks) = settings.get_mut("hooks").and_then(Value::as_object_mut) {
        for (_, entries) in hooks.iter_mut() {
            if let Some(list) = entries.as_array_mut() {
                list.retain(|entry| {
                    entry.get("_pushkin").is_none() && entry.get(legacy::MARKER_KEY).is_none()
                });
            }
        }
    }
}

pub fn read_json_or_empty(path: &str) -> Result<Value> {
    match std::fs::read_to_string(path) {
        Err(_) => Ok(json!({})),
        Ok(text) => serde_json::from_str(&text)
            .with_context(|| format!("{path} exists but is not valid JSON")),
    }
}

pub fn write_json(path: &str, value: &Value) -> Result<()> {
    if let Some(parent) = std::path::Path::new(path).parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("cannot create {}", parent.display()))?;
        }
    }
    let mut rendered = serde_json::to_string_pretty(value)?;
    rendered.push('\n');
    std::fs::write(path, rendered).with_context(|| format!("cannot write {path}"))
}

pub fn ensure_object_entry<'a>(root: &'a mut Value, key: &str) -> Result<&'a mut Value> {
    Ok(root
        .as_object_mut()
        .context("config root must be a JSON object")?
        .entry(key)
        .or_insert_with(|| json!({})))
}

/// Replaces any prior pushkin-marked entry (idempotence) and appends ours,
/// preserving user-owned entries. Any `_pushkin` key — or the pre-rename
/// `legacy::MARKER_KEY` — marks the entry as ours regardless of version,
/// so reinstall/repair migrates legacy-marker entries instead of stacking
/// a duplicate beside them (remediation pass 3, B2).
pub fn set_marked_entry(hooks: &mut Value, event: &str, entry: Value) -> Result<()> {
    let list = hooks
        .as_object_mut()
        .context("hooks must be a JSON object")?
        .entry(event)
        .or_insert_with(|| json!([]));
    let entries = list
        .as_array_mut()
        .context("hook event must hold an array")?;
    entries.retain(|candidate| {
        candidate.get("_pushkin").is_none() && candidate.get(legacy::MARKER_KEY).is_none()
    });
    entries.push(entry);
    Ok(())
}