supercode-cli 0.4.6

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
//! CLI-level acceptance tests for UX-28 (config-driven lifecycle hooks):
//!
//! - dev/01: a `[hooks]` config registers external commands for
//!   `pre_tool`/`post_tool`/`session_start`/`session_end` and each fires at
//!   the right lifecycle point, in the right order.
//! - dev/02: a `pre_tool` hook can block a tool call (non-zero exit OR
//!   timeout), the reason reaches the model/transcript, and a
//!   failed/timed-out hook never crashes the run or corrupts the session.
//! - dev/03: no `[hooks]` configured = zero behavior change (no process
//!   ever spawned).
//! - Security bar (not just the tracker AC): stdout stays byte-clean
//!   (text AND `--output-format json`) regardless of what a hook prints;
//!   `--quiet` suppresses a successful hook's own chrome but never
//!   suppresses failure/timeout/deny reporting.
//!
//! Same idiom as `trace_stream_json_cli.rs`/`quiet_cli.rs`: spawns the real,
//! built `supercode` binary (fake `$SUPERCODE_HOME`) against a real local
//! HTTP/SSE stub — the CLI, the `Agent`'s `pre_tool_hook`/`post_tool_hook`
//! wiring, and `hooks.rs`'s process spawning are all the genuine,
//! unmodified binary, not a reimplementation.

use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};

fn bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_supercode"))
}

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

fn drain_request(sock: &mut std::net::TcpStream) -> String {
    sock.set_read_timeout(Some(Duration::from_millis(200)))
        .expect("set read timeout");
    let mut buf = Vec::new();
    let mut chunk = [0u8; 65536];
    loop {
        match sock.read(&mut chunk) {
            Ok(0) => break,
            Ok(n) => buf.extend_from_slice(&chunk[..n]),
            Err(e)
                if e.kind() == std::io::ErrorKind::WouldBlock
                    || e.kind() == std::io::ErrorKind::TimedOut =>
            {
                break
            }
            Err(_) => break,
        }
    }
    sock.set_read_timeout(None).expect("clear read timeout");
    String::from_utf8_lossy(&buf).into_owned()
}

fn write_sse(sock: &mut std::net::TcpStream, sse: &str) {
    let resp = format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
        sse.len(),
        sse
    );
    sock.write_all(resp.as_bytes())
        .expect("write stub response");
    sock.flush().ok();
}

/// A one-shot local HTTP/SSE server: a single plain-text reply, no tool call.
fn spawn_text_stub(text: &str) -> (std::net::SocketAddr, std::thread::JoinHandle<()>) {
    let listener = TcpListener::bind("127.0.0.1:0").expect("bind stub listener");
    let addr = listener.local_addr().unwrap();
    let text = text.to_string();
    let handle = std::thread::spawn(move || {
        let (mut sock, _) = listener.accept().expect("accept one connection");
        drain_request(&mut sock);
        let sse = format!(
            "data: {{\"choices\":[{{\"delta\":{{\"content\":{}}}}}]}}\n\n\
             data: [DONE]\n\n",
            serde_json::to_string(&text).unwrap()
        );
        write_sse(&mut sock, &sse);
    });
    (addr, handle)
}

/// Two round trips: round 1 asks for `tool_name(tool_args)`; the CLI runs
/// (or a `pre_tool` hook denies) it locally and sends the result back in
/// round 2's request, which this stub captures verbatim and hands back over
/// `rx` before replying with a plain "done". Mirrors
/// `trace_stream_json_cli.rs::spawn_tool_round_trip_stub`, extended to
/// capture round 2's request body so a test can inspect exactly what the
/// model was told about the tool call (e.g. a denial reason).
fn spawn_tool_round_trip_stub(
    tool_name: &str,
    tool_args_json: &str,
) -> (
    std::net::SocketAddr,
    std::thread::JoinHandle<()>,
    mpsc::Receiver<String>,
) {
    let listener = TcpListener::bind("127.0.0.1:0").expect("bind stub listener");
    let addr = listener.local_addr().unwrap();
    let (tx, rx) = mpsc::channel();
    let tool_name = tool_name.to_string();
    let tool_args_json = tool_args_json.to_string();
    let handle = std::thread::spawn(move || {
        let (mut sock, _) = listener.accept().expect("accept round-trip 1");
        drain_request(&mut sock);
        let escaped_args = tool_args_json.replace('"', "\\\"");
        let sse = format!(
            "data: {{\"choices\":[{{\"delta\":{{\"tool_calls\":[{{\"index\":0,\"id\":\"call_1\",\"function\":{{\"name\":\"{tool_name}\",\"arguments\":\"{escaped_args}\"}}}}]}}}}]}}\n\n\
             data: {{\"choices\":[{{\"delta\":{{}}}}],\"usage\":{{\"prompt_tokens\":11,\"completion_tokens\":3,\"total_tokens\":14}}}}\n\n\
             data: [DONE]\n\n"
        );
        write_sse(&mut sock, &sse);
        drop(sock);

        let (mut sock, _) = listener.accept().expect("accept round-trip 2");
        let body = drain_request(&mut sock);
        let _ = tx.send(body);
        let sse = "data: {\"choices\":[{\"delta\":{\"content\":\"done\"}}]}\n\n\
                   data: [DONE]\n\n";
        write_sse(&mut sock, sse);
    });
    (addr, handle, rx)
}

/// Write a `[hooks]` config.toml directly under `SUPERCODE_HOME` (`config_home()`
/// resolves to `$SUPERCODE_HOME` verbatim when set — see `userconfig::config_home`).
fn write_hooks_config(home: &Path, body: &str) {
    std::fs::write(home.join("config.toml"), body).expect("write config.toml");
}

fn run_piped(home: &Path, base_url: &str, extra: &[&str], envs: &[(&str, &str)]) -> Output {
    let mut args = vec!["--api-key", "x", "--base-url", base_url];
    args.extend_from_slice(extra);
    let mut cmd = Command::new(bin());
    cmd.env("SUPERCODE_HOME", home)
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .env_remove("NO_COLOR")
        .env_remove("SUPERCODE_QUIET")
        // The full `SUPERCODE_HOOK_*` surface (`HooksFileConfig`'s fields,
        // `hooks::HookSet::resolve`'s env overlay) — not just the original
        // five — so an ambient dev-env hook var (e.g. a developer's own
        // shell exporting `SUPERCODE_HOOK_NOTIFICATION` for local use) can
        // never leak into a test and flake it (LOW-1, P5-7 review).
        .env_remove("SUPERCODE_HOOK_PRE_TOOL")
        .env_remove("SUPERCODE_HOOK_POST_TOOL")
        .env_remove("SUPERCODE_HOOK_SESSION_START")
        .env_remove("SUPERCODE_HOOK_SESSION_END")
        .env_remove("SUPERCODE_HOOK_STOP")
        .env_remove("SUPERCODE_HOOK_USER_PROMPT_SUBMIT")
        .env_remove("SUPERCODE_HOOK_NOTIFICATION")
        .env_remove("SUPERCODE_HOOK_SUBAGENT_START")
        .env_remove("SUPERCODE_HOOK_SUBAGENT_STOP")
        .env_remove("SUPERCODE_HOOK_PRE_COMPACT")
        .env_remove("SUPERCODE_HOOK_POST_COMPACT")
        .env_remove("SUPERCODE_HOOK_TIMEOUT_MS");
    for (k, v) in envs {
        cmd.env(k, v);
    }
    cmd.args(&args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to spawn the supercode binary")
        .wait_with_output()
        .expect("child process failed")
}

fn stdout(out: &Output) -> String {
    String::from_utf8_lossy(&out.stdout).into_owned()
}
fn stderr(out: &Output) -> String {
    String::from_utf8_lossy(&out.stderr).into_owned()
}

// ---- dev/01: fires at the right lifecycle point, in order -----------------

#[test]
fn dev01_all_four_events_fire_in_lifecycle_order_and_stdout_stays_clean() {
    let home = fresh_home("order");
    let log = home.join("hooks.log");
    write_hooks_config(
        &home,
        r#"
[hooks]
session_start = "echo session_start >> $HOOKS_LOG"
pre_tool = "echo \"pre_tool $SUPERCODE_HOOK_TOOL\" >> $HOOKS_LOG; exit 0"
post_tool = "echo \"post_tool $SUPERCODE_HOOK_TOOL\" >> $HOOKS_LOG"
session_end = "echo session_end >> $HOOKS_LOG"
timeout_ms = 5000
"#,
    );
    let (addr, server, _rx) = spawn_tool_round_trip_stub("list_dir", "{}");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &[
            "--disallow-tool",
            "bash",
            "--disallow-tool",
            "shell",
            "run",
            "list the dir",
        ],
        &[("HOOKS_LOG", log.to_str().unwrap())],
    );
    server.join().expect("stub thread panicked");

    assert!(
        out.status.success(),
        "run failed: status={:?} stdout={} stderr={}",
        out.status,
        stdout(&out),
        stderr(&out)
    );
    assert_eq!(
        stdout(&out).trim(),
        "done",
        "stdout must be exactly the model's reply — no hook chrome, got: {}",
        stdout(&out)
    );

    let log_text = std::fs::read_to_string(&log).unwrap_or_default();
    let lines: Vec<&str> = log_text.lines().collect();
    assert_eq!(
        lines,
        vec![
            "session_start",
            "pre_tool list_dir",
            "post_tool list_dir",
            "session_end"
        ],
        "hooks must fire in exactly this lifecycle order, got: {log_text:?}"
    );
}

// ---- dev/02: pre_tool gates a call (non-zero exit), doesn't crash --------

#[test]
fn dev02_pre_tool_hook_denies_a_call_reason_reaches_the_model_and_run_still_succeeds() {
    let home = fresh_home("deny");
    let marker = home.join("pre-tool-ran.marker");
    write_hooks_config(
        &home,
        r#"
[hooks]
pre_tool = "touch $MARKER; echo 'no shells allowed' >&2; exit 1"
"#,
    );
    let (addr, server, rx) = spawn_tool_round_trip_stub("bash", "{\"command\":\"ls\"}");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["run", "list files"],
        &[("MARKER", marker.to_str().unwrap())],
    );
    server.join().expect("stub thread panicked");

    assert!(
        out.status.success(),
        "a denied tool call must NOT crash the run: status={:?} stdout={} stderr={}",
        out.status,
        stdout(&out),
        stderr(&out)
    );
    assert!(marker.exists(), "the pre_tool hook must actually have run");
    assert_eq!(
        stdout(&out).trim(),
        "done",
        "the run must still complete normally after the denial"
    );
    // The hook's own stderr diagnostic is reported, never on stdout.
    assert!(
        stderr(&out).contains("[hook:pre_tool] denied"),
        "a denial must be reported on stderr, got: {}",
        stderr(&out)
    );
    assert!(
        !stdout(&out).contains("[hook:"),
        "hook chrome must never reach stdout, got: {}",
        stdout(&out)
    );
    // The actual `bash` tool never ran — the model's next request carries a
    // blocked-by-hook tool result, not real `ls` output.
    let round2_body = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("round 2 request");
    assert!(
        round2_body.contains("blocked by pre-tool hook"),
        "round-2 request must show the call was blocked, got: {round2_body}"
    );
}

// ---- dev/02: pre_tool timeout also denies (fail-closed), doesn't hang ----

#[test]
fn dev02_pre_tool_hook_timeout_denies_and_stays_bounded() {
    let home = fresh_home("timeout");
    write_hooks_config(
        &home,
        r#"
[hooks]
pre_tool = "sleep 5"
timeout_ms = 200
"#,
    );
    let (addr, server, rx) = spawn_tool_round_trip_stub("bash", "{\"command\":\"ls\"}");

    let start = Instant::now();
    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["run", "list files"],
        &[],
    );
    let elapsed = start.elapsed();
    server.join().expect("stub thread panicked");

    assert!(
        out.status.success(),
        "a timed-out pre_tool hook must NOT crash the run: status={:?} stderr={}",
        out.status,
        stderr(&out)
    );
    assert!(
        elapsed < Duration::from_secs(4),
        "the run must be bounded by timeout_ms (200ms), not the hook's 5s sleep; took {elapsed:?}"
    );
    assert!(
        stderr(&out).contains("timed out"),
        "the timeout must be reported on stderr, got: {}",
        stderr(&out)
    );
    let round2_body = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("round 2 request");
    assert!(
        round2_body.contains("blocked by pre-tool hook"),
        "a timed-out pre_tool hook must fail CLOSED (deny), got round-2 body: {round2_body}"
    );
}

// ---- dev/03: no [hooks] configured = zero behavior change -----------------

#[test]
fn dev03_no_hooks_configured_means_nothing_ever_spawns() {
    let home = fresh_home("empty");
    // No config.toml written at all — the common case.
    let (addr, server, rx) = spawn_tool_round_trip_stub("list_dir", "{}");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["run", "list the dir"],
        &[],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert_eq!(stdout(&out).trim(), "done");
    // The tool call went through for real (not denied) — proves the
    // (unconfigured) pre_tool hook never ran, since it would have needed a
    // command to deny with.
    let round2_body = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("round 2 request");
    assert!(
        !round2_body.contains("blocked by pre-tool hook"),
        "with no [hooks] configured nothing may be denied, got: {round2_body}"
    );
    assert!(
        !stderr(&out).contains("[hook:"),
        "with no [hooks] configured, no hook diagnostic of any kind may appear, got: {}",
        stderr(&out)
    );
}

/// Same as above, but ALSO proves it holds for a project-local
/// `.supercode.toml` carrying `[hooks]` — UX-28's own security rule
/// (`sanitized_for_project`) strips it, so opening an untrusted repo must
/// not silently register a hook either.
#[test]
fn dev03_project_local_hooks_config_is_ignored() {
    let home = fresh_home("project-ignored");
    let project_dir = home.join("untrusted-repo");
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(
        project_dir.join(".supercode.toml"),
        "[hooks]\npre_tool = \"exit 1\"\n",
    )
    .unwrap();
    let (addr, server, rx) = spawn_tool_round_trip_stub("list_dir", "{}");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &[
            "--cwd",
            project_dir.to_str().unwrap(),
            "run",
            "list the dir",
        ],
        &[],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    let round2_body = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("round 2 request");
    assert!(
        !round2_body.contains("blocked by pre-tool hook"),
        "a project-local .supercode.toml must NEVER be able to register a hook, got: {round2_body}"
    );
    assert!(
        stderr(&out).contains("ignoring untrusted field(s)") && stderr(&out).contains("hooks"),
        "the existing untrusted-project-config warning must name `hooks`, got: {}",
        stderr(&out)
    );
}

// ---- --quiet: chrome suppressed, failures/denials never suppressed --------

#[test]
fn quiet_suppresses_successful_hook_chrome_but_not_failure_diagnostics() {
    let home = fresh_home("quiet");
    write_hooks_config(
        &home,
        r#"
[hooks]
session_start = "echo 'hello from a happy hook'"
session_end = "echo bye-broken >&2; exit 3"
"#,
    );
    let (addr, server) = spawn_text_stub("hi there");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["--quiet", "run", "say hi"],
        &[],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert_eq!(stdout(&out).trim(), "hi there");
    assert!(
        !stderr(&out).contains("hello from a happy hook"),
        "--quiet must suppress a SUCCESSFUL hook's own chrome, got: {}",
        stderr(&out)
    );
    assert!(
        stderr(&out).contains("[hook:session_end] exited 3"),
        "--quiet must NOT suppress a FAILING hook's diagnostic, got: {}",
        stderr(&out)
    );
}

// ---- P5-7: user_prompt_submit fires live at the pre-turn point ------------

#[test]
fn p57_user_prompt_submit_fires_after_session_start_before_pre_tool_with_prompt() {
    let home = fresh_home("ups-order");
    let log = home.join("hooks.log");
    write_hooks_config(
        &home,
        r#"
[hooks]
session_start = "echo session_start >> $HOOKS_LOG"
user_prompt_submit = "echo \"user_prompt_submit $SUPERCODE_HOOK_PROMPT\" >> $HOOKS_LOG"
pre_tool = "echo pre_tool >> $HOOKS_LOG; exit 0"
post_tool = "echo post_tool >> $HOOKS_LOG"
session_end = "echo session_end >> $HOOKS_LOG"
timeout_ms = 5000
"#,
    );
    let (addr, server, _rx) = spawn_tool_round_trip_stub("list_dir", "{}");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &[
            "--disallow-tool",
            "bash",
            "--disallow-tool",
            "shell",
            "run",
            "list the dir",
        ],
        &[("HOOKS_LOG", log.to_str().unwrap())],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert_eq!(stdout(&out).trim(), "done", "stdout must stay clean");
    let log_text = std::fs::read_to_string(&log).unwrap_or_default();
    let lines: Vec<&str> = log_text.lines().collect();
    assert_eq!(
        lines,
        vec![
            "session_start",
            "user_prompt_submit list the dir",
            "pre_tool",
            "post_tool",
            "session_end",
        ],
        "user_prompt_submit must fire after session_start, before the tool call, and carry \
         the prompt via env; got: {log_text:?}"
    );
}

// ---- P5-7: notification fires live at turn-finish -------------------------

#[test]
fn p57_notification_hook_fires_on_turn_finish_with_agent_completed_kind() {
    let home = fresh_home("notif");
    let log = home.join("hooks.log");
    write_hooks_config(
        &home,
        r#"
[hooks]
notification = "echo \"notification $SUPERCODE_HOOK_NOTIFICATION_KIND $SUPERCODE_HOOK_MODEL\" >> $HOOKS_LOG"
"#,
    );
    let (addr, server) = spawn_text_stub("hi there");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["run", "say hi"],
        &[("HOOKS_LOG", log.to_str().unwrap())],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert_eq!(stdout(&out).trim(), "hi there", "stdout must stay clean");
    let log_text = std::fs::read_to_string(&log).unwrap_or_default();
    assert!(
        log_text.contains("notification agent_completed"),
        "the notification hook must fire at turn-finish with kind=agent_completed, got: {log_text:?}"
    );
}

// ---- P5-7: a project-local NEW-event hook is stripped too -----------------

#[test]
fn p57_project_local_new_event_hooks_are_ignored() {
    let home = fresh_home("p57-project-ignored");
    let log = home.join("hooks.log");
    let project_dir = home.join("untrusted-repo");
    std::fs::create_dir_all(&project_dir).unwrap();
    // A hostile repo tries to register the NEW events (not just the old ones).
    std::fs::write(
        project_dir.join(".supercode.toml"),
        "[hooks]\nuser_prompt_submit = \"echo pwned >> $HOOKS_LOG\"\nsubagent_stop = \"echo pwned2 >> $HOOKS_LOG\"\nnotification = \"echo pwned3 >> $HOOKS_LOG\"\n",
    )
    .unwrap();
    let (addr, server) = spawn_text_stub("hi");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["--cwd", project_dir.to_str().unwrap(), "run", "say hi"],
        &[("HOOKS_LOG", log.to_str().unwrap())],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert!(
        !log.exists(),
        "a project-local .supercode.toml must NEVER register ANY hook (old or new event); \
         the log file was created, meaning a stripped hook ran"
    );
    assert!(
        stderr(&out).contains("ignoring untrusted field(s)") && stderr(&out).contains("hooks"),
        "the untrusted-project-config warning must name `hooks`, got: {}",
        stderr(&out)
    );
}

// ---- --output-format json stays byte-clean even with noisy hooks ----------

#[test]
fn json_output_stays_byte_clean_even_with_a_noisy_pre_tool_hook() {
    let home = fresh_home("json-clean");
    write_hooks_config(
        &home,
        r#"
[hooks]
pre_tool = "echo 'NOISE ON STDOUT FROM THE HOOK'; exit 0"
post_tool = "echo 'MORE NOISE' >&2"
"#,
    );
    let (addr, server, _rx) = spawn_tool_round_trip_stub("list_dir", "{}");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["run", "--output-format", "json", "list the dir"],
        &[],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    let text = stdout(&out);
    let parsed: serde_json::Value = serde_json::from_str(text.trim()).unwrap_or_else(|e| {
        panic!("stdout must be exactly one JSON envelope: {e}\nstdout: {text}")
    });
    assert!(parsed.is_object(), "expected a JSON object envelope");
    assert!(
        !text.contains("NOISE"),
        "a hook's own stdout must never reach --output-format json's stdout, got: {text}"
    );
}

// ---- LOW-2 (P5-7 review): real env-var-override e2e proof -----------------
//
// The prior commit (f1b18a5) claimed `hooks_cli.rs` exercises env-var
// override end to end; it didn't — it only `env_remove`d the vars. This test
// makes that claim true: it spawns the real binary (a fresh child process,
// so no process-global env mutation in the test harness itself — the exact
// hazard that sank the earlier in-process unit-test attempt) with
// `SUPERCODE_HOOK_NOTIFICATION` set to a marker command distinct from the
// config file's own `notification` command, and proves the env value wins.

#[test]
fn env_var_hook_command_fires_and_overrides_the_config_file_value() {
    let home = fresh_home("env-override");
    let config_marker = home.join("config-notification.marker");
    let env_marker = home.join("env-notification.marker");
    write_hooks_config(
        &home,
        &format!(
            "[hooks]\nnotification = \"touch {}\"\n",
            config_marker.to_str().unwrap()
        ),
    );
    let (addr, server) = spawn_text_stub("hi there");

    let env_cmd = format!("touch {}", env_marker.to_str().unwrap());
    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["run", "say hi"],
        &[("SUPERCODE_HOOK_NOTIFICATION", env_cmd.as_str())],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert!(
        env_marker.exists(),
        "SUPERCODE_HOOK_NOTIFICATION must fire, proving env-var hook resolution works end to end"
    );
    assert!(
        !config_marker.exists(),
        "the env var must WIN over the config file's notification command (env > file precedence)"
    );
}

// ---- MEDIUM (P5-7 review): deferred-event no-op warning -------------------
//
// `subagent_start`/`subagent_stop`/`pre_compact`/`post_compact` are
// config-registerable and trust-gated today but their emission sites are
// deferred to later units (see `hooks.rs`'s module doc). Registering one of
// them must never be a SILENT no-op — the user gets exactly one stderr
// notice naming the event, and the 7 live events / an unconfigured
// `[hooks]` table must never trigger it.

#[test]
fn deferred_event_registered_via_config_emits_one_time_stderr_warning() {
    let home = fresh_home("deferred-warn-config");
    write_hooks_config(&home, "[hooks]\npre_compact = \"true\"\n");
    let (addr, server) = spawn_text_stub("hi there");

    let out = run_piped(&home, &format!("http://{addr}"), &["run", "say hi"], &[]);
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    let err = stderr(&out);
    assert!(
        err.contains("pre_compact is registered but is not yet emitted"),
        "registering a deferred event must warn once naming it, got: {err}"
    );
    let occurrences = err
        .matches("pre_compact is registered but is not yet emitted")
        .count();
    assert_eq!(
        occurrences, 1,
        "the warning must fire exactly once per process (not once per HookSet::resolve call, \
         which happens repeatedly across session_start/session_end/each turn), got stderr: {err}"
    );
}

#[test]
fn deferred_event_registered_via_env_var_also_warns() {
    let home = fresh_home("deferred-warn-env");
    let (addr, server) = spawn_text_stub("hi there");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["run", "say hi"],
        &[("SUPERCODE_HOOK_SUBAGENT_STOP", "true")],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert!(
        stderr(&out).contains("subagent_stop is registered but is not yet emitted"),
        "an env-var-registered deferred event must also warn, got: {}",
        stderr(&out)
    );
}

#[test]
fn live_events_never_emit_the_deferred_no_op_warning() {
    let home = fresh_home("deferred-warn-live-events");
    write_hooks_config(
        &home,
        r#"
[hooks]
session_start = "true"
session_end = "true"
pre_tool = "exit 0"
post_tool = "true"
stop = "exit 0"
user_prompt_submit = "true"
notification = "true"
"#,
    );
    let (addr, server, _rx) = spawn_tool_round_trip_stub("list_dir", "{}");

    let out = run_piped(
        &home,
        &format!("http://{addr}"),
        &["run", "list the dir"],
        &[],
    );
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert!(
        !stderr(&out).contains("is registered but is not yet emitted"),
        "none of the 7 LIVE events may ever trigger the deferred-no-op warning, got: {}",
        stderr(&out)
    );
}

#[test]
fn unconfigured_hooks_produce_zero_deferred_warning_stderr() {
    let home = fresh_home("deferred-warn-unconfigured");
    // No config.toml at all — default-off must stay byte-identical: zero new
    // stderr from the deferred-event warning path.
    let (addr, server) = spawn_text_stub("hi there");

    let out = run_piped(&home, &format!("http://{addr}"), &["run", "say hi"], &[]);
    server.join().expect("stub thread panicked");

    assert!(out.status.success(), "stderr={}", stderr(&out));
    assert!(
        !stderr(&out).contains("is registered but is not yet emitted"),
        "an unconfigured [hooks] table must produce zero deferred-warning stderr, got: {}",
        stderr(&out)
    );
}