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
//! CLI-level acceptance tests for TR-9 (T24): `supercode handoff <session>
//! --keep ... --objective ...`.
//!
//! Follows `reductions_cli.rs`'s idiom: spawn the built `supercode` binary
//! against an unreachable `--base-url` with a dummy API key and a fresh,
//! isolated `$SUPERCODE_HOME` per test. `handoff` (like `show-reductions`/
//! `convert`/`inspect`) never touches the network at all.
//!
//! Fixture construction: rather than going through the Claude Code/Codex
//! JSONL importer (whose fixtures rarely carry a leading system-role
//! message), this mints a store session directly with a LIVE `Agent` +
//! `SidecarWriter` + a scripted, in-process `Provider` — the same idiom
//! `tr7_summary_guarantor.rs`/`tr6_supersede_guarantor.rs` already use in the
//! core crate. No real network call anywhere.

use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicUsize, Ordering};

use async_trait::async_trait;
use supercode::session::Session;
use supercode::sidecar::SidecarWriter;
use supercode::store::SessionStore;
use supercode::{Agent, ChatMessage, ChatRequest, Config, Provider, Usage};

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-tr9-handoff-{tag}-{}-{nanos}",
        std::process::id()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn run(home: &Path, extra: &[&str]) -> Output {
    run_with_stdin(home, extra, None)
}

fn run_with_stdin(home: &Path, extra: &[&str], stdin: Option<&str>) -> Output {
    run_with_stdin_in(home, None, extra, stdin)
}

fn run_with_stdin_in(
    home: &Path,
    cwd: Option<&Path>,
    extra: &[&str],
    stdin: Option<&str>,
) -> Output {
    use std::io::Write;

    let mut args = vec!["--api-key", "x", "--base-url", "http://127.0.0.1:1"];
    args.extend_from_slice(extra);
    let mut command = Command::new(bin());
    command
        .env("SUPERCODE_HOME", home)
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .args(&args);
    if let Some(cwd) = cwd {
        command.current_dir(cwd);
    }
    let mut child = command
        .stdin(if stdin.is_some() {
            std::process::Stdio::piped()
        } else {
            std::process::Stdio::null()
        })
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("failed to run the supercode binary");
    if let Some(input) = stdin {
        child
            .stdin
            .as_mut()
            .unwrap()
            .write_all(input.as_bytes())
            .unwrap();
    }
    child.wait_with_output().expect("supercode 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()
}

fn sessions_dir(home: &Path) -> PathBuf {
    home.join("sessions")
}

fn filler(len: usize) -> String {
    (0..len).map(|i| (b'a' + (i % 26) as u8) as char).collect()
}

/// Every turn: a plain text reply padded with filler bytes, no tool calls —
/// keeps the fixture's construction simple while still producing a "large"
/// session by byte count.
struct PlainReplies {
    calls: AtomicUsize,
}
#[async_trait]
impl Provider for PlainReplies {
    async fn complete(
        &self,
        _req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        let n = self.calls.fetch_add(1, Ordering::SeqCst);
        Ok((
            ChatMessage::assistant(format!("reply {n}: {}", filler(200))),
            Usage::default(),
        ))
    }
}

/// Mint a "large fixture" reduced store session directly (no CLI/network
/// involvement in its construction): `n_turns` send/reply exchanges recorded
/// through a real sidecar, persisted under `name` in `home`'s store. Returns
/// the sidecar's own session, for independent byte-exact assertions.
async fn mint_large_session(home: &Path, name: &str, n_turns: usize) -> Session {
    let store = SessionStore::open(home.join("sessions")).unwrap();
    let sidecar_path = store.sidecar_path(name);

    let config = Config::builder()
        .cwd(home.to_path_buf())
        .system_prompt("you are a careful coding agent")
        .build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(PlainReplies {
            calls: AtomicUsize::new(0),
        }),
    );
    let empty_session = Session::from_claude_code_str("").unwrap();
    let writer = SidecarWriter::create(&sidecar_path, &empty_session).unwrap();
    agent.set_recorder(writer);
    agent.set_reduction_policy(supercode::reduce::ReductionPolicy::default());

    for i in 0..n_turns {
        agent
            .send(format!(
                "turn {i}: please look at src/mod_{i}.rs — {}",
                filler(300)
            ))
            .await
            .unwrap();
    }

    // Persist the reduction log (whatever the default policy minted, if
    // anything) and a plain transcript — mirrors `persist_session`/
    // `resume --reduced`'s own on-disk shape closely enough for `handoff`'s
    // own `store.load_sidecar`/`load_reduction_log`/`resolve_session` calls
    // to find it.
    store
        .save_reduction_log(name, agent.reduction_log())
        .unwrap();
    let jsonl: String = agent
        .history()
        .iter()
        .filter_map(|m| serde_json::to_string(m).ok())
        .collect::<Vec<_>>()
        .join("\n");
    store.save(name, "big fixture", &jsonl).unwrap();

    Session::from_sidecar_str(&std::fs::read_to_string(&sidecar_path).unwrap()).unwrap()
}

#[tokio::test]
async fn dev01_handoff_yields_projected_view_under_10_percent_of_original_tokens() {
    let home = fresh_home("dev01");
    let name = "dev01-sess";
    let sidecar = mint_large_session(&home, name, 40).await;
    assert!(
        sidecar.messages.len() > 40,
        "fixture must be a large session: {}",
        sidecar.messages.len()
    );

    let out = run(
        &home,
        &[
            "handoff",
            name,
            "--keep",
            "3",
            "--keep-last",
            "4",
            "--objective",
            "ship the fix and confirm tests pass",
            "--json",
        ],
    );
    assert!(
        out.status.success(),
        "handoff must exit 0: {}",
        stderr(&out)
    );
    let v: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();

    let full = v["full_tokens"].as_u64().unwrap();
    let view = v["view_tokens"].as_u64().unwrap();
    assert!(full > 0);
    assert!(
        (view as f64) <= 0.10 * (full as f64),
        "handoff view must be <=10% of original tokens: view={view} full={full} ({}%)",
        v["pct"]
    );
    assert_eq!(v["objective_source"], "user-supplied");
    assert_eq!(v["objective"], "ship the fix and confirm tests pass");
    assert!(!v["gap_ids"].as_array().unwrap().is_empty());

    // The persisted view must actually contain the banner + objective text.
    let jsonl_path = sessions_dir(&home).join(format!("{name}.jsonl"));
    let jsonl = std::fs::read_to_string(&jsonl_path).unwrap();
    assert!(jsonl.contains("=== HANDOFF ==="));
    assert!(jsonl.contains("ship the fix and confirm tests pass"));

    std::fs::remove_dir_all(&home).ok();
}

#[tokio::test]
async fn dev02_export_before_and_after_handoff_is_byte_identical() {
    let home = fresh_home("dev02");
    let name = "dev02-sess";
    mint_large_session(&home, name, 30).await;

    let before_path = home.join("before.jsonl");
    let conv_before = run(
        &home,
        &[
            "convert",
            name,
            "--to",
            "codex",
            "-o",
            before_path.to_str().unwrap(),
        ],
    );
    assert!(conv_before.status.success(), "{}", stderr(&conv_before));

    let handoff = run(
        &home,
        &["handoff", name, "--keep", "2", "--keep-last", "3", "--json"],
    );
    assert!(handoff.status.success(), "{}", stderr(&handoff));

    let after_path = home.join("after.jsonl");
    let conv_after = run(
        &home,
        &[
            "convert",
            name,
            "--to",
            "codex",
            "-o",
            after_path.to_str().unwrap(),
        ],
    );
    assert!(conv_after.status.success(), "{}", stderr(&conv_after));

    let before = std::fs::read_to_string(&before_path).unwrap();
    let after = std::fs::read_to_string(&after_path).unwrap();
    assert_eq!(
        before, after,
        "full-fidelity export must be byte-identical before and after handoff"
    );
    // Zero reduction-sentinel leakage, as every other `convert` test asserts.
    assert_eq!(after.matches("sc-reduced").count(), 0);

    std::fs::remove_dir_all(&home).ok();
}

#[tokio::test]
async fn dev03_inspect_after_handoff_shows_reduced_with_stubs_and_tokens() {
    let home = fresh_home("dev03");
    let name = "dev03-sess";
    mint_large_session(&home, name, 30).await;

    let objective = "finish the parser fix without losing the source transcript";
    let handoff = run(
        &home,
        &[
            "handoff",
            name,
            "--keep-last",
            "3",
            "--objective",
            objective,
            "--json",
        ],
    );
    assert!(handoff.status.success(), "{}", stderr(&handoff));
    let v: serde_json::Value = serde_json::from_str(&stdout(&handoff)).unwrap();
    // The last-K deterministic always-keep must be present even though no
    // `--keep` addresses were named at all (SPEC.md dev/03).
    let kept: Vec<u64> = v["kept_indices"]
        .as_array()
        .unwrap()
        .iter()
        .map(|n| n.as_u64().unwrap())
        .collect();
    assert!(!kept.is_empty());

    // C7: `inspect` on the handed-off session shows it as a reduced
    // projection event with before/after tokens and a nonzero stub count.
    let insp = run(&home, &["inspect", name]);
    assert!(insp.status.success(), "{}", stderr(&insp));
    let text = stdout(&insp);
    assert!(text.contains("⊟ reduced"), "{text}");
    assert!(text.contains("stubs"), "{text}");

    // Banner/objective are intentionally view-only (not sidecar/log
    // content), so a fresh inspect must read the persisted working view
    // instead of mechanically rebuilding only sidecar+log and silently
    // dropping them. Its token count must match handoff's own measurement.
    let insp_json = run(&home, &["inspect", name, "--json"]);
    assert!(insp_json.status.success(), "{}", stderr(&insp_json));
    let inspected: serde_json::Value = serde_json::from_str(&stdout(&insp_json)).unwrap();
    let previews: Vec<&str> = inspected["session"]["messages"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|m| m["content_preview"].as_str())
        .collect();
    assert!(
        previews.iter().any(|p| p.contains("=== HANDOFF ===")),
        "fresh inspect lost the persisted handoff banner: {inspected}"
    );
    assert_eq!(
        inspected["session"]["reduced"]["view_tokens"], v["view_tokens"],
        "inspect must measure the same persisted working view handoff reported"
    );

    // The handoff completion hint says `chat -c` (with no `--reduced`). A
    // saved reduced session must therefore restore its sidecar/log/policy
    // automatically rather than loading the flat view as an ordinary chat
    // and rejecting both lifecycle commands as "isn't in reduced mode".
    let id = v["gap_ids"][0].as_str().unwrap();
    let sidecar_path = sessions_dir(&home).join(format!("{name}.sidecar.jsonl"));
    let sidecar_before = std::fs::read(&sidecar_path).unwrap();
    let expand = run_with_stdin(&home, &["chat", "--last"], Some(&format!("/expand {id}\n")));
    assert!(expand.status.success(), "{}", stderr(&expand));
    let lifecycle_err = stderr(&expand);
    assert!(
        lifecycle_err.contains(&format!("expanded {id}")),
        "advertised saved-session continuation could not expand: {lifecycle_err}"
    );

    // Restart while deliberately expanded. The exact full working view and
    // durable expanded record must survive; reopening must not mechanically
    // mint an orphan stub and discard the replacement log.
    let expanded_inspect = run(&home, &["inspect", name, "--json"]);
    assert!(
        expanded_inspect.status.success(),
        "{}",
        stderr(&expanded_inspect)
    );
    let expanded_inspect: serde_json::Value =
        serde_json::from_str(&stdout(&expanded_inspect)).unwrap();
    assert_eq!(expanded_inspect["session"]["reduced"]["stub_count"], 0);
    let expanded_log: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.reduction.json")))
            .unwrap(),
    )
    .unwrap();
    assert!(expanded_log["reductions"].as_array().unwrap().is_empty());
    assert_eq!(expanded_log["expanded"][0]["id"], id);

    let reduce = run_with_stdin(&home, &["chat", "--last"], Some("/reduce\n"));
    assert!(reduce.status.success(), "{}", stderr(&reduce));
    assert!(
        stderr(&reduce).contains("re-reduced"),
        "reopened saved-session continuation could not reduce: {}",
        stderr(&reduce)
    );
    assert_eq!(
        std::fs::read(&sidecar_path).unwrap(),
        sidecar_before,
        "offline expand/reduce must never alter the full-fidelity sidecar"
    );
    let persisted =
        std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.jsonl"))).unwrap();
    assert!(
        persisted.contains(objective),
        "saved-session continuation lost the handoff objective"
    );
    let log: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.reduction.json")))
            .unwrap(),
    )
    .unwrap();
    assert!(
        log["reductions"]
            .as_array()
            .unwrap()
            .iter()
            .any(|r| r["id"] == id),
        "re-reduce did not persist the original stable reduction id"
    );
    assert!(
        log.get("expanded")
            .is_none_or(|expanded| expanded.as_array().is_some_and(Vec::is_empty)),
        "empty expanded state must be absent or an empty array: {log}"
    );

    // Reopen and persist once more: the handoff note is now embedded after
    // the normal agent system prompt, so this proves marker extraction is
    // not accidentally first-line-only. It remains exactly once.
    let second_reopen = run_with_stdin(&home, &["chat", "--last"], Some("/reduce\n"));
    assert!(second_reopen.status.success(), "{}", stderr(&second_reopen));
    let stored_title = SessionStore::open(sessions_dir(&home))
        .unwrap()
        .list()
        .into_iter()
        .find(|info| info.name == name)
        .expect("handed-off session metadata must still exist")
        .title;
    assert_eq!(
        stored_title, "big fixture",
        "handoff/expand/reduce changes which user turn is first in the working view, but must not retitle the saved session"
    );
    let persisted =
        std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.jsonl"))).unwrap();
    assert_eq!(
        persisted.matches(objective).count(),
        1,
        "second reopen lost or duplicated the handoff objective"
    );

    let exported = home.join("after-reopens.jsonl");
    let converted = run(
        &home,
        &[
            "convert",
            name,
            "--to",
            "claude-code",
            "-o",
            exported.to_str().unwrap(),
        ],
    );
    assert!(converted.status.success(), "{}", stderr(&converted));
    assert!(
        !std::fs::read_to_string(exported)
            .unwrap()
            .contains(objective),
        "view-only handoff objective leaked into full export"
    );

    std::fs::remove_dir_all(&home).ok();
}

#[tokio::test]
async fn handoff_prints_the_exact_named_resume_hint() {
    let home = fresh_home("hint");
    let name = "hint-sess";
    let sidecar = mint_large_session(&home, name, 20).await;

    let out = run(&home, &["handoff", name, "--keep-last", "3"]);
    assert!(out.status.success(), "{}", stderr(&out));
    let text = stdout(&out);

    assert!(
        text.contains(&format!("supercode resume {name}")),
        "must print the exact named `resume` form: {text}"
    );

    let resumed = run(&home, &["--reduced", "resume", name, "--dry-run"]);
    assert!(resumed.status.success(), "{}", stderr(&resumed));
    let report: serde_json::Value = serde_json::from_str(&stdout(&resumed)).unwrap();
    assert_eq!(
        report["replay_message_count"],
        sidecar.messages.len(),
        "named handoff resume must replay the full sidecar, not the projected flat view"
    );
    assert_eq!(report["provider_request_sent"], false);
    assert_eq!(report["store_written"], false);

    std::fs::remove_dir_all(&home).ok();
}

#[tokio::test]
async fn non_reduced_named_resume_persists_inherited_reduction_ids() {
    let home = fresh_home("inherited-log");
    let name = "inherited-log-source";
    mint_large_session(&home, name, 20).await;
    let handoff = run(&home, &["handoff", name, "--keep-last", "3"]);
    assert!(handoff.status.success(), "{}", stderr(&handoff));

    let store = SessionStore::open(sessions_dir(&home)).unwrap();
    let source_log = store.load_reduction_log(name).unwrap().unwrap();
    assert!(!source_log.reductions.is_empty());
    let mut expected_ids: Vec<_> = source_log
        .reductions
        .iter()
        .chain(&source_log.expanded)
        .map(|reduction| reduction.id.clone())
        .collect();
    expected_ids.sort();

    let resumed = run(&home, &["--no-reduced", "resume", name, "continue"]);
    assert!(
        !resumed.status.success(),
        "unreachable provider should fail"
    );
    assert!(
        !stderr(&resumed).contains("no session matching"),
        "{}",
        stderr(&resumed)
    );

    let reduction_files: Vec<_> = std::fs::read_dir(sessions_dir(&home))
        .unwrap()
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| {
            path.to_string_lossy().ends_with(".reduction.json")
                && path.file_name().and_then(|value| value.to_str())
                    != Some(&format!("{name}.reduction.json"))
        })
        .collect();
    assert_eq!(reduction_files.len(), 1, "expected one continuation log");
    let continued_log: supercode::reduce::ReductionLog =
        serde_json::from_str(&std::fs::read_to_string(&reduction_files[0]).unwrap()).unwrap();
    assert!(continued_log.reductions.is_empty());
    let mut continued_ids: Vec<_> = continued_log
        .expanded
        .iter()
        .map(|reduction| reduction.id.clone())
        .collect();
    continued_ids.sort();
    assert_eq!(continued_ids, expected_ids);

    std::fs::remove_dir_all(&home).ok();
}

#[tokio::test]
async fn handoff_on_a_never_reduced_session_errors_clearly() {
    let home = fresh_home("no-sidecar");
    let dir = sessions_dir(&home);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("plain-sess.jsonl"), "{}\n").unwrap();
    std::fs::write(
        dir.join("plain-sess.meta.json"),
        serde_json::json!({"name": "plain-sess", "title": "t"}).to_string(),
    )
    .unwrap();

    let out = run(&home, &["handoff", "plain-sess", "--keep-last", "2"]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("no sidecar recorded"),
        "{}",
        stderr(&out)
    );

    std::fs::remove_dir_all(&home).ok();
}

#[tokio::test]
async fn handoff_false_refuses_before_mutating_the_saved_sidecar_family() {
    let home = fresh_home("disabled-gate");
    let name = "disabled-handoff-sess";
    mint_large_session(&home, name, 20).await;

    std::fs::write(
        home.join("config.toml"),
        "schema_version = 1\nextends = \"token-saver\"\n\
         \n[experimental]\nmodule_registry = true\n\
         \n[capabilities.reduction]\nhandoff = false\n",
    )
    .unwrap();

    let before: std::collections::BTreeMap<_, _> = std::fs::read_dir(sessions_dir(&home))
        .unwrap()
        .flatten()
        .map(|entry| {
            let path = entry.path();
            (entry.file_name(), std::fs::read(path).unwrap())
        })
        .collect();

    let out = run(&home, &["handoff", name, "--keep-last", "3", "--json"]);
    assert!(!out.status.success(), "disabled handoff unexpectedly ran");
    assert!(
        stderr(&out).contains("handoff is disabled") && stderr(&out).contains("handoff = false"),
        "the refusal must name the controlling config gate: {}",
        stderr(&out)
    );

    let after: std::collections::BTreeMap<_, _> = std::fs::read_dir(sessions_dir(&home))
        .unwrap()
        .flatten()
        .map(|entry| {
            let path = entry.path();
            (entry.file_name(), std::fs::read(path).unwrap())
        })
        .collect();
    assert_eq!(
        after, before,
        "a capability refusal must happen before touching any transcript, sidecar, metadata, or reduction-log byte"
    );

    std::fs::remove_dir_all(&home).ok();
}

#[tokio::test]
async fn project_cannot_reenable_a_trusted_handoff_disable_or_discard_it_with_a_sibling_key() {
    for (tag, project_reduction) in [
        ("reenable", "handoff = true"),
        ("sibling", "stale_reads = false"),
    ] {
        let home = fresh_home(tag);
        let project = home.join("project");
        std::fs::create_dir_all(&project).unwrap();
        let name = format!("trusted-disabled-{tag}");
        mint_large_session(&home, &name, 20).await;

        std::fs::write(
            home.join("config.toml"),
            "schema_version = 1\nextends = \"token-saver\"\n\
             \n[experimental]\nmodule_registry = true\n\
             \n[capabilities.reduction]\nhandoff = false\n",
        )
        .unwrap();
        std::fs::write(
            project.join(".supercode.toml"),
            format!("schema_version = 1\n\n[capabilities.reduction]\n{project_reduction}\n"),
        )
        .unwrap();

        let before: std::collections::BTreeMap<_, _> = std::fs::read_dir(sessions_dir(&home))
            .unwrap()
            .flatten()
            .map(|entry| {
                let path = entry.path();
                (entry.file_name(), std::fs::read(path).unwrap())
            })
            .collect();
        let out = run_with_stdin_in(
            &home,
            Some(&project),
            &["handoff", &name, "--keep-last", "3", "--json"],
            None,
        );
        assert!(!out.status.success(), "project case {tag} widened handoff");
        assert!(
            stderr(&out).contains("handoff is disabled"),
            "project case {tag} did not preserve the trusted gate: {}",
            stderr(&out)
        );
        let after: std::collections::BTreeMap<_, _> = std::fs::read_dir(sessions_dir(&home))
            .unwrap()
            .flatten()
            .map(|entry| {
                let path = entry.path();
                (entry.file_name(), std::fs::read(path).unwrap())
            })
            .collect();
        assert_eq!(
            after, before,
            "project case {tag} mutated the session family"
        );

        std::fs::remove_dir_all(&home).ok();
    }
}

#[tokio::test]
async fn project_reduction_master_false_disables_handoff_before_any_session_mutation() {
    let home = fresh_home("master-off");
    let project = home.join("project");
    std::fs::create_dir_all(&project).unwrap();
    let name = "master-disabled-handoff";
    mint_large_session(&home, name, 20).await;

    std::fs::write(
        home.join("config.toml"),
        "schema_version = 1\nextends = \"token-saver\"\n\
         \n[experimental]\nmodule_registry = true\n",
    )
    .unwrap();
    std::fs::write(
        project.join(".supercode.toml"),
        "schema_version = 1\n\n[capabilities.reduction]\nenabled = false\n",
    )
    .unwrap();

    let before: std::collections::BTreeMap<_, _> = std::fs::read_dir(sessions_dir(&home))
        .unwrap()
        .flatten()
        .map(|entry| {
            let path = entry.path();
            (entry.file_name(), std::fs::read(path).unwrap())
        })
        .collect();
    let out = run_with_stdin_in(
        &home,
        Some(&project),
        &["handoff", name, "--keep-last", "3", "--json"],
        None,
    );
    assert!(
        !out.status.success(),
        "reduction master-off still ran handoff"
    );
    assert!(
        stderr(&out).contains("handoff is disabled") && stderr(&out).contains("enabled = false"),
        "master refusal must name the controlling gate: {}",
        stderr(&out)
    );
    let after: std::collections::BTreeMap<_, _> = std::fs::read_dir(sessions_dir(&home))
        .unwrap()
        .flatten()
        .map(|entry| {
            let path = entry.path();
            (entry.file_name(), std::fs::read(path).unwrap())
        })
        .collect();
    assert_eq!(after, before, "master refusal mutated the session family");

    std::fs::remove_dir_all(&home).ok();
}