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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
//! `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());
    // The [features] git-plane switch: while the human has git hooks off,
    // the floor and shim are not health surfaces — absent is the intended
    // state, and still-installed is the finding (a disabled plane that
    // keeps gating commits is the half-state `disable` exists to prevent).
    // Positive probe only: an absent or rejected manifest never flips
    // doctor's behavior — the gates' own surfaces are loud about that.
    let git_plane_disabled = super::features::git_hooks_disabled().unwrap_or(false);
    let (floor, shim) = if git_plane_disabled {
        (check_lefthook_disabled(), check_git_shim_disabled())
    } else {
        (check_lefthook(), check_git_shim())
    };
    let resolvability = check_adapter_resolvability(&reports);
    // F71 phase A. Non-aborting: a rejected manifest is a finding here, never an
    // early return — doctor is the one surface that must keep working when the
    // parse fails, because it is the surface that reports the failure.
    //
    // Deliberately NOT added to `sweep_findings` (the daemon's startup sweep):
    // that is a different surface with no acceptance case in this charter, and
    // widening to it silently would ship untested behaviour. Noted for a
    // follow-up rather than taken here.
    let manifest_skew = check_manifest_skew();
    // F73 phase 1 — detection only; resolution is unchanged by this probe.
    let nested_manifests = check_nested_manifests();
    // F73 — resolution unpinned because git could not be run.
    let resolution = check_manifest_resolution();
    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}");
    }
    if let Some(info) = &manifest_skew.info {
        println!("pushkin doctor: {info}");
    }
    if let Some(info) = &resolution.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()
        && manifest_skew.findings.is_empty()
        && nested_manifests.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}");
    }
    for finding in &manifest_skew.findings {
        println!("pushkin doctor: {finding}");
    }
    for finding in &nested_manifests.findings {
        println!("pushkin doctor: {finding}");
    }
    if !repair {
        println!("pushkin doctor: run `pushkin doctor --repair` to fix.");
        return Ok(1);
    }
    // Reinstalling a binary is not something pushkin owns, and repairing hook
    // configs with a binary that cannot read the manifest is the skew condition
    // itself. Decline loudly rather than act — the same posture as the
    // unreadable-state refusal immediately below.
    if !manifest_skew.findings.is_empty() {
        println!(
            "pushkin doctor: not repairing — resolve the manifest schema skew above first \
             (cargo install --path crates/pushkin-cli). Nothing was modified."
        );
        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);
    }
    if git_plane_disabled {
        repair_git_plane_disabled(&floor, &shim)?;
    } else {
        repair_floor(&floor)?;
        repair_git_shim(&shim)?;
    }
    repair_reports(&reports)
}

/// The floor while `[features] git_hooks = false`: not checked for
/// health, but a still-installed pushkin block is named — disable means
/// off, never half-installed.
fn check_lefthook_disabled() -> AgentCheck {
    let mut check = AgentCheck {
        info: Some(
            "lefthook: git hooks disabled ([features] git_hooks = false) — not checked".to_owned(),
        ),
        ..AgentCheck::default()
    };
    if let Ok(text) = std::fs::read_to_string(super::init::LEFTHOOK_FILE) {
        if floor_generation(&text, super::init::LEFTHOOK_MARKER).is_some() {
            check.findings.push(format!(
                "lefthook: git hooks are disabled but the pushkin floor block is still \
                 installed in {}; repair removes it (as `pushkin disable git-hooks` \
                 would have)",
                super::init::LEFTHOOK_FILE
            ));
        }
    }
    check
}

/// The native shim under the same switch, same rule as the floor.
fn check_git_shim_disabled() -> AgentCheck {
    let mut check = AgentCheck {
        info: Some(
            "git shim: git hooks disabled ([features] git_hooks = false) — not checked".to_owned(),
        ),
        ..AgentCheck::default()
    };
    let Some(git_dir) = super::git::git_dir() else {
        return check;
    };
    let target = git_dir.join("hooks").join("pre-commit");
    if let Ok(text) = std::fs::read_to_string(&target) {
        if super::init::is_pushkin_shim(&text) {
            check.findings.push(
                "git shim: git hooks are disabled but pushkin's pre-commit shim is still \
                 installed; repair removes it (as `pushkin disable git-hooks` would have)"
                    .to_owned(),
            );
        }
    }
    check
}

/// Repair under the switch removes rather than regenerates: the only
/// findings the disabled-state checks emit are still-installed pushkin
/// surfaces, and the removal paths are the same ownership-checked ones
/// uninstall uses — a foreign floor or hook is never touched.
fn repair_git_plane_disabled(floor: &AgentCheck, shim: &AgentCheck) -> Result<()> {
    if !floor.findings.is_empty() {
        super::init::remove_lefthook()?;
        println!("pushkin doctor: repaired — lefthook floor removed (git hooks disabled).");
    }
    if !shim.findings.is_empty() {
        super::init::remove_git_shim()?;
        println!("pushkin doctor: repaired — native git shim removed (git hooks disabled).");
    }
    Ok(())
}

/// 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(ref finding) => {
            check.unreadable = true;
            check.findings.push(finding.clone());
        }
        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(),
        );
    }
    // F56 — an installed codex hook is not necessarily a LIVE one. Codex gates
    // hook execution behind a persisted trust grant, and a fresh install does
    // not have it: observed 2026-08-17, `codex exec` produced no hook payload
    // at all until `--dangerously-bypass-hook-trust` was passed.
    //
    // Reported as INFO, not a finding, and worded as unverifiable rather than
    // failing — because it is exactly that. Codex exposes no way to query
    // hook trust, so a pass/fail verdict here would be a claim with no evidence
    // behind it. Note project trust is a DIFFERENT mechanism and does not
    // satisfy this: a `trust_level = "trusted"` project still did not fire.
    if matches!(entry, EntryState::Current) {
        check.info = Some(
            "codex: hook entry is current, but codex requires a persisted HOOK TRUST \
             grant. pushkin cannot verify that grant from here — until it is given, the \
             hook does not run and this repo is UNGATED for codex (F56). Grant it by \
             running codex once interactively and approving, or pass \
             --dangerously-bypass-hook-trust for vetted automation. Project trust \
             (`trust_level`) is a different setting and does not cover this."
                .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))
            })
        })
}

/// F71 phase A — binary/manifest schema skew, made visible.
///
/// **Non-aborting by construction.** This deliberately does NOT use
/// `load_manifest()?`: that is the very call whose `?` makes every
/// manifest-reading verb exit 1 before doing anything, and adopting it
/// here would make `doctor` fail the same way it exists to report on.
/// Read, attempt, convert `Err` into a finding, keep sweeping.
///
/// **Absence is not skew** (N13). A repo with no `pushkin.toml` has
/// positively probed absence — the one case N13 reserves fail-open for —
/// and reporting it as skew would make `doctor` red in every repo that
/// has not adopted pushkin. It is an info line, like every other
/// presence-keyed check here.
///
/// **Unreadable is not unparseable.** `chmod` and `cargo install` are
/// different remedies, so they get different findings; collapsing them
/// would route the reader to the wrong one.
///
/// Phase A stops here. The finding states what the skew costs TODAY —
/// the write-time gate is not running, because a hook exiting 1 is
/// non-blocking — and says nothing about changing that. Making the gate
/// fail closed is Phase B, unruled, and out of scope
/// (`docs/charters/2026-08-19-f71-manifest-skew.md` §3).
fn check_manifest_skew() -> AgentCheck {
    let path = super::MANIFEST_FILE;
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return AgentCheck {
                findings: Vec::new(),
                info: Some(format!("{path}: not present — not checked")),
                unreadable: false,
                path_advisory: false,
            };
        }
        Err(error) => {
            return AgentCheck {
                findings: vec![format!(
                    "{path} could not be read ({error}) — this binary cannot tell whether the \
                     manifest matches its schema, so the write-time gate's state is unknown. \
                     Fix the file's permissions and re-run; `doctor --repair` will not touch it."
                )],
                info: None,
                unreadable: true,
                path_advisory: false,
            };
        }
    };
    match pushkin_core::manifest::Manifest::parse(&text) {
        Ok(_) => AgentCheck {
            findings: Vec::new(),
            info: None,
            unreadable: false,
            path_advisory: false,
        },
        Err(error) => AgentCheck {
            findings: vec![format!(
                "manifest schema skew: this binary cannot parse {path}{error}\n  \
                 The write-time gate is NOT running while this is true: every manifest-reading \
                 verb exits 1 before it reads a payload, and a hook exiting 1 is non-blocking, \
                 so writes proceed ungated.\n  \
                 Remedy: cargo install --path crates/pushkin-cli (a binary older than the \
                 manifest schema is the usual cause). `doctor --repair` does not own this."
            )],
            info: None,
            unreadable: false,
            path_advisory: false,
        },
    }
}

/// F73 phase 1 — nested `pushkin.toml` files, named before resolution changes.
///
/// **Why this exists.** `verbs.rs:27` defines `MANIFEST_FILE` as the bare
/// relative path `"pushkin.toml"` and `load_manifest` reads it with no ancestor
/// walk, so the manifest that governs a verdict is whichever one sits in the
/// process's cwd. A nested manifest therefore decides verdicts for any
/// invocation made from its directory — silently, today.
///
/// **This changes nothing.** Resolution is phase 2 (git root, plus a
/// `PUSHKIN_MANIFEST` escape). Phase 1 only makes the situation visible, so the
/// switch is announced rather than sprung on repos that rely on a nested
/// manifest — knowingly or not. Shipping it silently would be doing to users
/// what the bug did to us.
///
/// **A nested manifest is not automatically a mistake**, so the finding does not
/// read as one: this repo's own `sandbox/db/pushkin.toml` is committed and
/// deliberate. Both legitimate outcomes are named, and `--repair` never deletes
/// it — that is the user's file.
///
/// Scope excludes `target/` and `node_modules/`: a full-tree walk would make
/// `doctor`'s cost scale with build artefacts, and `target/` can hold vendored
/// crates carrying their own manifest, producing findings about files the
/// operator never wrote. Gitignored manifests ARE reported — `.gitignore`
/// governs what ships, not what a `cd` can reach.
/// F73 — manifest resolution fell back to the working directory because `git`
/// could not be run.
///
/// The fallback itself is correct (N13: positively probed absence fails open),
/// and `load_manifest` already emits a loud notice at the point of use — which
/// is where it matters. This is the standing report.
///
/// **An INFO line, not a finding**, unlike its nested-manifest sibling. The
/// difference is what the operator can act on: a nested manifest is a fact
/// about *their repository*, which they chose and can change; a missing `git`
/// is a fact about *the environment*, which they may not control at all — a
/// minimal container, a restricted `PATH`, a build sandbox. Doctor already
/// files exactly that class as info (`not installed — not checked`, `not a git
/// repository — not checked`), and this joins it.
///
/// Making it a finding would turn `doctor` red in every git-less environment
/// and teach the operator to ignore a red doctor, which is the fatigue argument
/// that keeps `test` out of `on_stop`. It would also be the wrong claim: the
/// state is not a defect, it is a coverage limit — F73 is fixed where `git` is
/// available and unchanged where it is not, and this line is how a reader
/// learns which side they are on.
fn check_manifest_resolution() -> AgentCheck {
    let clean = AgentCheck {
        findings: Vec::new(),
        info: None,
        unreadable: false,
        path_advisory: false,
    };
    let Ok(resolved) = super::resolve_manifest() else {
        return clean;
    };
    let super::ManifestSource::WorkingDirectory {
        git_unavailable: Some(reason),
    } = resolved.source
    else {
        return clean;
    };
    AgentCheck {
        findings: Vec::new(),
        info: Some(format!(
            "manifest resolution: not pinned to a repository root — {reason} Falling back to \
             the working directory, so running pushkin from a subdirectory can pick up a \
             different manifest, or none (F73 is fixed where git is available). Put git on \
             PATH, or set PUSHKIN_MANIFEST to the manifest you mean."
        )),
        unreadable: false,
        path_advisory: false,
    }
}

fn check_nested_manifests() -> AgentCheck {
    let clean = AgentCheck {
        findings: Vec::new(),
        info: None,
        unreadable: false,
        path_advisory: false,
    };
    // No root manifest means there is nothing for a nested one to shadow; that
    // case belongs to the F71 probe's info line, not here.
    if !std::path::Path::new(super::MANIFEST_FILE).exists() {
        return clean;
    }
    let mut nested = Vec::new();
    collect_nested_manifests(std::path::Path::new("."), &mut nested);
    if nested.is_empty() {
        return clean;
    }
    nested.sort();
    AgentCheck {
        findings: nested
            .into_iter()
            .map(|path| {
                format!(
                    "nested pushkin.toml at {path} — it governs verdicts for any pushkin \
                     invocation made from its directory today, because the manifest is resolved \
                     from the current directory. That is F73, and it is being fixed: after the \
                     resolution change it will NOT govern.\n  \
                     If that is deliberate, set PUSHKIN_MANIFEST to point at it explicitly, or \
                     give it its own repo. `doctor --repair` will not touch it — it is your file."
                )
            })
            .collect(),
        info: None,
        unreadable: false,
        path_advisory: false,
    }
}

/// Directories never walked when looking for nested manifests.
const NESTED_SCAN_SKIP: &[&str] = &["target", "node_modules", ".git"];

/// Depth-first walk collecting every `pushkin.toml` below `root`, excluding the
/// root manifest itself. Errors are skipped rather than propagated: this is a
/// diagnostic, and an unreadable subdirectory must not abort `doctor`.
fn collect_nested_manifests(root: &std::path::Path, out: &mut Vec<String>) {
    let Ok(entries) = std::fs::read_dir(root) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if path.is_dir() {
            if NESTED_SCAN_SKIP.contains(&name.as_ref()) {
                continue;
            }
            collect_nested_manifests(&path, out);
        } else if name == super::MANIFEST_FILE {
            let display = path
                .strip_prefix("./")
                .unwrap_or(&path)
                .display()
                .to_string();
            if display != super::MANIFEST_FILE {
                out.push(display);
            }
        }
    }
}

#[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" })));
    }
}