supercode-core 0.2.1

A lightweight, fully-customizable AI coding agent SDK in Rust. Talks to any model via OpenRouter or any OpenAI-compatible endpoint.
Documentation
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
//! §4.3 — CONTINUE-WITH-REDUCTION: per harness X in {claude, codex, opencode,
//! pi}, measure the reduction ratio with the production C9 token estimator
//! against the harness's OWN replay slice (not the full linearization, S3),
//! then prove reversibility via a hash-verified `invert` over a real
//! `SidecarWriter`-backed sidecar (`docs/interop/opencode-pi-spec.md` §4.3).
//! Mirrors `reduction_verify.rs`'s use of `project`/`verify_log`.
//!
//! **Fixed per the skeptic-panel land-blocker on Wave C:** the committed §4.1/
//! §4.2 fixtures have no heavy tool output (the largest is 27 bytes), and an
//! earlier version of this test scaled the truncation/dedup thresholds down
//! ~100x from their production defaults to manufacture a nonzero ratio on
//! those tiny fixtures — opencode/pi, whose fixtures happen to have even less
//! to work with, still landed at a STRUCTURAL 0% (vacuous truth: reversibility
//! trivially holds over an empty reduction log). That proved only "the
//! plumbing runs", not that reduction+reversibility hold on a session loaded
//! from each harness.
//!
//! The fix, per each harness X: `S = load(fixtureX)`, then APPEND a genuine
//! heavy continuation to `S.messages` (real tool-call/tool-result turns —
//! duplicate `cat` output, a repeated `cargo test` command with a changed
//! result, a large `write_file` payload — see [`heavy_continuation`]), and
//! measure `project()` at the **production-default** [`ReductionPolicy`]
//! (`ReductionPolicy::default()`, unmodified — see [`production_policy`]).
//! This is a real "continued session with heavy tool output", loaded through
//! each harness's own parser, at the thresholds actually shipped — not a
//! lowered bar. Each harness's row is asserted to produce `n > 0` real
//! reductions of more than one kind; a `0`-reduction row is treated as a hard
//! test failure (the exact vacuous-truth shape this fix exists to close),
//! not a silently-accepted "n/a".

mod interop_common;

use std::path::{Path, PathBuf};

use interop_common::{core, msg_eq_multimodal, replay_eligible};
use supercode::reduce::{
    export_session, invert, project, reduce_to_fit, reduction_id, verify_log, ReductionKind,
    ReductionLog, ReductionPolicy, REDUCTION_METADATA_KEY, REDUCTION_SENTINEL,
};
use supercode::session::{Session, SessionFormat};
use supercode::sidecar::SidecarWriter;
use supercode::tokens::estimate_view_tokens;
use supercode::{ChatMessage, FunctionCall, Role, ToolCall};

fn fixture(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name)
}

fn fixture_file_for(f: SessionFormat) -> &'static str {
    match f {
        SessionFormat::ClaudeCode => "claude_code_session.jsonl",
        SessionFormat::Codex => "codex_session.jsonl",
        SessionFormat::OpenCode => "opencode_session.jsonl",
        SessionFormat::Pi => "pi_session.jsonl",
        SessionFormat::Grok => "grok_session/chat_history.jsonl",
    }
}

fn fname(f: SessionFormat) -> &'static str {
    match f {
        SessionFormat::ClaudeCode => "claude",
        SessionFormat::Codex => "codex",
        SessionFormat::OpenCode => "opencode",
        SessionFormat::Pi => "pi",
        SessionFormat::Grok => "grok",
    }
}

fn load_fixture(f: SessionFormat) -> Session {
    let path = fixture(fixture_file_for(f));
    match f {
        SessionFormat::ClaudeCode => Session::from_claude_code(path).unwrap(),
        SessionFormat::Codex => Session::from_codex(path).unwrap(),
        SessionFormat::OpenCode => Session::from_opencode(path).unwrap(),
        SessionFormat::Pi => Session::from_pi(path).unwrap(),
        SessionFormat::Grok => Session::from_grok(path).unwrap(),
    }
}

/// **Disclosure (per the panel's "no hand-waving" requirement):** the
/// production default, completely unmodified. Every threshold the earlier
/// (vacuous) version of this test scaled down —
/// `tool_output_keep_bytes`/`tool_output_trigger_bytes`/
/// `duplicate_output_min_bytes`/`supersede_min_bytes` — is left at its
/// shipped default (`4096`/`8192`/`256`/`256`). [`heavy_continuation`] is
/// sized to clear these real thresholds instead of the other way around,
/// which is the whole point of this fix: the fixture (now the fixture PLUS a
/// realistic continuation) is what changed, never the policy.
fn production_policy() -> ReductionPolicy {
    ReductionPolicy::default()
}

/// A deterministic, all-ASCII filler string of exactly `target_len` bytes,
/// beginning with `[label]` so a failing assertion's printed content stays
/// human-recognizable. Two calls with the same `label`/`target_len` are
/// byte-identical (needed below for the duplicate-output pair); two calls
/// with different `label`s are never byte-identical (needed for the
/// superseded-run trio, whose runs must NOT dedup against each other).
fn big(label: &str, target_len: usize) -> String {
    let mut s = format!("[{label}] ");
    while s.len() < target_len {
        s.push_str("the quick brown fox jumps over the lazy dog; ");
    }
    s.truncate(target_len);
    s
}

/// An assistant turn issuing one tool call (`name(args)`, id `id`) — the
/// generic `ChatMessage` shape every one of the four loaders normalizes an
/// assistant tool-call turn into, regardless of source wire format.
fn tool_call(id: &str, name: &str, args: serde_json::Value) -> ChatMessage {
    ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(vec![ToolCall {
            id: id.to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: name.to_string(),
                arguments: args.to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

/// A genuine, real "continued session with heavy tool output" — the thing
/// §4.3 asks for, appended after each harness's imported fixture prefix.
/// Tool names (`bash`/`write_file`) are chosen to land on
/// [`ReductionPolicy`]'s OWN production-default recognition tables
/// (`supersede_command_fields`'s `bash`->`command`,
/// `tool_input_elidable_fields`'s `write_file`->`content`) — the same names
/// opencode/pi's own native tools already carry verbatim (see
/// `opencode_session.jsonl`/`pi_session.jsonl`'s own `write_file`/`bash` tool
/// parts) — rather than inventing a bespoke policy per harness.
///
/// Six tool-call/tool-result turns, each large enough to clear every
/// production trigger (8192B for truncation/tool-input-elision, 256B for
/// dedup/supersede), engineered to exercise FOUR independent reduction
/// kinds at once:
/// - `cat build.log` run twice with byte-identical output -> TR-2
///   `DuplicateOutput` (the 2nd run dedups against the 1st).
/// - `cargo test` run three times (two distinct failures, then a pass) ->
///   TR-6 `Superseded` (the oldest, farthest-from-tail run supersedes; the
///   production `protect_last_n`/`supersede_protect_last_n` (both default
///   `3`) keep the newest few runs — including the 2nd failure — fully
///   visible, which is itself the intended "protect recent" behavior, not a
///   bug in this fixture).
/// - The oldest `cat build.log` run additionally clears A7's own
///   `tool_output_trigger_bytes` (8192B) once TR-2 has claimed its
///   duplicate partner, giving a genuine `ToolOutputTruncated` too.
/// - A `write_file` call with a 12,000-byte `content` argument ->
///   TR-10 `ToolInputElided`.
fn heavy_continuation() -> Vec<ChatMessage> {
    vec![
        // Two identical `cat build.log` runs (12,000B each) -> DuplicateOutput
        // on the 2nd, ToolOutputTruncated on the 1st (once TR-2 claims the
        // 2nd, the 1st is still a fully-visible, unprotected, oversized
        // result — a genuine A7 candidate).
        tool_call(
            "ir4-call-1",
            "bash",
            serde_json::json!({"command": "cat build.log"}),
        ),
        ChatMessage::tool_result("ir4-call-1", "bash", big("BUILD-LOG-CONTENTS", 12_000)),
        tool_call(
            "ir4-call-2",
            "bash",
            serde_json::json!({"command": "cat build.log"}),
        ),
        ChatMessage::tool_result("ir4-call-2", "bash", big("BUILD-LOG-CONTENTS", 12_000)),
        // Same command run three times with different (large) results -> the
        // oldest becomes Superseded; the newer two stay in the protected
        // recency window.
        tool_call(
            "ir4-call-3",
            "bash",
            serde_json::json!({"command": "cargo test"}),
        ),
        ChatMessage::tool_result("ir4-call-3", "bash", big("CARGO-TEST-FAIL-RUN-1", 12_000)),
        tool_call(
            "ir4-call-4",
            "bash",
            serde_json::json!({"command": "cargo test"}),
        ),
        ChatMessage::tool_result("ir4-call-4", "bash", big("CARGO-TEST-FAIL-RUN-2", 12_000)),
        // A large disk-persisting write -> ToolInputElided on the assistant's
        // own `content` argument.
        tool_call(
            "ir4-call-5",
            "write_file",
            serde_json::json!({"path": "output.log", "content": big("WRITE-FILE-PAYLOAD", 12_000)}),
        ),
        ChatMessage::tool_result(
            "ir4-call-5",
            "write_file",
            "wrote 12000 bytes to output.log",
        ),
        // The newest `cargo test` run (a pass) -> names the Superseded chain's
        // successor; stays fully visible (protected recency window).
        tool_call(
            "ir4-call-6",
            "bash",
            serde_json::json!({"command": "cargo test"}),
        ),
        ChatMessage::tool_result("ir4-call-6", "bash", big("CARGO-TEST-PASS-RUN-3", 12_000)),
    ]
}

/// The bare variant name of a `ReductionKind` (from its `Debug` form, up to
/// the first `{`/space) — for the printed per-kind breakdown, without
/// needing to hand-maintain a match arm per variant here.
fn kind_name(kind: &supercode::reduce::ReductionKind) -> String {
    let dbg = format!("{kind:?}");
    dbg.split(['{', ' ']).next().unwrap_or(&dbg).to_string()
}

/// One harness's measured reduction: builds the continued session (imported
/// fixture prefix + [`heavy_continuation`]), prints `reduction[X] = before ->
/// after tokens (pct% reduced, n reduction(s): kinds)`, and asserts
/// reversibility + hash-verification + no-silent-reduction over a REAL
/// `SidecarWriter`-backed sidecar file (not just the in-memory `Session`) —
/// and, unlike the earlier vacuous version of this test, asserts `n > 0`
/// real, multi-kind reductions.
fn measure_and_verify(format: SessionFormat) {
    let imported = load_fixture(format);
    let continuation = heavy_continuation();

    // The real continued session §4.3 asks for: the harness's own imported
    // prefix, plus a genuine heavy-tool-output continuation appended after
    // it — loaded through that harness's own parser, not a synthetic
    // from-scratch session.
    let mut full = imported.clone();
    full.messages.extend(continuation.iter().cloned());

    // §2.1/S3: the baseline is the harness's ACTUAL replay slice (compacted-
    // out history excluded), not the full linearization.
    let replay = replay_eligible(&full.messages);
    let before = estimate_view_tokens(&replay);

    // A real SidecarWriter-backed file: the imported prefix via `create`
    // (full-fidelity native-v2, exactly the shape a live agent's recorder
    // writes at import time), then every continuation turn via `append` —
    // exactly how a live recorder appends turn-by-turn
    // (`sidecar_family_reduction_resolve.rs`'s own pattern) — not just
    // `&full` held in memory.
    let sidecar_path = std::env::temp_dir().join(format!(
        "sc-reduction-metric-{}-{}.jsonl",
        std::process::id(),
        fname(format)
    ));
    {
        let mut writer = SidecarWriter::create(&sidecar_path, &imported).unwrap();
        for msg in &continuation {
            writer.append(msg).unwrap();
        }
    }
    let sidecar_text = std::fs::read_to_string(&sidecar_path).unwrap();
    let sidecar_session = Session::from_sidecar_str(&sidecar_text).unwrap();
    std::fs::remove_file(&sidecar_path).ok();

    assert_eq!(
        sidecar_session.messages.len(),
        full.messages.len(),
        "{format:?}: the sidecar must record every message of the continued session \
         (imported prefix + heavy continuation), positionally, before any reduction \
         is even minted"
    );

    let policy = production_policy();
    let (view, log) = project(&full, &policy, &ReductionLog::default());

    // The whole point of this fix: a real, non-vacuous, multi-kind
    // reduction — never a silently-accepted 0.
    assert!(
        !log.reductions.is_empty(),
        "{format:?}: the heavy continuation produced ZERO reductions at production \
         defaults — this is exactly the vacuous-truth failure mode this fix exists to \
         close; if this genuinely can't be built for this harness, that is a STOP-and-\
         report condition, not a silently-passing test"
    );
    let mut kinds: Vec<String> = log.reductions.iter().map(|r| kind_name(&r.kind)).collect();
    kinds.sort();
    let distinct_kinds: std::collections::BTreeSet<&String> = kinds.iter().collect();
    assert!(
        distinct_kinds.len() > 1,
        "{format:?}: the heavy continuation must exercise more than one reduction kind \
         (got only {kinds:?}) — a single-kind result is weaker evidence than the \
         continuation is built to provide"
    );

    let after = estimate_view_tokens(&replay_eligible(&view));
    let ratio = if before == 0 {
        1.0
    } else {
        after as f64 / before as f64
    };
    let pct_reduced = (1.0 - ratio) * 100.0;
    println!(
        "reduction[{}] = {} -> {} tokens ({:.1}% reduced, {} reduction(s): {})",
        fname(format),
        before,
        after,
        pct_reduced,
        log.reductions.len(),
        kinds.join(", "),
    );

    // Reversibility: invert() reconstructs the canonical core EXACTLY
    // (msg_eq_multimodal, S2's stronger comparator — zero semantic loss,
    // including multimodal content).
    let full_reconstructed = invert(&view, &log, &sidecar_session)
        .unwrap_or_else(|e| panic!("{format:?}: invert failed: {e}"));
    let before_core = core(&full.messages);
    let after_core = core(&full_reconstructed);
    assert_eq!(
        before_core.len(),
        after_core.len(),
        "{format:?}: invert changed message count"
    );
    for (i, (a, b)) in before_core.iter().zip(&after_core).enumerate() {
        assert!(
            msg_eq_multimodal(a, b),
            "{format:?}: invert lost/changed message {i}:\n  before: {a:?}\n  after:  {b:?}"
        );
    }

    // Every SidecarPtr verifies (hash-verified reversibility, catches a
    // pointer to content absent from the sidecar).
    verify_log(&log, &sidecar_session)
        .unwrap_or_else(|e| panic!("{format:?}: verify_log failed: {e}"));

    // No silent reduction: every reduction leaves an in-transcript stub.
    let stub_count = view.iter().filter(|m| reduction_id(m).is_some()).count();
    assert_eq!(
        stub_count,
        log.reductions.len(),
        "{format:?}: stub count must equal reduction count (no silent reduction)"
    );

    // Ratio sanity: never inflated (after <= before, modulo estimator
    // rounding noise from wire-format overhead on structurally-identical
    // stub vs. original messages, which cannot happen here since a
    // reduction only ever shrinks content).
    assert!(
        after <= before,
        "{format:?}: reduction must never INCREASE the estimated token count ({before} -> {after})"
    );
}

// ---------------------------------------------------------------------------
// P6 gate 4 (`docs/composable-harness/COMPOSABLE-HARNESS-DESIGN.md` §5.2):
// "the A13 reduction ratio as a regression bound." `reduction_metric_per_
// harness` above already asserts `n > 0` reductions and `after <= before`
// (never-inflates) — this turns the MEASURED ratio itself into a pinned
// floor: token reduction is the product's #1-priority differentiator (the
// rate-limit-rescue flagship), so a regression that quietly makes the
// reducer LESS effective on this exact, deterministic fixture+continuation
// input is high-severity and must fail CI, not just "still positive".
//
// Pinned at the EXACT measured `after`-token ceiling per harness (not a
// rounded/loosened floor — `before` is asserted EXACTLY too, as a sanity
// check that the fixture/continuation input itself hasn't silently
// changed out from under the pin). Both are pure, deterministic integer
// arithmetic over a fixed fixture + fixed `heavy_continuation()` — no
// margin is needed or added; a real regression of even one byte's worth of
// estimated tokens trips this. Measured via `cargo test -p supercode-core
// --test interop_reduction_metric -- --nocapture` at HEAD (see
// `reduction_metric_per_harness`'s own printed table for the same numbers,
// restated here as hard ceilings rather than only being visible in stdout).
// ---------------------------------------------------------------------------

/// `(harness, before_tokens, after_tokens_ceiling)` — exact measured values
/// at pin time. `before` must match exactly (the input didn't change);
/// `after` must not exceed the pin (the reducer didn't get weaker).
const REDUCTION_RATIO_FLOOR: [(&str, u64, u64); 4] = [
    // Re-pinned after Claude active-branch projection stopped replaying the
    // fixture's sidechain sibling. Both sides fell by the same five tokens;
    // the reducer's measured savings are unchanged.
    ("claude", 18528, 7691),
    ("codex", 20254, 9417),
    ("opencode", 18463, 7627),
    ("pi", 18511, 7675),
];

#[test]
fn reduction_ratio_regression_floor() {
    for &format in &[
        SessionFormat::ClaudeCode,
        SessionFormat::Codex,
        SessionFormat::OpenCode,
        SessionFormat::Pi,
    ] {
        let (harness, before_pin, after_ceiling) = REDUCTION_RATIO_FLOOR
            .iter()
            .find(|(h, _, _)| *h == fname(format))
            .copied()
            .unwrap_or_else(|| panic!("{format:?}: no pinned floor row — add one"));

        let imported = load_fixture(format);
        let continuation = heavy_continuation();
        let mut full = imported.clone();
        full.messages.extend(continuation.iter().cloned());

        let replay = replay_eligible(&full.messages);
        let before = estimate_view_tokens(&replay);
        assert_eq!(
            before, before_pin,
            "{harness}: pre-reduction token count drifted from the pinned {before_pin} (got \
             {before}) — the fixture or heavy_continuation() input changed; re-measure and \
             re-pin deliberately (this is a sanity check on the INPUT, not the reducer)"
        );

        let policy = production_policy();
        let (view, _log) = project(&full, &policy, &ReductionLog::default());
        let after = estimate_view_tokens(&replay_eligible(&view));

        assert!(
            after <= after_ceiling,
            "{harness}: reduction-ratio regression — post-reduction token count {after} exceeds \
             the pinned ceiling of {after_ceiling} (before={before}). At production defaults, \
             the reducer is now LESS effective on this exact, deterministic fixture than it was \
             at pin time — token reduction is priority #1 (the rate-limit-rescue flagship); this \
             is a high-severity regression, not a rounding blip."
        );

        let pct_reduced_at_pin = (1.0 - after_ceiling as f64 / before_pin as f64) * 100.0;
        let pct_reduced_now = (1.0 - after as f64 / before as f64) * 100.0;
        println!(
            "reduction_ratio_floor[{harness}]: pinned {before_pin}->{after_ceiling} \
             ({pct_reduced_at_pin:.1}% reduced) | measured now {before}->{after} \
             ({pct_reduced_now:.1}% reduced)"
        );
    }
}

#[test]
fn reduction_metric_per_harness() {
    println!("\n=== §4.3 CONTINUE-WITH-REDUCTION (measured ratio + reversibility) ===");
    for &format in &[
        SessionFormat::ClaudeCode,
        SessionFormat::Codex,
        SessionFormat::OpenCode,
        SessionFormat::Pi,
    ] {
        measure_and_verify(format);
    }
}

// ---------------------------------------------------------------------------
// Corpus-gated flagship (SUPERCODE_CORPUS=1): the rate-limit-rescue
// measurement on a large real supported-harness session, asserting the
// achieved ratio and disk-reloaded reversibility. `#[ignore]`d because the
// private corpus is supplied explicitly by the maintainer.
// ---------------------------------------------------------------------------

#[test]
#[ignore = "requires a large real harness session; set SUPERCODE_CORPUS=1 and \
            SUPERCODE_CORPUS_SESSION=<path to a real session file>"]
fn corpus_gated_flagship_reduction_ratio() {
    if std::env::var("SUPERCODE_CORPUS").is_err() {
        panic!(
            "SUPERCODE_CORPUS not set — this corpus test asserts nothing without a real, \
             large harness session; set SUPERCODE_CORPUS=1 and SUPERCODE_CORPUS_SESSION=<path>."
        );
    }
    let path = std::env::var("SUPERCODE_CORPUS_SESSION")
        .expect("set SUPERCODE_CORPUS_SESSION=<path to a real harness session file>");
    let s = Session::load(&path).unwrap();

    let replay = replay_eligible(&s.messages);
    let before = estimate_view_tokens(&replay);

    let sidecar_path = std::env::temp_dir().join(format!(
        "sc-reduction-metric-corpus-{}.jsonl",
        std::process::id()
    ));
    {
        let _writer = SidecarWriter::create(&sidecar_path, &s).unwrap();
    }
    let sidecar_text = std::fs::read_to_string(&sidecar_path).unwrap();
    let sidecar_session = Session::from_sidecar_str(&sidecar_text).unwrap();
    std::fs::remove_file(&sidecar_path).ok();

    // Full production defaults here — this is the real flagship measurement,
    // not the fixture-scaled policy above.
    let policy = ReductionPolicy::default();
    let (view, log) = project(&s, &policy, &ReductionLog::default());
    let after = estimate_view_tokens(&replay_eligible(&view));
    let ratio = if before == 0 {
        1.0
    } else {
        after as f64 / before as f64
    };

    println!(
        "corpus flagship: {} -> {} tokens ({:.1}% reduced, ratio={:.4}, {} reductions) — {}",
        before,
        after,
        (1.0 - ratio) * 100.0,
        ratio,
        log.reductions.len(),
        path
    );

    let target = before.saturating_mul(35).div_ceil(100);
    let (target_view, target_log, target_policy) =
        reduce_to_fit(&s.messages, &policy, &ReductionLog::default(), |view| {
            estimate_view_tokens(&replay_eligible(view)) <= target
        });
    let target_after = estimate_view_tokens(&replay_eligible(&target_view));
    let mut kinds = std::collections::BTreeMap::<&'static str, usize>::new();
    for reduction in &target_log.reductions {
        let name = match reduction.kind {
            ReductionKind::ToolOutputTruncated { .. } => "ToolOutputTruncated",
            ReductionKind::FileReadElided { .. } => "FileReadElided",
            ReductionKind::ImageRedacted { .. } => "ImageRedacted",
            ReductionKind::TurnsCleared { .. } => "TurnsCleared",
            ReductionKind::ToolInputElided { .. } => "ToolInputElided",
            ReductionKind::OutputNormalized { .. } => "OutputNormalized",
            ReductionKind::FileReadDiffed { .. } => "FileReadDiffed",
            ReductionKind::DuplicateOutput { .. } => "DuplicateOutput",
            ReductionKind::Superseded { .. } => "Superseded",
        };
        *kinds.entry(name).or_default() += 1;
    }
    println!(
        "corpus 35%-target: {} -> {} tokens (ratio={:.4}, {} reductions, kinds={:?})",
        before,
        target_after,
        target_after as f64 / before as f64,
        target_log.reductions.len(),
        kinds
    );
    assert!(
        target_after <= target,
        "35% target missed: {target_after} retained tokens > {target} target tokens"
    );
    let mut before_clear_policy = target_policy.clone();
    before_clear_policy.clear_turns_older_than = None;
    let (_, before_clear_log) = project(&s, &before_clear_policy, &ReductionLog::default());
    let clear_range = target_log.reductions.iter().find_map(|reduction| {
        if let ReductionKind::TurnsCleared { first, last, .. } = reduction.kind {
            Some((first, last))
        } else {
            None
        }
    });
    let swallowed_by_clear = clear_range.map_or(0, |(first, last)| {
        before_clear_log
            .reductions
            .iter()
            .filter(|reduction| {
                reduction.ptr.addr.index >= first && reduction.ptr.addr.index <= last
            })
            .count()
    });
    println!(
        "corpus pass-order: {} pre-A10 claims; {} swallowed by A10 and removed from the final log (no double count)",
        before_clear_log.reductions.len(),
        swallowed_by_clear,
    );
    let target_log_path = std::env::temp_dir().join(format!(
        "sc-reduction-metric-corpus-{}.reduction.json",
        std::process::id()
    ));
    std::fs::write(
        &target_log_path,
        serde_json::to_vec_pretty(&target_log).unwrap(),
    )
    .unwrap();
    let reloaded_target_log: ReductionLog =
        serde_json::from_slice(&std::fs::read(&target_log_path).unwrap()).unwrap();
    std::fs::remove_file(&target_log_path).ok();
    verify_log(&reloaded_target_log, &sidecar_session).unwrap();
    let target_full = invert(&target_view, &reloaded_target_log, &sidecar_session).unwrap();
    assert_eq!(
        sidecar_session.messages, target_full,
        "disk-reloaded target log must restore every canonical message byte-exact"
    );
    let claude_export = export_session(&sidecar_text, SessionFormat::ClaudeCode).unwrap();
    assert_eq!(claude_export.matches(REDUCTION_SENTINEL).count(), 0);
    assert_eq!(claude_export.matches(REDUCTION_METADATA_KEY).count(), 0);

    let full = invert(&view, &log, &sidecar_session).unwrap();
    let before_core = core(&s.messages);
    let after_core = core(&full);
    assert_eq!(before_core.len(), after_core.len());
    for (a, b) in before_core.iter().zip(&after_core) {
        assert!(msg_eq_multimodal(a, b));
    }
    verify_log(&log, &sidecar_session).unwrap();
}