supercode-cli 0.4.13

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
//! CLI-level acceptance tests for C4 (SPEC.md §7 C4(b)) and C7 (§7 C7(b)):
//! `sessions show-reductions`, the `/expand`/`/reduce` REPL verbs, and
//! `convert`/`inspect` on a reduced session.
//!
//! Follows the `reduced_resume.rs` (C1) idiom: spawn the built `supercode`
//! binary against an unreachable `--base-url` with a dummy API key and a
//! fresh, isolated `$SUPERCODE_HOME` per test. `show-reductions`/`convert`/
//! `inspect` are offline (no API key needed at all; the flags are just
//! carried along for consistency with `resume`'s invocations). `/expand`/
//! `/reduce` never call the model either — scripted stdin feeds slash
//! commands into the REPL, then EOF closes it (`bye.`), so no network
//! activity ever happens and these tests run fast and fully offline.
//!
//! Ids are deterministic (a pure function of message content + the default
//! `ReductionPolicy`), so tests compute the expected id independently via
//! `supercode::reduce::project` — the `supercode-cli` crate depends on
//! `supercode-core` (lib name `supercode`), so integration tests here can
//! call straight into it rather than re-deriving ids from spawned-process
//! output.

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

use supercode::reduce::{project, ReductionLog, ReductionPolicy};
use supercode::session::{Session, SessionFormat};
use supercode::tokens::estimate_view_tokens;

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-c4c7-{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, "")
}

fn run_with_stdin(home: &Path, extra: &[&str], stdin: &str) -> Output {
    let mut args = vec!["--api-key", "x", "--base-url", "http://127.0.0.1:1"];
    args.extend_from_slice(extra);
    let mut child = Command::new(bin())
        .env("SUPERCODE_HOME", home)
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .args(&args)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("failed to spawn the supercode binary");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(stdin.as_bytes())
        .unwrap();
    child.wait_with_output().expect("child process failed")
}

fn spawn_capturing_sse_stub(
    reply: &'static str,
) -> (std::net::SocketAddr, std::thread::JoinHandle<String>) {
    let listener = TcpListener::bind("127.0.0.1:0").expect("bind stub listener");
    let addr = listener.local_addr().unwrap();
    let handle = std::thread::spawn(move || {
        let (mut sock, _) = listener.accept().expect("accept one connection");
        sock.set_read_timeout(Some(Duration::from_millis(500)))
            .expect("set read timeout");
        let mut request = Vec::new();
        let mut buf = [0u8; 65_536];
        loop {
            match sock.read(&mut buf) {
                Ok(0) => break,
                Ok(n) => request.extend_from_slice(&buf[..n]),
                Err(e)
                    if e.kind() == std::io::ErrorKind::WouldBlock
                        || e.kind() == std::io::ErrorKind::TimedOut =>
                {
                    break
                }
                Err(e) => panic!("stub read failed: {e}"),
            }
        }
        let sse = format!(
            "data: {{\"choices\":[{{\"delta\":{{\"content\":\"{reply}\"}}}}]}}\n\ndata: [DONE]\n\n"
        );
        let response = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{sse}",
            sse.len()
        );
        sock.write_all(response.as_bytes()).unwrap();
        String::from_utf8(request).expect("request must be UTF-8")
    });
    (addr, handle)
}

fn run_at(home: &Path, base_url: &str, extra: &[&str]) -> Output {
    let mut args = vec!["--api-key", "x", "--base-url", base_url];
    args.extend_from_slice(extra);
    Command::new(bin())
        .env("SUPERCODE_HOME", home)
        .env_remove("OPENROUTER_API_KEY")
        .env_remove("OPENAI_API_KEY")
        .env_remove("ANTHROPIC_API_KEY")
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .expect("failed to spawn the supercode binary")
}

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()
}

/// A minimal, valid Claude Code session JSONL with ONE oversized tool result
/// (20,000 bytes — comfortably over the default A7 trigger, 8,192 bytes) at
/// the OLDEST of four tool results, so it is never in the protected "last 3"
/// tool-results window (`protect_last_n_tool_results` defaults to 3) and is
/// guaranteed to produce exactly one `ToolOutputTruncated` reduction under
/// `ReductionPolicy::default()`.
fn write_big_fixture(dir: &Path) -> PathBuf {
    let sid = "22222222-3333-4444-5555-666666666666";
    let mut lines: Vec<String> = Vec::new();
    lines.push(
        serde_json::json!({
            "type": "user",
            "message": {"role": "user", "content": "please investigate the failing test"},
            "uuid": "u0", "parentUuid": null,
            "timestamp": "2026-06-07T18:38:00.000Z", "sessionId": sid,
            "cwd": "/tmp/proj", "userType": "external",
        })
        .to_string(),
    );
    let big = "x".repeat(20_000);
    for i in 0..4 {
        let tool_id = format!("toolu_{i:02}");
        lines.push(
            serde_json::json!({
                "type": "assistant",
                "message": {"role": "assistant", "content": [
                    {"type": "tool_use", "id": tool_id, "name": "bash", "input": {"command": "cargo test"}}
                ]},
                "uuid": format!("a{i}"),
                "parentUuid": if i == 0 { "u0".to_string() } else { format!("t{}", i - 1) },
                "timestamp": "2026-06-07T18:38:01.000Z", "sessionId": sid,
            })
            .to_string(),
        );
        let content = if i == 0 {
            big.clone()
        } else {
            "ok".to_string()
        };
        lines.push(
            serde_json::json!({
                "type": "user",
                "message": {"role": "user", "content": [
                    {"tool_use_id": tool_id, "type": "tool_result", "content": [{"type": "text", "text": content}]}
                ]},
                "uuid": format!("t{i}"), "parentUuid": format!("a{i}"),
                "timestamp": "2026-06-07T18:38:02.000Z", "sessionId": sid,
                "toolUseResult": {"status": "completed"},
            })
            .to_string(),
        );
    }
    let path = dir.join("big_claude_session.jsonl");
    std::fs::write(&path, lines.join("\n") + "\n").unwrap();
    path
}

/// Large enough to cross the proactive 35% boundary and force A10 after the
/// earlier output/supersession passes have already produced claims.
fn write_pass_order_fixture(dir: &Path) -> PathBuf {
    let sid = "33333333-4444-5555-6666-777777777777";
    let mut lines = vec![serde_json::json!({
        "type": "user", "sessionId": sid, "cwd": dir,
        "uuid": "root", "parentUuid": null,
        "timestamp": "2026-07-16T00:00:00.000Z",
        "message": {"role": "user", "content": "attribute the completed continuation"}
    })
    .to_string()];
    for i in 0..12 {
        let tool_id = format!("toolu_order_{i:02}");
        lines.push(
            serde_json::json!({
                "type": "assistant", "sessionId": sid,
                "uuid": format!("a{i}"), "parentUuid": if i == 0 { "root".to_string() } else { format!("t{}", i - 1) },
                "timestamp": "2026-07-16T00:00:01.000Z",
                "message": {"role": "assistant", "content": [
                    {"type": "text", "text": format!("analysis-{i}-{}", "y".repeat(20_000))},
                    {"type": "tool_use", "id": tool_id, "name": "bash",
                     "input": {"command": "cargo test"}}
                ]}
            })
            .to_string(),
        );
        lines.push(
            serde_json::json!({
                "type": "user", "sessionId": sid,
                "uuid": format!("t{i}"), "parentUuid": format!("a{i}"),
                "timestamp": "2026-07-16T00:00:02.000Z",
                "message": {"role": "user", "content": [{
                    "type": "tool_result", "tool_use_id": tool_id,
                    "content": [{"type": "text", "text": format!("result-{i}-{}", "x".repeat(20_000))}]
                }]},
                "toolUseResult": {"status": "completed"}
            })
            .to_string(),
        );
    }
    let path = dir.join("pass_order_claude_session.jsonl");
    std::fs::write(&path, lines.join("\n") + "\n").unwrap();
    path
}

/// The reduction id `project(default policy)` deterministically assigns to
/// the fixture's one oversized tool result — computed independently of the
/// CLI, so tests can script `/expand <id>` without a prior process run.
fn expected_id(fixture_path: &Path) -> String {
    let session = Session::load(fixture_path).unwrap();
    let (_, log) = project(
        &session,
        &ReductionPolicy::default(),
        &ReductionLog::default(),
    );
    assert_eq!(
        log.reductions.len(),
        1,
        "fixture must yield exactly one reduction"
    );
    log.reductions[0].id.clone()
}

/// Mint a reduced store session from `fixture` (immediate EOF, no prompt —
/// no network activity) and return its store name, derived from the sidecar
/// path the C1 banner names.
fn mint_reduced_session(home: &Path, fixture: &Path) -> String {
    let out = run(home, &["resume", fixture.to_str().unwrap(), "--reduced"]);
    let err = stderr(&out);
    let line = err
        .lines()
        .find(|l| l.contains("full copy:"))
        .unwrap_or_else(|| panic!("no `full copy:` line in:\n{err}"));
    let sidecar_path = line.split("full copy:").nth(1).unwrap().trim();
    Path::new(sidecar_path)
        .file_name()
        .unwrap()
        .to_str()
        .unwrap()
        .strip_suffix(".sidecar.jsonl")
        .unwrap()
        .to_string()
}

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

#[test]
fn show_reductions_lists_exactly_the_sidecar_ids_and_json_count_matches() {
    let home = fresh_home("show-basic");
    let fixture = write_big_fixture(&home);
    let name = mint_reduced_session(&home, &fixture);

    // Ground truth: the ids actually recorded in `<name>.reduction.json`.
    let log_path = sessions_dir(&home).join(format!("{name}.reduction.json"));
    let log_json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&log_path).unwrap()).unwrap();
    let expected_ids: Vec<String> = log_json["reductions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["id"].as_str().unwrap().to_string())
        .collect();
    assert_eq!(expected_ids.len(), 1);

    let out = run(&home, &["sessions", "show-reductions", &name]);
    assert!(
        out.status.success(),
        "show-reductions must exit 0: {}",
        stderr(&out)
    );
    let table = stdout(&out);
    for id in &expected_ids {
        assert!(table.contains(id), "table must list id {id}:\n{table}");
    }
    // Exactly one row (one " B   " byte-marker per record).
    assert_eq!(table.matches(" B   ").count(), expected_ids.len());

    let json_out = run(&home, &["sessions", "show-reductions", &name, "--json"]);
    assert!(json_out.status.success());
    let log: serde_json::Value = serde_json::from_str(&stdout(&json_out)).unwrap();
    assert_eq!(
        log["reductions"].as_array().unwrap().len(),
        expected_ids.len()
    );

    // The banner's stub count (C1) must agree with `--json`'s count (C9
    // cross-surface consistency).
    let banner_err = {
        // Re-mint to read the banner's own stub count independent of the
        // table (the session above already consumed its banner text).
        let home2 = fresh_home("show-basic-banner");
        let out2 = run(&home2, &["resume", fixture.to_str().unwrap(), "--reduced"]);
        let e = stderr(&out2);
        std::fs::remove_dir_all(&home2).ok();
        e
    };
    let stub_count_line = banner_err
        .lines()
        .find(|l| l.contains("stubs"))
        .expect("banner must have a stub-count line");
    assert!(
        stub_count_line.contains(&format!("{} stubs", expected_ids.len())),
        "banner stub count must match: {stub_count_line}"
    );

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

#[test]
fn show_reductions_on_non_reduced_session_prints_notice_and_exits_zero() {
    let home = fresh_home("show-nonreduced");
    // Hand-craft a plain (non-reduced) store entry: no sidecar/reduction
    // files — this is exactly what a `chat`/`run` session (no `--reduced`)
    // looks like, without needing a live network call to produce one.
    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, &["sessions", "show-reductions", "plain-sess"]);
    assert!(out.status.success(), "must exit 0: {}", stderr(&out));
    assert!(
        stdout(&out).contains("not a reduced session — nothing to show"),
        "got: {}",
        stdout(&out)
    );
    std::fs::remove_dir_all(&home).ok();
}

#[test]
fn corrupt_sidecar_record_fails_show_reductions_and_convert_writes_no_file() {
    let home = fresh_home("corrupt");
    let fixture = write_big_fixture(&home);
    let name = mint_reduced_session(&home, &fixture);
    let id = expected_id(&fixture);

    // Tamper the sidecar's recorded bytes for the reduced record so its
    // content hash no longer matches `SidecarPtr::content_hash`, without
    // breaking JSONL parsing.
    let sidecar_path = sessions_dir(&home).join(format!("{name}.sidecar.jsonl"));
    let sidecar = std::fs::read_to_string(&sidecar_path).unwrap();
    assert!(
        sidecar.contains("xxxxx"),
        "fixture content must be present verbatim"
    );
    let tampered = sidecar.replacen("xxxxx", "yyyyy", 1);
    std::fs::write(&sidecar_path, tampered).unwrap();

    let show = run(&home, &["sessions", "show-reductions", &name]);
    assert!(
        !show.status.success(),
        "must exit non-zero on a corrupt record"
    );
    assert!(
        stderr(&show).contains(&id),
        "error must name the offending id {id}: {}",
        stderr(&show)
    );

    let out_path = home.join("out.jsonl");
    let conv = run(
        &home,
        &[
            "convert",
            &name,
            "--to",
            "codex",
            "-o",
            out_path.to_str().unwrap(),
        ],
    );
    assert!(
        !conv.status.success(),
        "convert must exit non-zero on a corrupt record"
    );
    assert!(
        stderr(&conv).contains(&id),
        "convert error must name the offending id {id}: {}",
        stderr(&conv)
    );
    assert!(
        !out_path.exists(),
        "convert must write no output file on failure"
    );

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

#[test]
fn missing_log_with_persisted_stubs_fails_every_reduced_store_surface() {
    let home = fresh_home("missing-log-with-stubs");
    let fixture = write_big_fixture(&home);
    let name = mint_reduced_session(&home, &fixture);
    let dir = sessions_dir(&home);
    let persisted = run_with_stdin(&home, &["chat", "--last"], "/reduce\n");
    assert!(persisted.status.success(), "{}", stderr(&persisted));
    let view = std::fs::read_to_string(dir.join(format!("{name}.jsonl"))).unwrap();
    assert!(view.contains("sc-reduced"), "fixture must persist a stub");
    std::fs::remove_file(dir.join(format!("{name}.reduction.json"))).unwrap();

    let out_path = home.join("must-not-exist.jsonl");
    let commands: Vec<Vec<&str>> = vec![
        vec!["inspect", &name, "--json"],
        vec!["sessions", "show-reductions", &name],
        vec!["chat", "--last"],
        vec![
            "convert",
            &name,
            "--to",
            "codex",
            "--out",
            out_path.to_str().unwrap(),
        ],
    ];
    for args in commands {
        let out = run(&home, &args);
        assert!(
            !out.status.success(),
            "{args:?} silently accepted corruption"
        );
        let err = stderr(&out);
        assert!(err.contains("reduction log is missing"), "{args:?}: {err}");
        assert!(err.contains(&name), "{args:?}: {err}");
    }
    assert!(
        !out_path.exists(),
        "convert must write nothing for an uninterpretable reduced family"
    );

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

#[test]
fn missing_empty_log_is_valid_when_the_working_view_has_no_stubs() {
    let home = fresh_home("missing-empty-log");
    let fixture = home.join("tiny.jsonl");
    std::fs::write(
        &fixture,
        serde_json::json!({
            "type": "user",
            "message": {"role": "user", "content": "tiny session"},
            "uuid": "u-tiny",
            "sessionId": "11111111-2222-4333-8444-555555555555",
            "timestamp": "2026-07-12T00:00:00.000Z",
            "cwd": "/tmp/tiny"
        })
        .to_string()
            + "\n",
    )
    .unwrap();
    let name = mint_reduced_session(&home, &fixture);
    let dir = sessions_dir(&home);
    let persisted = run_with_stdin(&home, &["chat", "--last"], "/reduce\n");
    assert!(persisted.status.success(), "{}", stderr(&persisted));
    let view = std::fs::read_to_string(dir.join(format!("{name}.jsonl"))).unwrap();
    assert!(!view.contains("sc-reduced"));
    let log: ReductionLog = serde_json::from_str(
        &std::fs::read_to_string(dir.join(format!("{name}.reduction.json"))).unwrap(),
    )
    .unwrap();
    assert!(log.reductions.is_empty());
    std::fs::remove_file(dir.join(format!("{name}.reduction.json"))).unwrap();

    let inspected = run(&home, &["inspect", &name, "--json"]);
    assert!(inspected.status.success(), "{}", stderr(&inspected));
    let json: serde_json::Value = serde_json::from_slice(&inspected.stdout).unwrap();
    assert_eq!(json["session"]["reduced"]["stub_count"], 0);

    let exported = home.join("tiny.codex.jsonl");
    let converted = run(
        &home,
        &[
            "convert",
            &name,
            "--to",
            "codex",
            "--out",
            exported.to_str().unwrap(),
        ],
    );
    assert!(converted.status.success(), "{}", stderr(&converted));
    assert!(exported.exists());

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

#[test]
fn convert_reduced_session_reads_sidecar_zero_leaks_and_fidelity_line() {
    let home = fresh_home("convert-ok");
    let fixture = write_big_fixture(&home);
    let name = mint_reduced_session(&home, &fixture);

    let out_path = home.join("as-codex.jsonl");
    let conv = run(
        &home,
        &[
            "convert",
            &name,
            "--to",
            "codex",
            "-o",
            out_path.to_str().unwrap(),
        ],
    );
    assert!(
        conv.status.success(),
        "convert must succeed: {}",
        stderr(&conv)
    );
    let written = std::fs::read_to_string(&out_path).unwrap();
    assert_eq!(
        written.matches("sc-reduced").count(),
        0,
        "export must contain zero 'sc-reduced' occurrences"
    );

    let err = stderr(&conv);
    assert!(
        err.contains("fidelity: full"),
        "missing fidelity line: {err}"
    );
    assert!(
        err.contains("stubs rehydrated"),
        "missing stub count: {err}"
    );
    assert!(
        err.contains("resume on your subscription"),
        "missing resume hint: {err}"
    );
    assert!(
        err.contains("codex exec resume"),
        "hint must name the target tool: {err}"
    );

    // A same-format export with no continued tail is not merely
    // semantically full-fidelity: the splice path replays the imported
    // source bytes verbatim.  The CLI must classify the bytes it actually
    // wrote instead of asserting that every reduced/store export differs.
    let claude_path = home.join("as-claude.jsonl");
    let diagonal = run(
        &home,
        &[
            "convert",
            &name,
            "--to",
            "claude-code",
            "-o",
            claude_path.to_str().unwrap(),
        ],
    );
    assert!(diagonal.status.success(), "{}", stderr(&diagonal));
    assert_eq!(
        std::fs::read(&claude_path).unwrap(),
        std::fs::read(&fixture).unwrap(),
        "same-format reduced export must replay the original bytes"
    );
    assert!(
        stderr(&diagonal).contains("byte-identical (verbatim)"),
        "same-format reduced export must report its observed byte identity: {}",
        stderr(&diagonal)
    );

    // Byte-for-byte match against an independent reconstruction of the
    // sidecar (same normalization path, A11/A12).
    let sidecar_path = sessions_dir(&home).join(format!("{name}.sidecar.jsonl"));
    let sidecar_str = std::fs::read_to_string(&sidecar_path).unwrap();
    let sidecar = Session::from_sidecar_str(&sidecar_str).unwrap();
    let expected = sidecar
        .to_jsonl_spliced(SessionFormat::Codex, None)
        .unwrap();
    assert_eq!(
        written, expected,
        "convert output must match an independent sidecar re-export"
    );

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

#[test]
fn inspect_reduced_session_shows_reduced_rows_and_tag() {
    let home = fresh_home("inspect-reduced");
    let fixture = write_big_fixture(&home);
    let name = mint_reduced_session(&home, &fixture);
    assert!(
        !sessions_dir(&home).join(format!("{name}.jsonl")).exists(),
        "EOF-only reduced resume must exercise the entry-only projection fallback"
    );

    let out = run(&home, &["inspect", &name]);
    assert!(
        out.status.success(),
        "inspect must succeed: {}",
        stderr(&out)
    );
    let text = stdout(&out);
    assert!(text.contains("reduced"), "missing `reduced` row:\n{text}");
    assert!(text.contains("stubs"), "missing stub count:\n{text}");
    assert!(text.contains("sidecar"), "missing `sidecar` row:\n{text}");
    assert!(
        text.contains("⊟ reduced"),
        "missing the reduced row tag:\n{text}"
    );

    let json_out = run(&home, &["inspect", &name, "--json"]);
    assert!(json_out.status.success(), "{}", stderr(&json_out));
    let json: serde_json::Value = serde_json::from_str(&stdout(&json_out)).unwrap();
    let attribution = &json["session"]["reduced"]["attribution"];
    let passes = attribution["passes"].as_array().unwrap();
    assert_eq!(passes.len(), 9, "every enabled pass must be reported");
    assert!(
        passes
            .iter()
            .any(|row| row["applied_count"].as_u64().unwrap() > 0),
        "fixture must have an attributed applied pass"
    );
    assert_eq!(attribution["aggregate_bytes_is_marginal_sum"], true);
    assert_eq!(attribution["aggregate_is_marginal_sum"], true);
    assert_eq!(
        passes
            .iter()
            .map(|row| row["marginal_saved_bytes"].as_u64().unwrap())
            .sum::<u64>(),
        attribution["aggregate_saved_bytes"].as_u64().unwrap(),
        "aggregate byte savings must be the marginal sum"
    );
    assert_eq!(
        passes
            .iter()
            .map(|row| row["marginal_saved_tokens"].as_u64().unwrap())
            .sum::<u64>(),
        attribution["aggregate_saved_tokens"].as_u64().unwrap(),
        "aggregate savings must be the marginal sum, never standalone claims added twice"
    );

    let sidecar = Session::from_sidecar_str(
        &std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.sidecar.jsonl")))
            .unwrap(),
    )
    .unwrap();
    let log: ReductionLog = serde_json::from_str(
        &std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.reduction.json")))
            .unwrap(),
    )
    .unwrap();
    let expected_view_messages = project(&sidecar, &ReductionPolicy::default(), &log).0.len() + 1;
    let continued = run(&home, &["chat", "--last"]);
    assert!(continued.status.success(), "{}", stderr(&continued));
    assert!(
        stderr(&continued).contains(&format!(
            "Continuing reduced session ({expected_view_messages}-message view; {} full messages).",
            sidecar.messages.len()
        )),
        "entry-only continuation count must include the model system message: {}",
        stderr(&continued)
    );

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

#[test]
fn completed_reduced_turn_refreshes_durable_pass_order_attribution() {
    let home = fresh_home("attribution-refresh");
    let fixture = write_pass_order_fixture(&home);
    let (addr, provider) = spawn_capturing_sse_stub("DONE");
    let out = run_at(
        &home,
        &format!("http://{addr}"),
        &[
            "--quiet",
            "--model",
            "z-ai/glm-5.2",
            "--reduced",
            "--no-project-context",
            "resume",
            fixture.to_str().unwrap(),
            "Reply exactly DONE.",
            "--paused",
        ],
    );
    assert!(out.status.success(), "{}", stderr(&out));
    let _ = provider.join().unwrap();

    let listed = run(&home, &["sessions", "list", "--json"]);
    assert!(listed.status.success(), "{}", stderr(&listed));
    let sessions: serde_json::Value = serde_json::from_str(&stdout(&listed)).unwrap();
    let name = sessions[0]["name"].as_str().unwrap();
    let log: ReductionLog = serde_json::from_str(
        &std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.reduction.json")))
            .unwrap(),
    )
    .unwrap();
    let sidecar = Session::from_sidecar_str(
        &std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.sidecar.jsonl")))
            .unwrap(),
    )
    .unwrap();
    let attribution = log
        .attribution
        .expect("completed turn must persist attribution");
    assert_eq!(
        attribution.full_tokens,
        estimate_view_tokens(&sidecar.messages),
        "persisted attribution must be refreshed against the post-turn sidecar"
    );
    assert!(
        attribution
            .passes
            .iter()
            .map(|row| row.suppressed_by_later_pass_count)
            .sum::<usize>()
            > 0,
        "A10 must durably name the earlier claims it subsumed"
    );
    assert_eq!(
        attribution
            .passes
            .iter()
            .map(|row| row.marginal_saved_tokens)
            .sum::<u64>(),
        attribution.aggregate_saved_tokens
    );
    std::fs::remove_dir_all(home).ok();
}

#[test]
fn no_reduced_saved_continuation_uses_full_history_and_keeps_sidecar_current() {
    let home = fresh_home("no-reduced-saved");
    let fixture = write_big_fixture(&home);
    let name = mint_reduced_session(&home, &fixture);
    let sidecar_path = sessions_dir(&home).join(format!("{name}.sidecar.jsonl"));
    let before = Session::from_sidecar_str(&std::fs::read_to_string(&sidecar_path).unwrap())
        .unwrap()
        .messages
        .len();

    const USER_MARKER: &str = "NO_REDUCED_SAVED_USER_MARKER";
    const ASSISTANT_MARKER: &str = "NO_REDUCED_SAVED_ASSISTANT_MARKER";
    let (addr, server) = spawn_capturing_sse_stub(ASSISTANT_MARKER);
    let out = run_at(
        &home,
        &format!("http://{addr}"),
        &["--no-reduced", "--last", "run", USER_MARKER],
    );
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(
        stderr(&out).contains(&format!("Continuing session ({} messages).", before + 1)),
        "the unreduced continuation must load full sidecar history: {}",
        stderr(&out)
    );
    assert!(
        !stderr(&out).contains("Continuing reduced session"),
        "--no-reduced must suppress reduced-mode startup: {}",
        stderr(&out)
    );

    let request = server.join().unwrap();
    assert!(request.contains(USER_MARKER), "request lost the new prompt");
    assert!(
        request.contains(&"x".repeat(20_000)),
        "unreduced request must contain the original oversized result"
    );
    assert!(
        !request.contains("sc-reduced"),
        "unreduced request must not contain unresolved reduction stubs"
    );

    let sidecar_text = std::fs::read_to_string(&sidecar_path).unwrap();
    let sidecar = Session::from_sidecar_str(&sidecar_text).unwrap();
    assert_eq!(sidecar.messages.len(), before + 2);
    assert!(sidecar_text.contains(USER_MARKER));
    assert!(sidecar_text.contains(ASSISTANT_MARKER));

    let exported = home.join("continued.claude.jsonl");
    let conv = run(
        &home,
        &[
            "convert",
            &name,
            "--to",
            "claude-code",
            "--out",
            exported.to_str().unwrap(),
        ],
    );
    assert!(conv.status.success(), "{}", stderr(&conv));
    let export_text = std::fs::read_to_string(exported).unwrap();
    assert!(export_text.contains(USER_MARKER));
    assert!(export_text.contains(ASSISTANT_MARKER));

    let meta: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.meta.json"))).unwrap(),
    )
    .unwrap();
    assert_eq!(meta["reduced"], true, "the sidecar family still exists");
    assert_eq!(meta["stub_count"], 0, "the current full view has no stubs");

    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_eq!(log["reductions"].as_array().unwrap().len(), 0);
    assert_eq!(
        log["expanded"].as_array().unwrap().len(),
        1,
        "--no-reduced must durably represent the full view as expand-all"
    );

    let inspected = run(&home, &["inspect", &name, "--json"]);
    assert!(inspected.status.success(), "{}", stderr(&inspected));
    let inspected: serde_json::Value = serde_json::from_slice(&inspected.stdout).unwrap();
    assert_eq!(inspected["session"]["reduced"]["stub_count"], 0);
    assert!(
        !inspected.to_string().contains("sc-reduced"),
        "inspect must agree that the saved full view has no active stubs"
    );

    let reopened = run(&home, &["chat", "--last"]);
    assert!(reopened.status.success(), "{}", stderr(&reopened));
    assert!(
        stderr(&reopened).contains(&format!(
            "Continuing reduced session ({}-message view; {} full messages).",
            before + 3,
            before + 2
        )),
        "ordinary reopen must report the full expanded view it actually loads: {}",
        stderr(&reopened)
    );

    let reopened_log: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(sessions_dir(&home).join(format!("{name}.reduction.json")))
            .unwrap(),
    )
    .unwrap();
    assert_eq!(reopened_log["reductions"].as_array().unwrap().len(), 0);
    assert_eq!(reopened_log["expanded"].as_array().unwrap().len(), 1);

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

#[test]
fn inspect_reduced_session_rejects_malformed_persisted_working_view() {
    let home = fresh_home("inspect-malformed-view");
    let fixture = write_big_fixture(&home);
    let name = mint_reduced_session(&home, &fixture);
    std::fs::write(
        sessions_dir(&home).join(format!("{name}.jsonl")),
        "this is not a ChatMessage\n",
    )
    .unwrap();

    let out = run(&home, &["inspect", &name, "--json"]);
    assert!(!out.status.success(), "malformed persisted view must fail");
    assert!(
        stderr(&out).contains("parsing stored working view"),
        "failure must name the broken working view: {}",
        stderr(&out)
    );
    assert!(
        stdout(&out).is_empty(),
        "inspect must not print a projection after rejecting the persisted view"
    );

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

#[test]
fn inspect_reduced_session_rejects_unreadable_present_working_view() {
    let home = fresh_home("inspect-unreadable-view");
    let fixture = write_big_fixture(&home);
    let name = mint_reduced_session(&home, &fixture);
    let transcript = sessions_dir(&home).join(format!("{name}.jsonl"));
    std::fs::create_dir(&transcript).unwrap();

    let out = run(&home, &["inspect", &name, "--json"]);
    assert!(
        !out.status.success(),
        "present but unreadable working view must fail"
    );
    assert!(
        stderr(&out).contains("reading stored working view"),
        "failure must name the unreadable working view: {}",
        stderr(&out)
    );
    assert!(
        stdout(&out).is_empty(),
        "inspect must not print a projection after a working-view read error"
    );

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

#[test]
fn inspect_and_convert_on_non_reduced_input_are_unaffected() {
    // Regression guard (C7(b)): a literal, non-reduced session file's
    // `inspect`/`convert` output must carry none of the new reduced-only
    // markers.
    let home = fresh_home("regression");
    let fixture = write_big_fixture(&home);

    let insp = run(&home, &["inspect", fixture.to_str().unwrap()]);
    assert!(insp.status.success());
    let insp_text = stdout(&insp);
    assert!(
        !insp_text.contains("⊟ reduced"),
        "non-reduced inspect must carry no reduced tag"
    );
    assert!(
        !insp_text.to_lowercase().contains("reduced  yes")
            && !insp_text.contains("reduced      yes"),
        "non-reduced inspect must carry no `reduced` row:\n{insp_text}"
    );

    let out_path = home.join("plain-convert.jsonl");
    let conv = run(
        &home,
        &[
            "convert",
            fixture.to_str().unwrap(),
            "--to",
            "codex",
            "-o",
            out_path.to_str().unwrap(),
        ],
    );
    assert!(conv.status.success());
    assert!(
        !stderr(&conv).contains("fidelity:"),
        "non-reduced convert must not print a fidelity line: {}",
        stderr(&conv)
    );

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

#[test]
fn expand_then_reduce_restores_the_same_id_via_repl() {
    let home = fresh_home("expand-reduce");
    let fixture = write_big_fixture(&home);
    let id = expected_id(&fixture);

    let stdin = format!("/expand {id}\n/reduce\n");
    let out = run_with_stdin(
        &home,
        &["resume", fixture.to_str().unwrap(), "--reduced"],
        &stdin,
    );
    let err = stderr(&out);

    let expand_line = err
        .lines()
        .find(|l| l.contains("expanded") && l.contains(&id))
        .unwrap_or_else(|| panic!("no `⤢ expanded {id}` line in:\n{err}"));
    assert!(
        expand_line.contains('+'),
        "expand line must show a byte delta: {expand_line}"
    );
    assert!(
        expand_line.contains("~+"),
        "expand line must show a token delta: {expand_line}"
    );
    assert!(
        expand_line.contains("view now"),
        "expand line must show the new view size: {expand_line}"
    );

    let reduce_line = err
        .lines()
        .find(|l| l.contains("re-reduced"))
        .unwrap_or_else(|| panic!("no `⤵ re-reduced` line in:\n{err}"));
    assert!(
        reduce_line.contains("stubs"),
        "reduce line must show a stub count: {reduce_line}"
    );

    // Find the minted store name from the banner and check final on-disk
    // state: the SAME id is present in both the persisted view and the log.
    let sidecar_line = err
        .lines()
        .find(|l| l.contains("full copy:"))
        .expect("banner must name the sidecar");
    let sidecar_path = sidecar_line.split("full copy:").nth(1).unwrap().trim();
    let name = Path::new(sidecar_path)
        .file_name()
        .unwrap()
        .to_str()
        .unwrap()
        .strip_suffix(".sidecar.jsonl")
        .unwrap();

    let jsonl_path = sessions_dir(&home).join(format!("{name}.jsonl"));
    let jsonl = std::fs::read_to_string(&jsonl_path).unwrap();
    // TR-6: the fixture's first `cargo test` run is superseded by the later
    // identical-args run before this test's re-reduce ever runs, so the
    // restored stub's kind is `superseded`, not `tool-output` (the id is
    // unchanged: same reduction, only the kind token differs post-TR-6).
    assert!(
        jsonl.contains(&format!("sc-reduced superseded {id}")),
        "persisted view must contain the restored stub for {id}:\n{jsonl}"
    );

    let log_path = sessions_dir(&home).join(format!("{name}.reduction.json"));
    let log: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&log_path).unwrap()).unwrap();
    let ids: Vec<&str> = log["reductions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["id"].as_str().unwrap())
        .collect();
    assert_eq!(
        ids,
        vec![id.as_str()],
        "the final log must contain the SAME id after expand+reduce"
    );

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

#[test]
fn expand_bogus_id_errors_with_hint_and_changes_nothing() {
    let home = fresh_home("expand-bogus");
    let fixture = write_big_fixture(&home);

    let out = run_with_stdin(
        &home,
        &["resume", fixture.to_str().unwrap(), "--reduced"],
        "/expand bogus-id\n",
    );
    let err = stderr(&out);
    assert!(err.contains("no reduction with id"), "missing error: {err}");
    assert!(
        err.contains("bogus-id"),
        "error must name the bogus id: {err}"
    );
    assert!(
        err.contains("valid ids"),
        "error must hint at valid ids: {err}"
    );

    // Nothing was ever persisted: `/expand` returned before calling
    // `persist_full_view`, and no other command in this scripted session
    // ever calls `persist_session` either.
    let sidecar_line = err
        .lines()
        .find(|l| l.contains("full copy:"))
        .expect("banner must name the sidecar");
    let sidecar_path = sidecar_line.split("full copy:").nth(1).unwrap().trim();
    let name = Path::new(sidecar_path)
        .file_name()
        .unwrap()
        .to_str()
        .unwrap()
        .strip_suffix(".sidecar.jsonl")
        .unwrap();
    let jsonl_path = sessions_dir(&home).join(format!("{name}.jsonl"));
    assert!(
        !jsonl_path.exists(),
        "a bogus /expand must not create/modify the persisted view"
    );

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