supercode-cli 0.5.57

Volter Harness — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
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
//! UX-28 + P5-7: config-driven lifecycle hooks — user-configured EXTERNAL
//! COMMANDS run at fixed lifecycle points. P5-7 (design §2 module 17, §5.2 P5
//! row 7) grows the original 5-event table to the CC/CX-common set:
//! `pre_tool`, `post_tool`, `session_start`, `session_end`, `stop`,
//! `user_prompt_submit`, `notification`, `subagent_start`, `subagent_stop`,
//! `pre_compact`, `post_compact` (11 events). The event set = the Claude
//! Code ∩ Codex hook intersection (`cc§3`/`cx§7`) plus `session_end`
//! (already shipped) and `notification` (a universal turn-finish UX point).
//!
//! ## Emission wiring vs. registration
//!
//! ALL 11 events are config-registerable, trust-gated, bounded, and fire
//! through the one `run_hook` engine below. Their LIFECYCLE EMISSION points
//! land in two places:
//! - **Live-wired here (CLI surface):** `session_start`/`session_end`/
//!   `pre_tool`/`post_tool`/`stop` (pre-P5-7), plus `user_prompt_submit`
//!   (fired before each user turn — `main.rs`) and `notification` (fired at
//!   turn-finish — `notify::maybe_fire`).
//! - **Live-wired through the core's lifecycle observer (BP-11):**
//!   `pre_compact`/`post_compact` fire from `Agent::compact_in_place` (both
//!   the automatic triggers and `/compact`; env names the message counts and
//!   the trigger) and `subagent_start`/`subagent_stop` bracket a validated
//!   `spawn_subagent` call (env names the task, and on stop the error flag
//!   and output length). `main.rs` installs `Config::lifecycle_hook` when
//!   any of the four is configured.
//!
//! Every P5-7 event is OBSERVATIONAL (fail-open): only `pre_tool` and `stop`
//! are veto-capable. BP-10 (catalog row "Hook/plugin permission veto"):
//! `pre_tool` may now also ALLOW, ASK, or REWRITE — but those answers are
//! tiers inside the ONE permissions engine, not a bypass of it. An `allow`
//! answers a prompt the user would otherwise have seen; it can never
//! override a `deny` rule or a protected path. See
//! [`parse_pre_tool_stdout`] for the wire shape and
//! `supercode_harness::PreToolOutcome` for the contract.
//!
//! ## Security model (non-negotiable — read before touching this file)
//!
//! 1. **Opt-in only.** A hook fires only if its command is a non-empty
//!    string somewhere in [`HookSet`]. [`HookSet::is_empty`] is checked at
//!    every call site (`crates/cli/src/main.rs::build_config` for
//!    `pre_tool`/`post_tool`, and the three session entry points in `main`
//!    for `session_start`/`session_end`) *before* anything is wired up or
//!    spawned — an absent/empty `[hooks]` config is a hard, provable no-op
//!    (see `hooks_cli.rs::empty_config_runs_nothing`).
//! 2. **Config-only source.** The command STRING only ever comes from
//!    [`HooksFileConfig`] (deserialized from the user's OWN
//!    `~/.config/supercode/config.toml` — never a project-local
//!    `.supercode.toml`, see `userconfig::FileConfig::sanitized_for_project`,
//!    which strips `[hooks]` from a project config exactly like `base_url`/
//!    `system_prompt`/`sandbox`/`approval`, since opening an untrusted repo
//!    must never silently register a command to run) or a `SUPERCODE_HOOK_*`
//!    env var the user's own shell/CI set. Per-event CONTEXT (tool name,
//!    event name, session id) is passed to the hook as environment
//!    variables on the CHILD process (`run_hook`'s `extra_env`) — never
//!    spliced into the command string — so nothing the model or a tool
//!    produced is ever interpreted by a shell.
//! 3. **Bounded.** Every invocation is wall-clock bounded by `timeout_ms`
//!    (config/env `timeout_ms`/`SUPERCODE_HOOK_TIMEOUT_MS`, default
//!    [`DEFAULT_HOOK_TIMEOUT_MS`]); a hook that outlives it is killed
//!    (`run_hook`'s poll loop).
//! 4. **Failure-isolated.** A hook that fails to spawn, exits non-zero, or
//!    times out never panics and never aborts the run — `run_hook` returns
//!    a plain [`HookOutcome`], not a `Result` a caller could `?`-propagate.
//!    The one deliberate exception is `pre_tool`: since its entire purpose
//!    is to GATE a tool call, a failed/timed-out `pre_tool` hook fails
//!    CLOSED (denies the call — see [`fire_pre_tool`]) rather than silently
//!    letting it through. The three observational hooks (`post_tool`/
//!    `session_start`/`session_end`) always fail OPEN: log to stderr via
//!    [`report`] and continue exactly as if no hook had been configured.
//! 5. **stdout-clean.** A hook's own stdout/stderr are captured and
//!    forwarded ONLY to supercode's stderr (`[hook:<event>]`-prefixed) —
//!    never to stdout, so `--output-format json`/`stream-json` stay
//!    byte-exact regardless of what a hook script prints.
//!
//! `--quiet` suppresses the informational forwarding of a SUCCESSFUL hook's
//! own stdout/stderr (chrome), but never suppresses failure/timeout/deny
//! diagnostics (requirement 4 is unconditional) — see `report`.

use std::io::Read as _;
use std::process::{Command, Stdio};

use std::sync::Once;
use std::time::{Duration, Instant};
use supercode_harness::{HookDecision, PreToolOutcome};

/// Default per-hook timeout. Generous enough for a real script (git hooks,
/// notifiers) but bounded — no config can accidentally hang a turn forever.
pub const DEFAULT_HOOK_TIMEOUT_MS: u64 = 10_000;

/// The `[hooks]` table shape in `config.toml` / a (sanitized-away-from-
/// project) `.supercode.toml`. Every field optional — an absent table
/// deserializes to all-`None`, i.e. zero hooks (requirement 1).
#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct HooksFileConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pre_tool: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post_tool: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_start: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_end: Option<String>,
    /// P4b (COMPOSABLE-HARNESS-DESIGN.md §5.2 "P4", §1.9/§2 module 17,
    /// design's §3.1 comment `# ... stop = "cmd" ...`): the declarative
    /// stop-gate — a fifth event on the SAME `[hooks]` table, layered on
    /// `supercode-harness`'s single `Config::stop_gate` slot (see
    /// `fire_stop`'s doc comment for why this can never double-fire with a
    /// hand-installed code-level gate).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop: Option<String>,
    // ---- P5-7: the CC/CX-common lifecycle event set (design §2 module 17,
    // "config-registered lifecycle hooks (~10-30 events)"; §5.2 P5 row 7,
    // "grow the CLI 4-event table toward the CC/CX-common set"). Every event
    // below is (a) shipped by BOTH Claude Code AND Codex — the intersection
    // of `cc§3 Hooks` (30 events) and `cx§7` (10 events, "Claude-Code-
    // compatible shape": SessionStart, SubagentStart, PreToolUse,
    // PermissionRequest, PostToolUse, PreCompact, PostCompact,
    // UserPromptSubmit, SubagentStop, Stop) — or, for `notification`, a
    // universal UX-notification point both surface (cc `Notification` hook /
    // cx `[tui] notifications`). Each is OBSERVATIONAL (fail-open, best-
    // effort): unlike `pre_tool`/`stop`, none can veto — a veto hook can only
    // ever DENY an action, and none of these events gate one. Same opt-in /
    // config-only-source / bounded / project-forbidden security model as the
    // five above (see the module doc); adding them here automatically extends
    // the project-strip (`userconfig::sanitized_for_project` strips the whole
    // `[hooks]` table the moment ANY field — old or new — is set).
    /// CC `UserPromptSubmit` / CX `UserPromptSubmit`: fires when a user prompt
    /// is submitted, before the agent turn runs (CLI-side lifecycle point).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_prompt_submit: Option<String>,
    /// CC `Notification` (notification-type `agent_completed`): fires at the
    /// turn-finish notification point (see `crate::notify::maybe_fire`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notification: Option<String>,
    /// CC/CX `SubagentStart`: fires when a subagent begins. REGISTERABLE +
    /// trust-gated now; its in-loop emission site lives inside
    /// `supercode-harness`'s `Agent::run_spawn_subagent` (the `subagents` module,
    /// design §1.12 / P5-3) and is intentionally NOT wired from this
    /// CLI-surface unit — see the module doc's "deferred emission" note.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subagent_start: Option<String>,
    /// CC/CX `SubagentStop`: fires when a subagent completes. Same
    /// deferred-emission note as `subagent_start`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subagent_stop: Option<String>,
    /// CC/CX `PreCompact`: fires before compaction. Same deferred-emission
    /// note — the site is inside `Agent::maybe_compact`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pre_compact: Option<String>,
    /// CC/CX `PostCompact`: fires after compaction. Same deferred-emission
    /// note as `pre_compact`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post_compact: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

/// Which lifecycle point fired. Also the value of the `SUPERCODE_HOOK_EVENT`
/// env var handed to the child process and the `[hook:<event>]` stderr
/// prefix — one source of truth for the string form (`as_str`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookEvent {
    PreTool,
    PostTool,
    SessionStart,
    SessionEnd,
    /// P4b: the stop-gate event — see [`HooksFileConfig::stop`].
    Stop,
    // P5-7 CC/CX-common events (all observational).
    UserPromptSubmit,
    Notification,
    // The four below are config-registerable + trust-gated + fireable today,
    // but their lifecycle EMISSION site lives inside `supercode-harness`'s loop
    // (`run_spawn_subagent` / `maybe_compact`) and is intentionally deferred
    // to its owning subsystem (see the module doc's "deferred emission"
    // note). They are therefore not yet CONSTRUCTED in production — only
    // matched (`as_str`/`command_for`) and exercised by tests — so the
    // never-constructed lint is expected and allowed until the owning
    // subsystem wires the one-line `fire_observational` call at its site.
    #[allow(dead_code)]
    SubagentStart,
    #[allow(dead_code)]
    SubagentStop,
    #[allow(dead_code)]
    PreCompact,
    #[allow(dead_code)]
    PostCompact,
}

impl HookEvent {
    pub fn as_str(self) -> &'static str {
        match self {
            HookEvent::PreTool => "pre_tool",
            HookEvent::PostTool => "post_tool",
            HookEvent::SessionStart => "session_start",
            HookEvent::SessionEnd => "session_end",
            HookEvent::Stop => "stop",
            HookEvent::UserPromptSubmit => "user_prompt_submit",
            HookEvent::Notification => "notification",
            HookEvent::SubagentStart => "subagent_start",
            HookEvent::SubagentStop => "subagent_stop",
            HookEvent::PreCompact => "pre_compact",
            HookEvent::PostCompact => "post_compact",
        }
    }

    /// Whether this event can VETO (deny/refuse) — only `pre_tool` (deny a
    /// tool call) and `stop` (refuse termination). Every P5-7 event is
    /// observational and can never veto: a hook may only ever DENY an action
    /// a veto-capable event already gates, never grant or escalate one (a
    /// registered `notification`/`subagent_stop`/… hook has no action to
    /// gate at all). Also the one place the fail-open vs fail-closed split is
    /// named: veto events fail CLOSED (`pre_tool`) / OPEN (`stop`) per their
    /// own `fire_*`; observational events always fail open.
    pub fn is_veto_capable(self) -> bool {
        matches!(self, HookEvent::PreTool | HookEvent::Stop)
    }
}

/// The fully-resolved set of hooks for this process: `HooksFileConfig`
/// (already project-sanitized by the time it reaches here — see
/// `userconfig::FileConfig::sanitized_for_project`) with `SUPERCODE_HOOK_*`
/// env vars overlaid on top (env wins, matching every other config knob's
/// flag > env > file precedence in this crate).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct HookSet {
    pub pre_tool: Option<String>,
    pub post_tool: Option<String>,
    pub session_start: Option<String>,
    pub session_end: Option<String>,
    /// P4b — see [`HooksFileConfig::stop`].
    pub stop: Option<String>,
    // P5-7 CC/CX-common events.
    pub user_prompt_submit: Option<String>,
    pub notification: Option<String>,
    pub subagent_start: Option<String>,
    pub subagent_stop: Option<String>,
    pub pre_compact: Option<String>,
    pub post_compact: Option<String>,
    pub timeout_ms: u64,
}

// P4e-class defect fix (P5-7 review, MEDIUM): a user who registers one of
// the four deferred-emission events (`subagent_start`/`subagent_stop`/
// `pre_compact`/`post_compact` — see the module doc's "Emission wiring vs.
// registration" section) gets a SILENT no-op today: the event resolves,
// passes the trust/strip checks, and is even matched by `command_for`, but
// nothing ever calls `fire_observational` for it because the owning
// subsystem (`subagents`/`maybe_compact`) hasn't landed its emission call
// yet. That is indistinguishable, from the user's seat, from a config typo.
// One `Once` per deferred event turns "silent" into "reported exactly once
// per process, the moment the event first resolves to `Some`" without
// requiring every `HookSet::resolve` call site (there are several — session
// entry points, the per-tool wiring, the per-turn `user_prompt_submit`
// reload) to coordinate on printing exactly once itself.
static WARN_SUBAGENT_START: Once = Once::new();
static WARN_SUBAGENT_STOP: Once = Once::new();
static WARN_PRE_COMPACT: Once = Once::new();
static WARN_POST_COMPACT: Once = Once::new();

/// Emit the one-time "registered but not yet emitted" stderr notice for a
/// deferred event, iff `configured` (this process's resolved `HookSet` has a
/// `Some` command for it) — never for an unconfigured event (requirement 1:
/// default-off must stay behaviorally silent) and never more than once per
/// process even though `HookSet::resolve` runs many times in a session (the
/// `Once` gate, not a call-count check, is what guarantees that).
fn warn_once_if_deferred(once: &Once, event: HookEvent, configured: bool) {
    if configured {
        once.call_once(|| {
            eprintln!(
                "warning: [hooks] {} is registered but is not yet emitted in this build (no-op)",
                event.as_str()
            );
        });
    }
}

impl HookSet {
    /// Resolve from the (already project-sanitized) file config, overlaying
    /// `SUPERCODE_HOOK_*` env vars. Env vars are inherited from the
    /// invoking shell/CI — never from a repo's files — so overlaying them
    /// here does not weaken requirement 2.
    ///
    /// Also the single choke point for the deferred-event no-op warning (see
    /// [`warn_once_if_deferred`]): every call site that builds a `HookSet`
    /// for a session or a turn (`load_hook_set`, `main.rs`'s direct
    /// `HookSet::resolve` calls at startup, `pre_tool`/`post_tool` wiring,
    /// and the per-turn `user_prompt_submit` reload) funnels through here,
    /// so gating the warning on a `Once` rather than printing unconditionally
    /// is what makes it fire exactly once per PROCESS regardless of how many
    /// times a session's hook set gets re-resolved.
    pub fn resolve(fc: &HooksFileConfig) -> HookSet {
        let env =
            |name: &str| -> Option<String> { std::env::var(name).ok().filter(|v| !v.is_empty()) };
        let hs = HookSet {
            pre_tool: env("SUPERCODE_HOOK_PRE_TOOL").or_else(|| fc.pre_tool.clone()),
            post_tool: env("SUPERCODE_HOOK_POST_TOOL").or_else(|| fc.post_tool.clone()),
            session_start: env("SUPERCODE_HOOK_SESSION_START").or_else(|| fc.session_start.clone()),
            session_end: env("SUPERCODE_HOOK_SESSION_END").or_else(|| fc.session_end.clone()),
            stop: env("SUPERCODE_HOOK_STOP").or_else(|| fc.stop.clone()),
            user_prompt_submit: env("SUPERCODE_HOOK_USER_PROMPT_SUBMIT")
                .or_else(|| fc.user_prompt_submit.clone()),
            notification: env("SUPERCODE_HOOK_NOTIFICATION").or_else(|| fc.notification.clone()),
            subagent_start: env("SUPERCODE_HOOK_SUBAGENT_START")
                .or_else(|| fc.subagent_start.clone()),
            subagent_stop: env("SUPERCODE_HOOK_SUBAGENT_STOP").or_else(|| fc.subagent_stop.clone()),
            pre_compact: env("SUPERCODE_HOOK_PRE_COMPACT").or_else(|| fc.pre_compact.clone()),
            post_compact: env("SUPERCODE_HOOK_POST_COMPACT").or_else(|| fc.post_compact.clone()),
            timeout_ms: env("SUPERCODE_HOOK_TIMEOUT_MS")
                .and_then(|v| v.parse().ok())
                .or(fc.timeout_ms)
                .unwrap_or(DEFAULT_HOOK_TIMEOUT_MS),
        };
        warn_once_if_deferred(
            &WARN_SUBAGENT_START,
            HookEvent::SubagentStart,
            hs.subagent_start.is_some(),
        );
        warn_once_if_deferred(
            &WARN_SUBAGENT_STOP,
            HookEvent::SubagentStop,
            hs.subagent_stop.is_some(),
        );
        warn_once_if_deferred(
            &WARN_PRE_COMPACT,
            HookEvent::PreCompact,
            hs.pre_compact.is_some(),
        );
        warn_once_if_deferred(
            &WARN_POST_COMPACT,
            HookEvent::PostCompact,
            hs.post_compact.is_some(),
        );
        hs
    }

    /// Requirement 1 (opt-in): true iff NOT ONE event has a command
    /// configured. Every call site checks this before wiring up a closure
    /// or spawning anything — "no hooks configured" is a hard, checkable
    /// no-op, not just an emergent property of empty strings never matching.
    /// BP-10: how many events actually have a command configured — for
    /// the one-line notice the trust gate prints when it refuses to
    /// install them.
    pub fn configured_count(&self) -> usize {
        [
            &self.pre_tool,
            &self.post_tool,
            &self.session_start,
            &self.session_end,
            &self.stop,
            &self.user_prompt_submit,
            &self.notification,
            &self.subagent_start,
            &self.subagent_stop,
            &self.pre_compact,
            &self.post_compact,
        ]
        .iter()
        .filter(|c| c.is_some())
        .count()
    }

    pub fn is_empty(&self) -> bool {
        self.pre_tool.is_none()
            && self.post_tool.is_none()
            && self.session_start.is_none()
            && self.session_end.is_none()
            && self.stop.is_none()
            && self.user_prompt_submit.is_none()
            && self.notification.is_none()
            && self.subagent_start.is_none()
            && self.subagent_stop.is_none()
            && self.pre_compact.is_none()
            && self.post_compact.is_none()
    }

    fn command_for(&self, event: HookEvent) -> Option<&str> {
        match event {
            HookEvent::PreTool => self.pre_tool.as_deref(),
            HookEvent::PostTool => self.post_tool.as_deref(),
            HookEvent::SessionStart => self.session_start.as_deref(),
            HookEvent::SessionEnd => self.session_end.as_deref(),
            HookEvent::Stop => self.stop.as_deref(),
            HookEvent::UserPromptSubmit => self.user_prompt_submit.as_deref(),
            HookEvent::Notification => self.notification.as_deref(),
            HookEvent::SubagentStart => self.subagent_start.as_deref(),
            HookEvent::SubagentStop => self.subagent_stop.as_deref(),
            HookEvent::PreCompact => self.pre_compact.as_deref(),
            HookEvent::PostCompact => self.post_compact.as_deref(),
        }
    }
}

/// The result of running one hook invocation. Deliberately NOT a `Result` —
/// every failure mode (spawn error, timeout, non-zero exit) is a normal,
/// representable outcome a caller inspects, never a `?`-propagated error
/// (requirement 4: a hook can never abort the run by erroring).
#[derive(Debug, Default)]
struct HookOutcome {
    timed_out: bool,
    exit_code: Option<i32>,
    stdout: String,
    stderr: String,
    spawn_error: Option<String>,
}

impl HookOutcome {
    fn failed(&self, event: HookEvent) -> bool {
        self.spawn_error.is_some()
            || self.timed_out
            || matches!(
                self.exit_code,
                // A non-zero exit is a "failure" to report ONLY for
                // observational events; for the veto-capable ones
                // (`pre_tool`/`stop`) a non-zero exit is a normal DENY/VETO
                // signal handled by their own `fire_*`, not a failure.
                Some(c) if c != 0 && !event.is_veto_capable()
            )
    }
}

/// Run `command` via `sh -c` (std::process — no async runtime needed here;
/// this stays a plain blocking call so it can be invoked from the existing
/// SYNCHRONOUS `PreToolHook`/`PostToolHook` closure signatures in
/// `supercode-harness`, reusing that plumbing exactly per the ticket's approach
/// sketch rather than widening those types to `async`). Bounded by
/// `timeout_ms` via a poll loop (`try_wait`) that kills the child on
/// expiry — no new dependency (`std::process`/`std::thread` only).
///
/// `extra_env` is context (tool name, session id, …) attached as literal
/// environment variables on the CHILD process — never interpolated into
/// `command` itself, so untrusted content (a tool's arguments/output) is
/// never handed to a shell for interpretation (requirement 2).
fn run_hook(
    event: HookEvent,
    command: &str,
    timeout_ms: u64,
    extra_env: &[(&str, String)],
) -> HookOutcome {
    let mut cmd = Command::new("sh");
    cmd.arg("-c").arg(command);
    cmd.env("SUPERCODE_HOOK_EVENT", event.as_str());
    for (k, v) in extra_env {
        cmd.env(k, v);
    }
    cmd.stdin(Stdio::null());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    // On timeout we must kill the WHOLE process tree, not just the direct
    // `sh` child — `sh -c "some | pipeline"` or a script that backgrounds
    // work can leave grandchildren running, which would hold the stdout/
    // stderr pipes open and make the "bounded" reads below block for as
    // long as THOSE processes run, silently defeating `timeout_ms`. Placing
    // the child in its own new process group (`process_group(0)`, stable
    // std API, no new dependency) makes its pgid == its pid, so
    // `kill(-pid, SIGKILL)` on timeout (see the loop below) reaches every
    // descendant in one call.
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    // Windows has no process groups: the child starts suspended, joins a
    // Job Object, and only then runs, so every descendant it spawns is in
    // the job that `kill_process_tree` terminates on timeout.
    #[cfg(windows)]
    let job = HookJob::create();
    #[cfg(windows)]
    if job.is_some() {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED);
    }

    let mut child = match cmd.spawn() {
        Ok(c) => c,
        Err(e) => {
            return HookOutcome {
                spawn_error: Some(e.to_string()),
                ..Default::default()
            }
        }
    };
    #[cfg(windows)]
    let job = match job {
        Some(job) => match job.attach_and_resume(&child) {
            Ok(true) => Some(job),
            Ok(false) => None,
            Err(e) => {
                // Never leave a suspended hook behind.
                let _ = child.kill();
                let _ = child.wait();
                return HookOutcome {
                    spawn_error: Some(e.to_string()),
                    ..Default::default()
                };
            }
        },
        None => None,
    };

    // Drain stdout/stderr on background threads WHILE polling for exit —
    // reading only after the process ends risks a pipe-buffer deadlock if
    // the hook writes more than the OS pipe buffer before exiting.
    let stdout_pipe = child.stdout.take();
    let stderr_pipe = child.stderr.take();
    let stdout_handle = stdout_pipe.map(|mut p| {
        std::thread::spawn(move || {
            let mut s = String::new();
            let _ = p.read_to_string(&mut s);
            s
        })
    });
    let stderr_handle = stderr_pipe.map(|mut p| {
        std::thread::spawn(move || {
            let mut s = String::new();
            let _ = p.read_to_string(&mut s);
            s
        })
    });

    let deadline = Instant::now() + Duration::from_millis(timeout_ms);
    let mut timed_out = false;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break Some(status),
            Ok(None) => {
                if Instant::now() >= deadline {
                    timed_out = true;
                    #[cfg(windows)]
                    if let Some(job) = &job {
                        job.terminate();
                    }
                    kill_process_tree(&mut child);
                    let _ = child.wait();
                    break None;
                }
                std::thread::sleep(Duration::from_millis(15));
            }
            Err(_) => break None,
        }
    };

    HookOutcome {
        timed_out,
        exit_code: status.and_then(|s| s.code()),
        stdout: stdout_handle
            .and_then(|h| h.join().ok())
            .unwrap_or_default(),
        stderr: stderr_handle
            .and_then(|h| h.join().ok())
            .unwrap_or_default(),
        spawn_error: None,
    }
}

/// Kill a timed-out hook's ENTIRE process group (see `run_hook`'s
/// `process_group(0)` setup) — plain `Child::kill` only signals the direct
/// `sh` PID, which leaves any grandchild it forked (a backgrounded command,
/// a pipeline stage) running and holding the stdout/stderr pipes open.
#[cfg(unix)]
fn kill_process_tree(child: &mut std::process::Child) {
    // Safety: `libc::kill` is a plain syscall wrapper with no preconditions
    // beyond a valid pid, which `child.id()` always is here. Negating the
    // pid targets the whole process group `run_hook` placed this child in
    // (`process_group(0)` makes pgid == pid).
    unsafe {
        libc::kill(-(child.id() as libc::pid_t), libc::SIGKILL);
    }
    let _ = child.kill(); // belt-and-suspenders if the group signal ever fails
}

/// On Windows the tree itself is ended by [`HookJob::terminate`] first; this
/// kills the direct child (also the only kill when no job could be made).
#[cfg(not(unix))]
fn kill_process_tree(child: &mut std::process::Child) {
    let _ = child.kill();
}

/// A Job Object owning one hook's process tree — Windows' counterpart to
/// the Unix `process_group(0)` + `kill(-pgid)` above. Without it, killing
/// the direct `sh` leaves a grandchild (`sleep 5`) holding the stdout/
/// stderr pipes open, and the reads block for its full run. Not
/// kill-on-close: like the Unix group, descendants of a hook that exits
/// normally are left alone; only a timeout ends them.
#[cfg(windows)]
struct HookJob(windows_sys::Win32::Foundation::HANDLE);

#[cfg(windows)]
impl HookJob {
    fn create() -> Option<Self> {
        use windows_sys::Win32::System::JobObjects::CreateJobObjectW;
        let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        (!job.is_null()).then_some(Self(job))
    }

    /// Assign the suspended `child` to the job, then resume its primary
    /// thread (std doesn't expose the thread handle, so find it by pid).
    /// `Ok(false)`: resumed, but not in the job (see below).
    fn attach_and_resume(&self, child: &std::process::Child) -> std::io::Result<bool> {
        use std::os::windows::io::AsRawHandle;
        use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
        use windows_sys::Win32::System::Diagnostics::ToolHelp::{
            CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32,
        };
        use windows_sys::Win32::System::JobObjects::AssignProcessToJobObject;
        use windows_sys::Win32::System::Threading::{
            OpenThread, ResumeThread, THREAD_SUSPEND_RESUME,
        };

        // Joining the job is best effort: a supercode that runs inside a job that won't nest can't place the
        // hook in one, and the hook then runs without it (a timeout ends only the direct child, as before).
        // Only failing to resume the suspended hook is an error.
        let attached =
            unsafe { AssignProcessToJobObject(self.0, child.as_raw_handle().cast()) } != 0;
        let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
        if snapshot == INVALID_HANDLE_VALUE {
            return Err(std::io::Error::last_os_error());
        }
        let result = (|| {
            let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
            entry.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
            let mut has_entry = unsafe { Thread32First(snapshot, &mut entry) } != 0;
            while has_entry {
                if entry.th32OwnerProcessID == child.id() {
                    let thread =
                        unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
                    if thread.is_null() {
                        return Err(std::io::Error::last_os_error());
                    }
                    let resumed = unsafe { ResumeThread(thread) };
                    unsafe { CloseHandle(thread) };
                    if resumed == u32::MAX {
                        return Err(std::io::Error::last_os_error());
                    }
                    return Ok(());
                }
                has_entry = unsafe { Thread32Next(snapshot, &mut entry) } != 0;
            }
            Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "suspended hook's primary thread was not found",
            ))
        })();
        unsafe { CloseHandle(snapshot) };
        result.map(|()| attached)
    }

    fn terminate(&self) {
        use windows_sys::Win32::System::JobObjects::TerminateJobObject;
        unsafe { TerminateJobObject(self.0, 1) };
    }
}

#[cfg(windows)]
impl Drop for HookJob {
    fn drop(&mut self) {
        unsafe { windows_sys::Win32::Foundation::CloseHandle(self.0) };
    }
}

/// Forward a hook's own stdout/stderr and any failure diagnostic to
/// supercode's stderr — NEVER stdout (requirement 5). `--quiet` suppresses
/// the successful-path forwarding (chrome), but a failure/timeout is always
/// reported regardless of `quiet` (requirement 4 is unconditional).
fn report(event: HookEvent, outcome: &HookOutcome, quiet: bool) {
    if let Some(err) = &outcome.spawn_error {
        eprintln!("[hook:{}] failed to start: {err}", event.as_str());
        return;
    }
    let failed = outcome.failed(event);
    if !quiet || failed {
        let out = outcome.stdout.trim();
        if !out.is_empty() {
            eprintln!("[hook:{}] {out}", event.as_str());
        }
        let err = outcome.stderr.trim();
        if !err.is_empty() {
            eprintln!("[hook:{}] stderr: {err}", event.as_str());
        }
    }
    if outcome.timed_out {
        eprintln!("[hook:{}] timed out and was killed", event.as_str());
    } else if let Some(code) = outcome.exit_code {
        if code != 0 && !event.is_veto_capable() {
            eprintln!("[hook:{}] exited {code}", event.as_str());
        }
    }
}

/// Fire an OBSERVATIONAL hook (`post_tool`/`session_start`/`session_end`):
/// best-effort, always fails OPEN — never influences control flow, never
/// panics, never blocks longer than `timeout_ms`. A no-op if this event has
/// no command configured (requirement 1).
pub fn fire_observational(
    hooks: &HookSet,
    event: HookEvent,
    extra_env: &[(&str, String)],
    quiet: bool,
) {
    let Some(command) = hooks.command_for(event) else {
        return;
    };
    let outcome = run_hook(event, command, hooks.timeout_ms, extra_env);
    report(event, &outcome, quiet);
}

/// P5-7: fire the `user_prompt_submit` observational hook at the CLI's
/// pre-turn lifecycle point (before a user prompt is sent to the agent).
/// Best-effort / fail-open like every observational event: a failing hook is
/// logged to stderr and the turn proceeds unchanged. The prompt text is
/// attached as BOUNDED env context (`SUPERCODE_HOOK_PROMPT`, capped) — never
/// spliced into the command string (requirement 2) — alongside `cwd`/session
/// context. A no-op if `user_prompt_submit` has no command configured.
pub fn fire_user_prompt_submit(
    hooks: &HookSet,
    prompt: &str,
    cwd: &std::path::Path,
    session_name: Option<&str>,
    quiet: bool,
) {
    if hooks.user_prompt_submit.is_none() {
        return;
    }
    let mut extra = vec![
        ("SUPERCODE_HOOK_CWD", cwd.to_string_lossy().into_owned()),
        (
            "SUPERCODE_HOOK_PROMPT",
            prompt.chars().take(8_000).collect::<String>(),
        ),
    ];
    if let Some(name) = session_name {
        extra.push(("SUPERCODE_HOOK_SESSION", name.to_string()));
    }
    fire_observational(hooks, HookEvent::UserPromptSubmit, &extra, quiet);
}

/// P5-7: fire the `notification` observational hook at the turn-finish
/// notification point (CC `Notification` hook, notification-type
/// `agent_completed`). Wired from `crate::notify::maybe_fire`, it fires on
/// every completed turn independent of the desktop-notify opt-in/tty gate —
/// the hook is its OWN opt-in (a distinct config command), so a consumer can
/// react to turn completions without also enabling desktop pop-ups. Bounded
/// context via env (`SUPERCODE_HOOK_NOTIFICATION_KIND`, model, elapsed
/// seconds, a short capped summary). A no-op if `notification` is unset.
pub fn fire_notification(
    hooks: &HookSet,
    model: &str,
    elapsed_secs: u64,
    summary: &str,
    quiet: bool,
) {
    if hooks.notification.is_none() {
        return;
    }
    let extra: [(&str, String); 4] = [
        (
            "SUPERCODE_HOOK_NOTIFICATION_KIND",
            "agent_completed".to_string(),
        ),
        ("SUPERCODE_HOOK_MODEL", model.to_string()),
        ("SUPERCODE_HOOK_ELAPSED_SECS", elapsed_secs.to_string()),
        (
            "SUPERCODE_HOOK_SUMMARY",
            summary.chars().take(2_000).collect::<String>(),
        ),
    ];
    fire_observational(hooks, HookEvent::Notification, &extra, quiet);
}

/// Fire the `pre_tool` GATING hook. Returns `None` to ALLOW the call, or
/// `Some(reason)` to DENY it (fed back to the model as a tool error, same
/// contract `Agent::run_tool` already has for the compiled-in `PreToolHook`
/// closure). A no-op (`None`, i.e. allow) if `pre_tool` has no command
/// configured (requirement 1).
///
/// Fails CLOSED (requirement 4): a spawn error, a timeout, or an inability
/// to read an exit code all deny the call, exactly like an explicit
/// non-zero exit — the entire point of a gating hook is "don't let this
/// through unless the hook actively said yes," so a hook that can't run at
/// all must not be silently treated as permission.
pub fn fire_pre_tool(hooks: &HookSet, extra_env: &[(&str, String)], quiet: bool) -> PreToolOutcome {
    let Some(command) = hooks.pre_tool.as_ref() else {
        return PreToolOutcome::pass();
    };
    let outcome = run_hook(HookEvent::PreTool, command, hooks.timeout_ms, extra_env);
    report(HookEvent::PreTool, &outcome, quiet);

    let result = if let Some(err) = &outcome.spawn_error {
        PreToolOutcome::deny(format!("pre_tool hook failed to start: {err}"))
    } else if outcome.timed_out {
        PreToolOutcome::deny(format!(
            "pre_tool hook timed out after {}ms",
            hooks.timeout_ms
        ))
    } else {
        match outcome.exit_code {
            // BP-10: exit 0 no longer means only "allow". A hook may print
            // a JSON verdict on stdout to allow / ask / deny / REWRITE the
            // call — see `parse_pre_tool_stdout`. Anything else (the
            // common case: silence) still means "no opinion", exactly as
            // before.
            Some(0) => parse_pre_tool_stdout(outcome.stdout.trim()),
            Some(code) => {
                let text = outcome.stdout.trim();
                PreToolOutcome::deny(if text.is_empty() {
                    format!("pre_tool hook denied (exit {code})")
                } else {
                    text.to_string()
                })
            }
            None => PreToolOutcome::deny("pre_tool hook exited abnormally (no exit code)"),
        }
    };
    // A denial is a security-relevant, non-decorative event: always visible
    // on stderr regardless of `--quiet` (the tool-call error itself also
    // surfaces the reason to the model/transcript, but this line is the
    // supercode-side audit trail).
    if result.decision == HookDecision::Deny {
        let r = result
            .reason
            .clone()
            .unwrap_or_else(|| "denied".to_string());
        eprintln!("[hook:pre_tool] denied: {r}");
    }
    result
}

/// BP-10 (catalog row "Hook/plugin permission veto", the allow/ask/rewrite
/// half): read a `pre_tool` hook's stdout as a structured verdict.
///
/// Accepted shapes, in the order they are looked for:
///
/// * Claude Code's own PreToolUse JSON —
///   `{"hookSpecificOutput": {"permissionDecision": "allow"|"deny"|"ask",
///   "permissionDecisionReason": "...", "updatedInput": {...}}}` — because a
///   hook someone already wrote for CC should work here unchanged (this is
///   the compatibility layer's whole job).
/// * The same keys at the top level, plus the shorter spellings
///   `decision` / `reason` / `updated_args`.
///
/// Anything that is not a JSON object (the overwhelmingly common case: no
/// output at all, or a log line) is [`HookDecision::Pass`] — a hook that
/// exits 0 and says nothing means what it always meant.
fn parse_pre_tool_stdout(stdout: &str) -> PreToolOutcome {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(stdout) else {
        return PreToolOutcome::pass();
    };
    let Some(obj) = value.as_object() else {
        return PreToolOutcome::pass();
    };
    let specific = obj.get("hookSpecificOutput").and_then(|v| v.as_object());
    let field = |name: &str, alt: &str| -> Option<serde_json::Value> {
        specific
            .and_then(|o| o.get(name))
            .or_else(|| obj.get(name))
            .or_else(|| specific.and_then(|o| o.get(alt)))
            .or_else(|| obj.get(alt))
            .cloned()
    };
    let decision = match field("permissionDecision", "decision")
        .as_ref()
        .and_then(|v| v.as_str())
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        Some("allow") => HookDecision::Allow,
        Some("ask") => HookDecision::Ask,
        Some("deny") => HookDecision::Deny,
        // An unrecognized verdict is not a silent allow: it is no opinion,
        // and the engine's own rules decide.
        _ => HookDecision::Pass,
    };
    PreToolOutcome {
        decision,
        reason: field("permissionDecisionReason", "reason")
            .as_ref()
            .and_then(|v| v.as_str())
            .map(str::to_string),
        updated_args: field("updatedInput", "updated_args").filter(serde_json::Value::is_object),
    }
}

/// P4b (design §5.2 "P4", §1.9/§2 module 17): fire the `stop` GATING hook —
/// the declarative form of `supercode-harness`'s single `Config::stop_gate`
/// slot (CC Stop-hook semantics cc§3). Returns `None` to ALLOW the loop to
/// terminate, or `Some(reason)` to VETO termination — `reason` is injected
/// as a new user message and the loop continues (`crate::agent::Agent::run_loop`'s
/// contract for `Config::stop_gate`). A no-op (`None`) if `stop` has no
/// command configured (requirement 1).
///
/// **Never double-fires with a hand-installed code-level gate** (the §2
/// module 17 note): `Config::stop_gate` is exactly ONE `Option` slot on
/// `Config` — whoever builds the `Config` (here, `build_config`) installs
/// AT MOST one closure into it. This function is only ever wired in as
/// THAT closure (see `build_config`), never registered alongside a second,
/// independent call site — so "hooks layer on core's gate" is true by
/// construction (there is only one gate to layer onto), not by convention.
///
/// **Fails OPEN, unlike `fire_pre_tool`'s fail-CLOSED.** A `pre_tool` gate
/// exists to keep a possibly-dangerous action from happening; failing
/// closed (deny) on a broken hook is the safe default. A `stop` gate is the
/// opposite shape: failing CLOSED here would mean "deny the ability to
/// finish", forcing the loop to keep spending model calls/tokens on every
/// single turn a broken/timed-out hook script produces — a worse outcome
/// than just letting the turn end normally. A spawn error, a timeout, or an
/// unparseable exit therefore all ALLOW the stop (matching CC's own
/// behavior: a Stop-hook error is logged and the stop proceeds).
///
/// `final_content` (the would-be-final assistant message) is attached as an
/// env var, bounded like `pre_tool`'s `SUPERCODE_HOOK_TOOL_ARGS` — never
/// spliced into the command string (requirement 2).
pub fn fire_stop(hooks: &HookSet, final_content: &str, quiet: bool) -> Option<String> {
    let command = hooks.stop.as_ref()?;
    let extra_env: [(&str, String); 1] = [(
        "SUPERCODE_HOOK_STOP_CONTENT",
        final_content.chars().take(8_000).collect::<String>(),
    )];
    let outcome = run_hook(HookEvent::Stop, command, hooks.timeout_ms, &extra_env);
    report(HookEvent::Stop, &outcome, quiet);

    if outcome.spawn_error.is_some() || outcome.timed_out {
        // Fail OPEN — see the doc comment above.
        return None;
    }
    match outcome.exit_code {
        Some(0) | None => None,
        Some(code) => {
            let text = outcome.stdout.trim();
            let reason = if text.is_empty() {
                format!("stop hook vetoed (exit {code})")
            } else {
                text.to_string()
            };
            eprintln!("[hook:stop] vetoed termination: {reason}");
            Some(reason)
        }
    }
}

/// Resolve the [`HookSet`] for a session-level lifecycle event
/// (`session_start`/`session_end`) from `cwd`'s config — the exact same
/// source (`userconfig::load`, already project-sanitized) `build_config`
/// uses for `pre_tool`/`post_tool`, so all four events see one consistent,
/// opt-in configuration.
pub fn load_hook_set(cwd: &std::path::Path) -> HookSet {
    HookSet::resolve(&crate::userconfig::load(cwd).hooks)
}

/// Environment context attached to `session_start`/`session_end` invocations
/// (requirement 2: context via env, never spliced into the command string).
pub fn session_env(
    cwd: &std::path::Path,
    session_name: Option<&str>,
) -> Vec<(&'static str, String)> {
    let mut v = vec![("SUPERCODE_HOOK_CWD", cwd.to_string_lossy().into_owned())];
    if let Some(name) = session_name {
        v.push(("SUPERCODE_HOOK_SESSION", name.to_string()));
    }
    v
}