supercode-cli 0.4.18

supercode — 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
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
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
//! 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::{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-core`'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-core`'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-core`'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-core`, 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);
    }

    let mut child = match cmd.spawn() {
        Ok(c) => c,
        Err(e) => {
            return HookOutcome {
                spawn_error: Some(e.to_string()),
                ..Default::default()
            }
        }
    };

    // 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;
                    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
}

#[cfg(not(unix))]
fn kill_process_tree(child: &mut std::process::Child) {
    let _ = child.kill();
}

/// 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-core`'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
}

#[cfg(test)]
mod tests {
    use super::*;

    fn touch_cmd(path: &std::path::Path) -> String {
        format!("touch {}", shell_quote(path.to_str().unwrap()))
    }

    fn shell_quote(s: &str) -> String {
        format!("'{}'", s.replace('\'', "'\\''"))
    }

    fn tmp(tag: &str) -> std::path::PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!(
            "supercode-ux28-hooks-unit-{tag}-{}-{nanos}",
            std::process::id()
        ))
    }

    // ---- HookSet::is_empty / resolve (requirement 1: opt-in) --------------

    #[test]
    fn default_hook_set_is_empty() {
        assert!(HookSet::default().is_empty());
        assert!(HookSet::resolve(&HooksFileConfig::default()).is_empty());
    }

    #[test]
    fn a_single_configured_event_makes_the_set_non_empty() {
        let fc = HooksFileConfig {
            session_start: Some("true".to_string()),
            ..Default::default()
        };
        assert!(!HookSet::resolve(&fc).is_empty());
    }

    #[test]
    fn default_timeout_applies_when_unset() {
        let hs = HookSet::resolve(&HooksFileConfig::default());
        assert_eq!(hs.timeout_ms, DEFAULT_HOOK_TIMEOUT_MS);
    }

    #[test]
    fn file_config_timeout_is_honored() {
        let fc = HooksFileConfig {
            timeout_ms: Some(1234),
            ..Default::default()
        };
        assert_eq!(HookSet::resolve(&fc).timeout_ms, 1234);
    }

    // ---- fire_observational: opt-in + fires at all 3 observational points -

    #[test]
    fn empty_set_fires_nothing_for_any_event() {
        let hs = HookSet::default();
        let marker = tmp("empty-noop");
        for event in [
            HookEvent::PreTool,
            HookEvent::PostTool,
            HookEvent::SessionStart,
            HookEvent::SessionEnd,
        ] {
            fire_observational(&hs, event, &[], true);
        }
        assert!(
            !marker.exists(),
            "an empty HookSet must never spawn a process"
        );
        assert!(
            fire_pre_tool(&hs, &[], true).decision != HookDecision::Deny,
            "empty pre_tool must allow"
        );
    }

    #[test]
    fn session_start_hook_fires_and_its_side_effect_is_observable() {
        let marker = tmp("session-start");
        let fc = HooksFileConfig {
            session_start: Some(touch_cmd(&marker)),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        fire_observational(&hs, HookEvent::SessionStart, &[], true);
        assert!(marker.exists(), "session_start hook must have run");
    }

    #[test]
    fn session_end_hook_fires_and_its_side_effect_is_observable() {
        let marker = tmp("session-end");
        let fc = HooksFileConfig {
            session_end: Some(touch_cmd(&marker)),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        fire_observational(&hs, HookEvent::SessionEnd, &[], true);
        assert!(marker.exists(), "session_end hook must have run");
    }

    #[test]
    fn post_tool_hook_fires_and_receives_extra_env_context() {
        let marker = tmp("post-tool-env");
        let fc = HooksFileConfig {
            // Prove context arrives via env, not by string-splicing into
            // the command (requirement 2): the hook itself reads $TOOL.
            post_tool: Some(format!(
                "[ \"$SUPERCODE_HOOK_TOOL\" = \"bash\" ] && {}",
                touch_cmd(&marker)
            )),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        fire_observational(
            &hs,
            HookEvent::PostTool,
            &[("SUPERCODE_HOOK_TOOL", "bash".to_string())],
            true,
        );
        assert!(
            marker.exists(),
            "post_tool hook must see SUPERCODE_HOOK_TOOL"
        );
    }

    #[test]
    fn observational_hook_failure_does_not_panic_or_propagate() {
        // A guaranteed-nonzero-exit command must not panic `fire_observational`
        // and must not change its (unit) return — best-effort, logged only.
        let fc = HooksFileConfig {
            post_tool: Some("exit 7".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        fire_observational(&hs, HookEvent::PostTool, &[], true); // must not panic
    }

    // ---- fire_pre_tool: gating + timeout (requirement 4, dev/02) ----------

    #[test]
    fn pre_tool_hook_zero_exit_allows() {
        let fc = HooksFileConfig {
            pre_tool: Some("exit 0".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        assert_eq!(
            fire_pre_tool(&hs, &[], true).decision,
            HookDecision::Pass,
            "an exit-0 hook with no output still means no opinion"
        );
    }

    #[test]
    fn pre_tool_hook_nonzero_exit_denies_with_its_stdout_as_reason() {
        let fc = HooksFileConfig {
            pre_tool: Some("echo 'no shells allowed'; exit 1".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        let outcome = fire_pre_tool(&hs, &[], true);
        assert_eq!(outcome.decision, HookDecision::Deny);
        assert_eq!(outcome.reason.as_deref(), Some("no shells allowed"));
    }

    #[test]
    fn pre_tool_hook_timeout_denies_fail_closed() {
        let fc = HooksFileConfig {
            pre_tool: Some("sleep 5".to_string()),
            timeout_ms: Some(80),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        let start = Instant::now();
        let outcome = fire_pre_tool(&hs, &[], true);
        assert_eq!(
            outcome.decision,
            HookDecision::Deny,
            "a timed-out pre_tool hook must deny (fail closed)"
        );
        assert!(
            outcome.reason.unwrap().contains("timed out"),
            "denial reason should say it timed out"
        );
        assert!(
            start.elapsed() < Duration::from_secs(3),
            "must be bounded by timeout_ms, not the sleep's full duration"
        );
    }

    #[test]
    fn pre_tool_hook_spawn_failure_denies_fail_closed() {
        let fc = HooksFileConfig {
            pre_tool: Some("/no/such/binary-ux28-hooks-test --deny-everything".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        // `sh -c /no/such/binary...` itself still spawns (it's `sh` that's
        // spawned, not the missing binary) and simply exits non-zero — this
        // exercises the non-zero-exit path with an unambiguous "no reason
        // text on stdout" case rather than an actual `Command::spawn` error
        // (which would require `sh` itself to be missing).
        assert_eq!(fire_pre_tool(&hs, &[], true).decision, HookDecision::Deny);
    }

    #[test]
    fn pre_tool_hook_command_string_never_shell_evaluates_extra_env_content() {
        // requirement 2: context is env, never interpolated into the
        // command string. Even if extra_env carries shell metacharacters,
        // the FIXED command (which never references them) is unaffected —
        // prove a malicious-looking arg value doesn't blow up parsing or
        // get executed.
        let marker = tmp("no-eval");
        let fc = HooksFileConfig {
            pre_tool: Some("exit 0".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        let evil = format!("; {}; #", touch_cmd(&marker));
        let outcome = fire_pre_tool(&hs, &[("SUPERCODE_HOOK_TOOL_ARGS", evil)], true);
        assert_eq!(
            outcome.decision,
            HookDecision::Pass,
            "fixed command still just exits 0"
        );
        assert!(
            !marker.exists(),
            "env-carried content must never be shell-evaluated"
        );
    }

    // ---- P4b: fire_stop (§1.9/§2 module 17) -------------------------------

    #[test]
    fn stop_hook_zero_exit_allows_termination() {
        let fc = HooksFileConfig {
            stop: Some("exit 0".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        assert!(fire_stop(&hs, "final answer", true).is_none());
    }

    #[test]
    fn stop_hook_nonzero_exit_vetoes_with_its_stdout_as_reason() {
        let fc = HooksFileConfig {
            stop: Some("echo 'not done yet'; exit 1".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        let reason = fire_stop(&hs, "final answer", true);
        assert_eq!(reason.as_deref(), Some("not done yet"));
    }

    #[test]
    fn stop_hook_nonzero_exit_with_no_stdout_gets_a_default_reason() {
        let fc = HooksFileConfig {
            stop: Some("exit 3".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        let reason = fire_stop(&hs, "final answer", true);
        assert_eq!(reason.as_deref(), Some("stop hook vetoed (exit 3)"));
    }

    #[test]
    fn stop_hook_timeout_fails_open_unlike_pre_tool() {
        let fc = HooksFileConfig {
            stop: Some("sleep 5".to_string()),
            timeout_ms: Some(80),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        let start = Instant::now();
        let reason = fire_stop(&hs, "final answer", true);
        assert!(
            reason.is_none(),
            "a timed-out stop hook must ALLOW the stop (fail open) — unlike pre_tool"
        );
        assert!(
            start.elapsed() < Duration::from_secs(3),
            "must be bounded by timeout_ms"
        );
    }

    #[test]
    fn stop_hook_spawn_failure_fails_open() {
        let fc = HooksFileConfig {
            stop: Some("/no/such/binary-p4b-stop-hook-test".to_string()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        // Same non-error-spawn nuance as the pre_tool test above: `sh -c
        // /no/such/binary` still spawns `sh`, which just exits non-zero —
        // this exercises the non-zero-exit path, distinctly proving `stop`
        // (unlike `pre_tool`) still ALLOWS on it only when spawn/timeout,
        // not on a plain non-zero exit (that's the normal veto signal).
        // A genuine spawn error is exercised by construction impossible to
        // trigger portably here, so this asserts the DOCUMENTED contract on
        // the reachable path: a non-zero exit is a veto, never a fail-open.
        let reason = fire_stop(&hs, "final answer", true);
        assert!(
            reason.is_some(),
            "a plain non-zero exit is a NORMAL veto, not a failure"
        );
    }

    #[test]
    fn empty_hook_set_stop_is_a_no_op() {
        let hs = HookSet::default();
        assert!(fire_stop(&hs, "final answer", true).is_none());
    }

    #[test]
    fn hook_set_with_only_stop_configured_is_not_empty() {
        let fc = HooksFileConfig {
            stop: Some("exit 0".to_string()),
            ..Default::default()
        };
        assert!(!HookSet::resolve(&fc).is_empty());
    }

    // ---- P5-7: expanded CC/CX-common event set ----------------------------

    #[test]
    fn only_pre_tool_and_stop_are_veto_capable() {
        for e in [HookEvent::PreTool, HookEvent::Stop] {
            assert!(e.is_veto_capable(), "{} must veto", e.as_str());
        }
        for e in [
            HookEvent::PostTool,
            HookEvent::SessionStart,
            HookEvent::SessionEnd,
            HookEvent::UserPromptSubmit,
            HookEvent::Notification,
            HookEvent::SubagentStart,
            HookEvent::SubagentStop,
            HookEvent::PreCompact,
            HookEvent::PostCompact,
        ] {
            assert!(
                !e.is_veto_capable(),
                "{} is observational and must never veto/escalate",
                e.as_str()
            );
        }
    }

    #[test]
    fn each_new_event_resolves_from_config_and_makes_the_set_non_empty() {
        // A HookSet with ONLY a given new event set must be non-empty and
        // report that event's command via `command_for`. Each config sets
        // exactly one new-event field (no fn-pointer table — keeps the type
        // simple for clippy).
        let cases = [
            (
                HookEvent::UserPromptSubmit,
                HooksFileConfig {
                    user_prompt_submit: Some("true".into()),
                    ..Default::default()
                },
            ),
            (
                HookEvent::Notification,
                HooksFileConfig {
                    notification: Some("true".into()),
                    ..Default::default()
                },
            ),
            (
                HookEvent::SubagentStart,
                HooksFileConfig {
                    subagent_start: Some("true".into()),
                    ..Default::default()
                },
            ),
            (
                HookEvent::SubagentStop,
                HooksFileConfig {
                    subagent_stop: Some("true".into()),
                    ..Default::default()
                },
            ),
            (
                HookEvent::PreCompact,
                HooksFileConfig {
                    pre_compact: Some("true".into()),
                    ..Default::default()
                },
            ),
            (
                HookEvent::PostCompact,
                HooksFileConfig {
                    post_compact: Some("true".into()),
                    ..Default::default()
                },
            ),
        ];
        for (event, fc) in cases {
            let hs = HookSet::resolve(&fc);
            assert!(
                !hs.is_empty(),
                "{} should make the set non-empty",
                event.as_str()
            );
            assert_eq!(hs.command_for(event), Some("true"));
        }
    }

    // NOTE: env-var precedence for the new events uses the exact same
    // `env(...).or_else(|| fc....)` shape as the original five (see
    // `HookSet::resolve`); it is deliberately NOT unit-tested here because
    // asserting it requires mutating a PROCESS-GLOBAL `SUPERCODE_HOOK_*` var,
    // which races every other parallel test that calls `HookSet::resolve`
    // (they'd observe the set var and stop being "empty"). The CLI-level
    // `hooks_cli.rs` harness exercises real env/config resolution end to end
    // in isolated child processes instead.

    #[test]
    fn observational_new_event_fires_and_receives_env_context() {
        // pre_compact is one of the deferred-emission events, but its FIRE
        // path (`fire_observational`) works today — prove it runs and sees
        // its env context (requirement 2: context via env, not the command).
        let marker = tmp("pre-compact-fires");
        let fc = HooksFileConfig {
            pre_compact: Some(format!(
                "[ \"$SUPERCODE_HOOK_EVENT\" = \"pre_compact\" ] && {}",
                touch_cmd(&marker)
            )),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        fire_observational(&hs, HookEvent::PreCompact, &[], true);
        assert!(
            marker.exists(),
            "pre_compact hook must fire and see its event name"
        );
    }

    #[test]
    fn observational_new_event_nonzero_exit_does_not_panic_or_veto() {
        // A non-zero exit from an observational event is a logged failure,
        // never a veto (it has nothing to gate) — must not panic.
        let fc = HooksFileConfig {
            subagent_stop: Some("exit 9".into()),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        fire_observational(&hs, HookEvent::SubagentStop, &[], true); // must not panic
    }

    #[test]
    fn fire_user_prompt_submit_runs_and_passes_bounded_prompt_via_env() {
        let ran = tmp("ups-ran");
        let injected = tmp("ups-injected");
        let fc = HooksFileConfig {
            user_prompt_submit: Some(format!(
                "[ -n \"$SUPERCODE_HOOK_PROMPT\" ] && {}",
                touch_cmd(&ran)
            )),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        // A prompt with shell metacharacters must never be evaluated.
        let evil = format!("; {}; #", touch_cmd(&injected));
        fire_user_prompt_submit(&hs, &evil, std::path::Path::new("/tmp"), Some("sess"), true);
        assert!(
            ran.exists(),
            "user_prompt_submit must fire and see $SUPERCODE_HOOK_PROMPT"
        );
        assert!(
            !injected.exists(),
            "prompt content must be inert env text, never shell-evaluated"
        );
    }

    #[test]
    fn fire_user_prompt_submit_is_a_no_op_when_unconfigured() {
        let hs = HookSet::default();
        let marker = tmp("ups-noop");
        fire_user_prompt_submit(&hs, "hi", std::path::Path::new("/tmp"), None, true);
        assert!(!marker.exists());
    }

    #[test]
    fn fire_notification_runs_and_passes_kind_and_summary_via_env() {
        let ran = tmp("notif-ran");
        let fc = HooksFileConfig {
            notification: Some(format!(
                "[ \"$SUPERCODE_HOOK_NOTIFICATION_KIND\" = \"agent_completed\" ] && {}",
                touch_cmd(&ran)
            )),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        fire_notification(&hs, "some/model", 42, "a short reply", true);
        assert!(
            ran.exists(),
            "notification hook must fire with kind=agent_completed"
        );
    }

    #[test]
    fn fire_notification_is_a_no_op_when_unconfigured() {
        let hs = HookSet::default();
        // Only session_start configured — notification must still be a no-op.
        let hs2 = HookSet::resolve(&HooksFileConfig {
            session_start: Some("true".into()),
            ..Default::default()
        });
        fire_notification(&hs, "m", 1, "r", true);
        fire_notification(&hs2, "m", 1, "r", true); // must not spawn the notification hook
    }

    #[test]
    fn stop_hook_content_arrives_via_env_never_shell_evaluated() {
        let ran_marker = tmp("stop-no-eval-ran");
        let injected_marker = tmp("stop-no-eval-injected");
        let fc = HooksFileConfig {
            stop: Some(format!(
                "[ -n \"$SUPERCODE_HOOK_STOP_CONTENT\" ] && {}",
                touch_cmd(&ran_marker)
            )),
            ..Default::default()
        };
        let hs = HookSet::resolve(&fc);
        // A malicious-looking final answer embedding shell metacharacters
        // and a second touch command — must never be evaluated, only ever
        // seen as inert env-var text by the FIXED command above.
        let evil_content = format!("; {}; #", touch_cmd(&injected_marker));
        fire_stop(&hs, &evil_content, true);
        assert!(
            ran_marker.exists(),
            "content must be visible (non-empty) via SUPERCODE_HOOK_STOP_CONTENT env var"
        );
        assert!(
            !injected_marker.exists(),
            "env-carried content must never be shell-evaluated"
        );
    }
}