pushkin 0.1.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
//! `pushkin doctor [--repair]`: verifies hook installs across agent
//! configs; `--repair` reinstalls missing/stale pushkin entries in place.
//! Refuses destructive repair on unreadable state — corrupt config is a red
//! finding for the human, never a mass-delete (addendum §3.6).
//!
//! Detection is presence-keyed (task 5): a pack is checked only when its
//! on-disk footprint exists; an absent pack is named loudly as "not
//! installed — not checked" (§13), never silently skipped. Repair stays
//! Claude-only in Phase 2 and says so per agent; the manual remedy is that
//! agent's `pushkin init --agent <agent>`.

use anyhow::{Context as _, Result};
use pushkin_core::waivers::WaiverSet;
use serde_json::Value;

use crate::agents::Agent;

use super::init::install_claude;
use super::{CLAUDE_SETTINGS, PUSHKIN_MARKER};

pub fn run_with_repair(repair: bool) -> Result<i32> {
    if repair {
        // One-time pre-rename footprint rename (remediation pass 3, B2)
        // before any check runs against the new paths.
        super::init::migrate_legacy_footprint()?;
    }
    println!("pushkin doctor: {}", super::daemon::health_line());
    for finding in waiver_lint_findings() {
        println!("pushkin doctor: {finding}");
    }
    let reports = collect_reports(host_os());
    let floor = check_lefthook();
    let shim = check_git_shim();
    let resolvability = check_adapter_resolvability(&reports);
    for (_, check) in &reports {
        if let Some(info) = &check.info {
            println!("pushkin doctor: {info}");
        }
    }
    if let Some(info) = &floor.info {
        println!("pushkin doctor: {info}");
    }
    if let Some(info) = &shim.info {
        println!("pushkin doctor: {info}");
    }
    let healthy = reports.iter().all(|(_, check)| check.findings.is_empty())
        && floor.findings.is_empty()
        && shim.findings.is_empty()
        && resolvability.findings.is_empty();
    if healthy {
        println!("pushkin doctor: hooks healthy.");
        return Ok(0);
    }
    for (_, check) in &reports {
        for finding in &check.findings {
            println!("pushkin doctor: {finding}");
        }
    }
    for finding in &floor.findings {
        println!("pushkin doctor: {finding}");
    }
    for finding in &shim.findings {
        println!("pushkin doctor: {finding}");
    }
    for finding in &resolvability.findings {
        println!("pushkin doctor: {finding}");
    }
    if !repair {
        println!("pushkin doctor: run `pushkin doctor --repair` to fix.");
        return Ok(1);
    }
    if reports.iter().any(|(_, check)| check.unreadable) || floor.unreadable || shim.unreadable {
        println!(
            "pushkin doctor: refusing to repair unreadable state — fix or delete \
             the file named above yourself, then re-run. Nothing was modified."
        );
        return Ok(1);
    }
    repair_floor(&floor)?;
    repair_git_shim(&shim)?;
    repair_reports(&reports)
}

/// The native git shim (S2b): presence-keyed like every pack — absent,
/// non-repo, or foreign is never a finding. A pushkin-owned shim that
/// lost its executable bit is dead (git silently skips it): a red,
/// repairable finding. An unresolvable `pushkin` is the same advisory
/// the lefthook floor carries.
fn check_git_shim() -> AgentCheck {
    let mut check = AgentCheck::default();
    let Some(git_dir) = super::git::git_dir() else {
        check.info = Some("git shim: not a git repository — not checked".to_owned());
        return check;
    };
    let target = git_dir.join("hooks").join("pre-commit");
    let text = match std::fs::read_to_string(&target) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            check.info = Some("git shim: not installed — not checked".to_owned());
            return check;
        }
        Err(error) => {
            check.unreadable = true;
            check.findings.push(format!(
                "git shim: cannot read {}: {error}",
                target.display()
            ));
            return check;
        }
        Ok(text) => text,
    };
    if !super::init::is_pushkin_shim(&text) {
        check.info = Some("git shim: present but not pushkin's — not checked".to_owned());
        return check;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = std::fs::metadata(&target) {
            if meta.permissions().mode() & 0o111 == 0 {
                check.findings.push(
                    "git shim: the pre-commit hook is not executable, so git never runs \
                     it; repair rewrites the shim with the executable bit restored"
                        .to_owned(),
                );
            }
        }
    }
    if !pushkin_on_path() {
        check.findings.push(
            "git shim: the hook runs `pushkin` from PATH but no `pushkin` is resolvable \
             there — the pre-commit gate will fail open until the binary is installed \
             (`cargo install --path crates/pushkin-cli`)"
                .to_owned(),
        );
        check.path_advisory = true;
    }
    check
}

/// Repair regenerates only a pushkin-owned shim (install re-checks
/// ownership before writing), and mirrors `repair_floor`'s rule: an
/// advisory-only finding list rewrites nothing.
fn repair_git_shim(shim: &AgentCheck) -> Result<()> {
    let repairable = shim.findings.len() > usize::from(shim.path_advisory);
    if !repairable {
        return Ok(());
    }
    super::init::install_git_shim()?;
    println!("pushkin doctor: repaired — native git shim regenerated.");
    Ok(())
}

/// Regenerating the floor goes through the same merge path `init` uses, so
/// repair can never clobber a config that carries other teams' commands.
/// A missing `pushkin` on PATH is advisory: nothing about the file is
/// wrong and no rewrite installs a binary, so when it is the ONLY finding
/// the file is left untouched and no "regenerated" claim is printed (M2) —
/// the message names the human's actual remedy instead.
fn repair_floor(floor: &AgentCheck) -> Result<()> {
    let repairable = floor.findings.len() > usize::from(floor.path_advisory);
    if !repairable {
        if floor.path_advisory {
            println!(
                "pushkin doctor: the lefthook floor file is current; the PATH \
                 finding is advisory — install pushkin (`cargo install --path \
                 crates/pushkin-cli`). Nothing was rewritten."
            );
        }
        return Ok(());
    }
    let path = std::path::Path::new(super::init::LEFTHOOK_FILE);
    if !path.exists() {
        return Ok(());
    }
    let text = std::fs::read_to_string(path).context("cannot read lefthook.yml")?;
    if floor_generation(&text, super::init::LEFTHOOK_MARKER).is_some() {
        super::init::install_lefthook()?;
        println!("pushkin doctor: repaired — lefthook floor regenerated.");
    } else {
        // Not our floor: the only repairable finding on such a file is
        // comment litter. Scrub it and stop — installing a floor here
        // would re-install an uninstall (S1b; the M1 bite's last shape).
        let scrubbed = super::init::without_pushkin_comment_lines(&text, true);
        std::fs::write(path, scrubbed).context("cannot write lefthook.yml")?;
        println!(
            "pushkin doctor: repaired — orphaned pushkin marker comments removed; \
             the file carries no pushkin block, so nothing was installed."
        );
    }
    Ok(())
}

/// A3(b): adapter packs are installed but `pushkin` is not resolvable via
/// the A0 scheme, so every emitted hook command would fail to launch and
/// writes would go ungated. Presence-keyed (§13): with no pack installed
/// there is nothing to resolve, so this is silent. Advisory like the floor's
/// equivalent — repair cannot install a binary for the human.
fn check_adapter_resolvability(reports: &[(Agent, AgentCheck)]) -> AgentCheck {
    let mut check = AgentCheck::default();
    let any_installed = reports.iter().any(|(_, report)| report.info.is_none());
    if any_installed && !pushkin_on_path() {
        check.findings.push(unresolvable_binary_finding());
    }
    check
}

/// The findings-only sweep the daemon repeats at startup (spec §6):
/// every agent's findings flattened, no exit-code semantics, no repair.
#[must_use]
pub fn sweep_findings() -> Vec<String> {
    let reports = collect_reports(host_os());
    let resolvability = check_adapter_resolvability(&reports);
    reports
        .into_iter()
        .flat_map(|(_, check)| check.findings)
        .chain(check_lefthook().findings)
        .chain(check_git_shim().findings)
        .chain(resolvability.findings)
        .collect()
}

/// Waiver decision-log lint (spec §15 Phase 5: stale-entry lint;
/// supersedes/contradicts semantics). Advisory findings, never repaired —
/// pruning the human-plane record is the human's call. A malformed file is
/// itself a finding: the gate is failing closed on it right now.
fn waiver_lint_findings() -> Vec<String> {
    match WaiverSet::load(std::path::Path::new(super::waive::WAIVERS_FILE)) {
        Ok(set) => set.lint_now(),
        Err(error) => vec![format!(
            "waivers file rejected ({error}) — no waivers are being honored \
             until it parses"
        )],
    }
}

/// One agent's verdict. Errors reading a present pack become findings
/// (fail-loud), never a silent downgrade to "not installed".
#[derive(Default)]
struct AgentCheck {
    findings: Vec<String>,
    info: Option<String>,
    unreadable: bool,
    /// Set when `findings` includes the floor's PATH-resolvability advisory
    /// — a finding no file rewrite can fix. Repair stays hands-off when it
    /// is the only one (M2); reporting and exit codes are unchanged.
    path_advisory: bool,
}

fn collect_reports(os: HostOs) -> Vec<(Agent, AgentCheck)> {
    Agent::ALL
        .into_iter()
        .map(|agent| {
            let check = match agent {
                Agent::Claude => check_claude(),
                Agent::Codex => check_codex(os),
                Agent::Auggie => check_auggie(),
                Agent::Hermes => check_hermes(),
                Agent::Opencode => check_opencode(),
            };
            (agent, check)
        })
        .collect()
}

/// Repairs what has a Phase-2 repair path and defers the rest. Deferrals
/// are ADVISORY (D2, ratified 2026-08-15; resolves IDEAS.md:20): the
/// message names the manual remedy and the exit code stays 0 — a
/// successful repair must never exit 1 because a deferral printed beside
/// it. Exit 1 is reserved for the unreadable-state refusal (handled before
/// repair runs) and for real failures (error propagation from the repair
/// itself).
fn repair_reports(reports: &[(Agent, AgentCheck)]) -> Result<i32> {
    for (agent, check) in reports {
        if check.findings.is_empty() {
            continue;
        }
        match agent {
            Agent::Claude => {
                install_claude()?;
                println!("pushkin doctor: repaired — pushkin entries reinstalled.");
            }
            Agent::Codex | Agent::Auggie | Agent::Hermes | Agent::Opencode => {
                println!(
                    "pushkin doctor: repair not implemented for {name} in Phase 2 — \
                     rerun `pushkin init --agent {name}`.",
                    name = agent.as_str()
                );
            }
        }
    }
    Ok(0)
}

// ---------- host OS (one boundary parse; addendum §3.2 Windows caveat) ----------

/// Only Windows changes a finding today, so only Windows earns a variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HostOs {
    Windows,
    Other,
}

impl HostOs {
    /// Domain is `std::env::consts::OS` values — lowercase, e.g. "windows".
    fn parse(name: &str) -> Self {
        match name {
            "windows" => HostOs::Windows,
            _ => HostOs::Other,
        }
    }
}

/// `PUSHKIN_DOCTOR_OS` overrides for tests (this host cannot execute the
/// real Windows branch); production reads `std::env::consts::OS`.
fn host_os() -> HostOs {
    let name =
        std::env::var("PUSHKIN_DOCTOR_OS").unwrap_or_else(|_| std::env::consts::OS.to_owned());
    HostOs::parse(&name)
}

// ---------- claude (primary pack; behavior pinned by tests/install_doctor.rs) ----------

fn check_claude() -> AgentCheck {
    let mut check = AgentCheck::default();
    match std::fs::read_to_string(CLAUDE_SETTINGS) {
        Err(_) => check
            .findings
            .push(format!("{CLAUDE_SETTINGS} missing — no hook installed")),
        Ok(text) => match serde_json::from_str::<Value>(&text) {
            Err(error) => {
                check.unreadable = true;
                check
                    .findings
                    .push(format!("{CLAUDE_SETTINGS} is not valid JSON: {error}"));
            }
            Ok(settings) => {
                for event in ["PreToolUse", "Stop"] {
                    match pushkin_entry(&settings, event) {
                        None => check
                            .findings
                            .push(claude_missing_finding(&settings, event)),
                        Some(entry) => {
                            if !command_is_current(entry) {
                                let detail = if entry_has_absolute_command(entry) {
                                    " — it embeds an absolute binary path, which goes \
                                     stale when the binary moves"
                                } else {
                                    ""
                                };
                                check.findings.push(format!(
                                    "{event} hook command is stale (does not invoke \
                                     `hook claude` via the portable `pushkin` command){detail}"
                                ));
                            }
                        }
                    }
                }
            }
        },
    }
    check
}

fn claude_missing_finding(settings: &Value, event: &str) -> String {
    if legacy_entry(settings, event).is_some() {
        format!(
            "{event} hook entry carries a legacy pushkin marker — \
             repair migrates it to {PUSHKIN_MARKER}"
        )
    } else {
        format!("{event} hook entry missing or not pushkin's")
    }
}

// ---------- codex (hooks.json + execpolicy floor; addendum §3.2) ----------

fn check_codex(os: HostOs) -> AgentCheck {
    let mut check = AgentCheck::default();
    let rules_path = ".codex/rules/pushkin.rules";
    let rules_present = std::path::Path::new(rules_path).exists();
    let entry = marked_entry_state(".codex/hooks.json", "hook codex");
    if !rules_present && matches!(entry, EntryState::FileAbsent | EntryState::Missing) {
        check.info = Some("codex: not installed — not checked".to_owned());
        return check;
    }
    match entry {
        EntryState::Unreadable(finding) => {
            check.unreadable = true;
            check.findings.push(finding);
        }
        EntryState::FileAbsent | EntryState::Missing => check.findings.push(
            "codex: PreToolUse hook entry missing or not pushkin's (.codex/hooks.json)".to_owned(),
        ),
        EntryState::Stale => check.findings.push(
            "codex: PreToolUse hook command is stale (does not invoke `hook codex` \
             on this binary)"
                .to_owned(),
        ),
        EntryState::Current => {}
    }
    if !rules_present {
        check.findings.push(format!(
            "codex: {rules_path} missing — execpolicy floor absent"
        ));
    }
    if os == HostOs::Windows {
        check.findings.push(
            "codex: hooks are unavailable on Windows (openai/codex#17478) — the \
             execpolicy rules floor still applies; the PreToolUse gate will not fire"
                .to_owned(),
        );
    }
    check
}

// ---------- auggie (settings entry + wrapper script; addendum §3.4) ----------

fn check_auggie() -> AgentCheck {
    let mut check = AgentCheck::default();
    let script_path = ".augment/hooks/pushkin.sh";
    let script_present = std::path::Path::new(script_path).exists();
    let entry = marked_entry_state(".augment/settings.json", "pushkin.sh");
    if !script_present && matches!(entry, EntryState::FileAbsent | EntryState::Missing) {
        check.info = Some("auggie: not installed — not checked".to_owned());
        return check;
    }
    match entry {
        EntryState::Unreadable(finding) => {
            check.unreadable = true;
            check.findings.push(finding);
        }
        EntryState::FileAbsent | EntryState::Missing => check.findings.push(
            "auggie: PreToolUse hook entry missing or not pushkin's (.augment/settings.json)"
                .to_owned(),
        ),
        EntryState::Stale => check
            .findings
            .push("auggie: hook command does not invoke the pushkin.sh wrapper — stale".to_owned()),
        EntryState::Current => {}
    }
    if !script_present {
        check.findings.push(format!(
            "auggie: {script_path} missing — hook script absent"
        ));
    } else if let Ok(script) = std::fs::read_to_string(script_path) {
        // A1: the wrapper body is where auggie's portability lives — the
        // settings entry legitimately carries the absolute script path.
        if script.lines().any(|line| {
            line.starts_with("exec ") && command_has_absolute_path(&line["exec ".len()..])
        }) {
            check.findings.push(format!(
                "auggie: {script_path} is stale — it execs an absolute binary \
                 path, which breaks when the binary moves; repair regenerates it"
            ));
        }
    }
    check
}

// ---------- hermes (per-user plugin dir; advisory tier; addendum §3.5) ----------

fn check_hermes() -> AgentCheck {
    let mut check = AgentCheck::default();
    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");
    if !std::path::Path::new(&plugin_dir).exists() {
        check.info = Some("hermes: not installed — not checked".to_owned());
        return check;
    }
    for file in ["plugin.yaml", "__init__.py"] {
        if !std::path::Path::new(&format!("{plugin_dir}/{file}")).exists() {
            check
                .findings
                .push(format!("hermes: {file} missing from {plugin_dir}"));
        }
    }
    check
}

// ---------- opencode (singular plugin dir, live-verified on 1.18.18) ----------

fn check_opencode() -> AgentCheck {
    let mut check = AgentCheck::default();
    // The shipped layout is `.opencode/plugin/` (singular) — current docs lead
    // with the plural dir, but the check must match what init actually writes
    // (commit 8b699db), or it would red-flag our own healthy install.
    let path = ".opencode/plugin/pushkin.ts";
    match std::fs::read_to_string(path) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            check.info = Some("opencode: not installed — not checked".to_owned());
        }
        Err(error) => {
            check.unreadable = true;
            check
                .findings
                .push(format!("opencode: cannot read {path}: {error}"));
        }
        Ok(text) => {
            if !text.contains(PUSHKIN_MARKER) || !text.contains("hook opencode") {
                check.findings.push(format!(
                    "opencode: {path} is not pushkin's current plugin (marker or \
                     hook relay missing) — hand-edited or stale"
                ));
            }
        }
    }
    check
}

// ---------- lefthook floor (remediation: L4) ----------

/// Which generation of pushkin's floor a config carries. Ownership is decided
/// by the versioned marker alone — never by a bare "pushkin" substring, which
/// would claim a config someone else wrote that merely mentions the tool.
#[derive(Clone, Copy)]
enum FloorGeneration {
    /// Unmarked, but carrying pushkin's own pre-marker command shape.
    V1,
    /// Marked v2: clean PATH-resolved command, but no fail-open guard.
    V2,
    /// Marked current.
    Current,
}

impl FloorGeneration {
    /// The truthful diagnosis for this generation. v1 and v2 are stale for
    /// entirely different reasons, and saying so is the point (F-F(b)). Both
    /// messages keep the word "stale" — the committed suite pins it, and it is
    /// the word that tells a reader the config needs regenerating.
    fn stale_finding(self, file: &str) -> Option<String> {
        match self {
            Self::V1 => Some(format!(
                "lefthook: {file} carries a stale v1 pushkin floor (an absolute binary path \
                 and/or a whole-repo Stop sweep); repair regenerates it and preserves \
                 other commands"
            )),
            Self::V2 => Some(format!(
                "lefthook: {file} carries a stale v2 pushkin floor — the command is clean, \
                 but it has no fail-open guard, so it blocks teammates who have not \
                 installed pushkin; repair regenerates it and preserves other commands"
            )),
            Self::Current => None,
        }
    }
}

/// Identifies pushkin's floor in a config, or `None` when the config is not
/// ours. Keyed on the marker for v2+; v1 predates markers, so it is recognized
/// by the command shape it uniquely emitted (a `pushkin` command under a
/// `pushkin:` key), never by the word appearing anywhere in the file.
fn floor_generation(text: &str, marker: &str) -> Option<FloorGeneration> {
    if text.contains(marker) {
        return Some(FloorGeneration::Current);
    }
    // A generation marker alone is not a floor: an EMPTY orphaned pair —
    // the pre-fix binary's upgrade-then-remove residue — must read as
    // litter, never as a v2 floor repair would re-install (S1b).
    if (text.contains("pushkin:begin pushkin-v2") || text.contains("marker: pushkin-v2"))
        && has_pushkin_entry(text)
    {
        return Some(FloorGeneration::V2);
    }
    // v1: unmarked. Ours only if a `pushkin:` command entry actually runs a
    // pushkin command — a comment mentioning pushkin is not ownership.
    has_pushkin_entry(text).then_some(FloorGeneration::V1)
}

/// A real `pushkin:` command entry: the key line plus a more-indented
/// `run:` that invokes pushkin. Marker comments alone are not an entry.
fn has_pushkin_entry(text: &str) -> bool {
    let mut lines = text.lines().skip_while(|line| line.trim() != "pushkin:");
    if lines.next().is_none() {
        return false;
    }
    lines
        .take_while(|line| line.starts_with(' ') || line.trim().is_empty())
        .any(|line| {
            let trimmed = line.trim();
            trimmed.starts_with("run:") && trimmed.contains("pushkin")
        })
}

/// The pre-commit floor is agent-agnostic, so it is checked outside the
/// per-agent sweep. Presence-keyed like every other pack: no file, no
/// findings. Two red cases — a floor from an older generation, diagnosed
/// truthfully per version, and a floor whose PATH-resolved `pushkin` cannot
/// actually be resolved, which would make the hook silently never fire.
fn check_lefthook() -> AgentCheck {
    use super::init::{LEFTHOOK_FILE, LEFTHOOK_MARKER};

    let mut check = AgentCheck::default();
    let text = match std::fs::read_to_string(LEFTHOOK_FILE) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            check.info = Some("lefthook: not installed — not checked".to_owned());
            return check;
        }
        Err(error) => {
            check.unreadable = true;
            check
                .findings
                .push(format!("lefthook: cannot read {LEFTHOOK_FILE}: {error}"));
            return check;
        }
        Ok(text) => text,
    };
    let Some(generation) = floor_generation(&text, LEFTHOOK_MARKER) else {
        // Someone else's lefthook config; our floor is simply not installed.
        // Our comment litter may still be present (a pre-fix uninstall left
        // the orphaned pair behind) — that is ours to name and to scrub,
        // and NOTHING more: repair on a file that is not ours never
        // installs a floor (S1b).
        check.info = Some("lefthook: present but no pushkin block — not checked".to_owned());
        if super::init::has_stale_pushkin_comments(&text) {
            check.findings.push(format!(
                "lefthook: {LEFTHOOK_FILE} carries orphaned pushkin marker comments but \
                 no pushkin block; repair removes the orphans, preserves other \
                 commands, and installs nothing"
            ));
        }
        return check;
    };
    if let Some(finding) = generation.stale_finding(LEFTHOOK_FILE) {
        check.findings.push(finding);
    } else if super::init::has_stale_pushkin_comments(&text) {
        // A Current floor bitten by the pre-fix upgrade path (PR #24 exit
        // review, R1): the block is fine, but a prior generation's marker
        // or header comments survive outside it. Repairable — the splice
        // scrubs exactly this litter, so the finding and the fix share one
        // predicate. A stale floor skips this arm: its regeneration
        // already scrubs.
        check.findings.push(format!(
            "lefthook: {LEFTHOOK_FILE} carries orphaned pushkin marker comments outside \
             the current block (litter from an upgrade by a pre-fix binary); repair \
             removes them and preserves other commands"
        ));
    }
    if !pushkin_on_path() {
        check.findings.push(
            "lefthook: the floor runs `pushkin` from PATH but no `pushkin` is resolvable \
             there — the pre-commit gate will fail to launch. Install it on PATH \
             (`cargo install --path crates/pushkin-cli`) or add the binary's directory \
             to PATH"
                .to_owned(),
        );
        check.path_advisory = true;
    }
    check
}

/// Whether a `pushkin` executable is resolvable on PATH. Deliberately not
/// `current_exe()`: the question is what a shell in a git hook would find.
fn pushkin_on_path() -> bool {
    let Ok(path) = std::env::var("PATH") else {
        return false;
    };
    std::env::split_paths(&path).any(|dir| {
        let candidate = dir.join("pushkin");
        candidate.is_file() || candidate.with_extension("exe").is_file()
    })
}

/// A generated hook command that embeds an absolute binary path is the
/// pre-A1 form: it goes stale as soon as the binary moves or another clone
/// runs init (field evidence: d75765f). The A0 scheme is the bare
/// PATH-resolved `pushkin hook <agent>`.
///
/// SCOPED EXCEPTION: auggie's settings entry must point at an absolute
/// *script* path — auggie only executes hook commands that are scripts with
/// a supported extension, so that path is load-bearing, not stale. Only an
/// absolute path to the BINARY is the defect, and the wrapper script's own
/// body is checked separately.
fn command_has_absolute_path(command: &str) -> bool {
    let absolute = command.starts_with('/') || command.starts_with('\\') || command.contains(":\\");
    absolute && !command.contains("pushkin.sh")
}

/// The A3(b) finding, shared by every adapter: hooks are installed but the
/// command they run cannot be resolved, so the gate silently never fires.
fn unresolvable_binary_finding() -> String {
    "adapter hooks are installed but no `pushkin` is resolvable on PATH — \
     the gate will fail to launch and writes will go ungated. Install it on \
     PATH (`cargo install --path crates/pushkin-cli`) or add the binary's \
     directory to PATH"
        .to_owned()
}

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

enum EntryState {
    FileAbsent,
    Unreadable(String),
    Missing,
    Stale,
    Current,
}

/// State of the pushkin-marked `PreToolUse` entry in an agent's hook config.
/// A read failure on a present file is `Unreadable` — never `FileAbsent` —
/// so a broken pack can't masquerade as an uninstalled one.
fn marked_entry_state(path: &str, needle: &str) -> EntryState {
    match std::fs::read_to_string(path) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => EntryState::FileAbsent,
        Err(error) => EntryState::Unreadable(format!("cannot read {path}: {error}")),
        Ok(text) => match serde_json::from_str::<Value>(&text) {
            Err(error) => EntryState::Unreadable(format!("{path} is not valid JSON: {error}")),
            Ok(settings) => match pushkin_entry(&settings, "PreToolUse") {
                None => EntryState::Missing,
                Some(entry) if entry_has_absolute_command(entry) => EntryState::Stale,
                Some(entry) if entry_invokes(entry, needle) => EntryState::Current,
                Some(_) => EntryState::Stale,
            },
        },
    }
}

fn pushkin_entry<'a>(settings: &'a Value, event: &str) -> Option<&'a Value> {
    settings
        .get("hooks")
        .and_then(|hooks| hooks.get(event))
        .and_then(Value::as_array)
        .and_then(|entries| {
            entries
                .iter()
                .find(|entry| entry.get("_pushkin").and_then(Value::as_str) == Some(PUSHKIN_MARKER))
        })
}

/// An entry marked with a `_pushkin` key whose value is not the current
/// marker: ours, but written by an older install — repair migrates it.
fn legacy_entry<'a>(settings: &'a Value, event: &str) -> Option<&'a Value> {
    settings
        .get("hooks")
        .and_then(|hooks| hooks.get(event))
        .and_then(Value::as_array)
        .and_then(|entries| entries.iter().find(|entry| marker_is_legacy(entry)))
}

fn marker_is_legacy(entry: &Value) -> bool {
    entry
        .get("_pushkin")
        .is_some_and(|marker| marker.as_str() != Some(PUSHKIN_MARKER))
        || entry.get(pushkin_core::legacy::MARKER_KEY).is_some()
}

/// A current command invokes the `hook claude` verb via the portable A0
/// scheme; anything else (old `check`-based strings, foreign paths with
/// legacy flags, or a pre-A1 absolute binary path) is stale and gets
/// migrated in place by repair.
fn command_is_current(entry: &Value) -> bool {
    entry_invokes(entry, "hook claude") && !entry_has_absolute_command(entry)
}

/// Whether any command in the entry embeds an absolute binary path (A3(a)).
fn entry_has_absolute_command(entry: &Value) -> bool {
    entry
        .get("hooks")
        .and_then(Value::as_array)
        .is_some_and(|hooks| {
            hooks.iter().any(|hook| {
                hook.get("command")
                    .and_then(Value::as_str)
                    .is_some_and(command_has_absolute_path)
            })
        })
}

fn entry_invokes(entry: &Value, needle: &str) -> bool {
    entry
        .get("hooks")
        .and_then(Value::as_array)
        .is_some_and(|hooks| {
            hooks.iter().all(|hook| {
                hook.get("command")
                    .and_then(Value::as_str)
                    .is_some_and(|command| command.contains(needle))
            })
        })
}

#[cfg(test)]
mod tests {
    use super::{marker_is_legacy, HostOs};
    use serde_json::json;

    #[test]
    fn host_os_parses_the_consts_os_domain() {
        assert_eq!(HostOs::parse("windows"), HostOs::Windows);
        assert_eq!(HostOs::parse("macos"), HostOs::Other);
        assert_eq!(HostOs::parse("linux"), HostOs::Other);
        // consts::OS is lowercase; anything else is outside the domain.
        assert_eq!(HostOs::parse("Windows"), HostOs::Other);
    }

    #[test]
    fn marker_is_legacy_only_for_foreign_pushkin_versions() {
        assert!(marker_is_legacy(&json!({ "_pushkin": "pushkin-v0" })));
        assert!(!marker_is_legacy(&json!({ "_pushkin": "pushkin-v1" })));
        assert!(!marker_is_legacy(&json!({ "matcher": "Bash" })));
    }
}