supercode-harness 0.4.13

The optional native Supercode agent and tool harness
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
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
//! Acceptance tests for SPEC.md TR-4/T30 (`ReductionKind::OutputNormalized`
//! — terminal-noise normalization): ANSI/redraw collapse over bash tool
//! output, wired through the same `project`/`invert`/rehydrate machinery
//! every other reduction kind uses.
//!
//! Each test names the TR-4.md acceptance-criterion id it proves
//! (`dev/01`..`dev/05`). `crates/harness/src/reduce/normalize.rs`'s own unit
//! tests cover the state-machine mechanics in isolation (SGR/CR/EL/CUU/CUD/
//! CHA, the exotic-DSR passthrough example, the truncated-escape/fuzz no-
//! panic sweep, determinism); this file covers the same reduction kind
//! wired through the real pipeline: `project_messages`, `invert`,
//! `verify_log`, `expand_reduction`, and `sidecar_search`.
//!
//! # Fixture provenance (`tests/fixtures/terminal/`)
//!
//! `cargo_build.raw` and `npm_install.raw` are GENUINE live captures taken
//! in this sandboxed worktree, byte-for-byte as emitted by the real tools —
//! not hand-typed:
//!
//! - `cargo_build.raw`: a throwaway crate (`tokio`/`clap`/`rand`/`chrono`/
//!   `itertools` deps, enough to produce a multi-crate build with cargo's
//!   real `Building [===>] N/76: crate-a, crate-b` progress bar) built under
//!   a real pseudo-terminal spawned via Python's `pty.openpty()` +
//!   `fcntl.ioctl(..., termios.TIOCSWINSZ, ...)` (cargo's progress renderer
//!   requires a real tty with a known window size — a plain pipe or the
//!   `script` command's fallback path here did not trigger it), running
//!   `cargo build --color always -j 2`, output captured verbatim from the
//!   pty master fd.
//! - `npm_install.raw`: `npm install webpack webpack-cli react react-dom
//!   typescript eslint --color=always`, captured the same way (real network
//!   access was available in this sandbox for the npm registry). Shows the
//!   real modern-npm idiom: a Braille spinner glyph + `ESC[1G` (CHA) +
//!   `ESC[0K` (EL) repeated, then the final summary lines.
//!
//! `pip_download.raw` and `docker_pull.raw` are hand-constructed,
//! deliberately modeled on the real, well-documented byte-level idioms of
//! `pip`'s `DownloadProgressBar` (`pip/_internal/cli/progress_bars.py`: a
//! `\r`-updated `|████...|` bar) and `docker pull`'s multi-layer renderer
//! (`moby/moby`'s `pkg/jsonmessage`: `ESC[<n>A` cursor-up to a layer's line,
//! `\r`, redraw, `ESC[K`, `ESC[<n>B` back down) — this sandbox has neither a
//! `pip`/`ensurepip` binary (verified: `pip`/`pip3` absent from `$PATH`,
//! `python3 -m ensurepip` reports "No module named ensurepip") nor a docker
//! daemon, so a live capture was not possible. TR-4.md's `dev/01` only
//! requires the cargo/npm fixtures to clear the 80% floor and requires
//! savings to be *reported* (not any particular figure) for pip/docker —
//! both real captures clear 80% (see
//! `cargo_and_npm_fixtures_meet_the_80_percent_reduction_floor`) and both
//! synthetic fixtures still exercise real coverage gaps the real captures
//! don't (docker's cursor-up/down multi-line redraw; pip's SGR "Successfully
//! installed" line mixed with many-frame `\r` bar updates).
//!
//! `plain_output.raw` is a plain multi-line `cargo test` result summary with
//! no `\r` and no escape sequences at all — the `dev/04` "untouched" fixture.
//!
//! Golden files (`*.golden.txt`) were generated by running this branch's own
//! `reduce::normalize::normalize` against each `.raw` fixture and are
//! checked in as goldens (a plain-text visual diff on review); they are not
//! independently authored.

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

use supercode_harness::reduce::rehydrate::{expand_reduction, sidecar_search};
use supercode_harness::reduce::{
    self, invert, normalize, project_messages, reduction_id, stub, verify_log, ReductionKind,
    ReductionLog, ReductionPolicy, REDUCTION_SENTINEL,
};
use supercode_harness::session::Session;
use supercode_harness::{ChatMessage, FunctionCall, Role, ToolCall};

fn fixtures_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/terminal")
}

fn load_raw(name: &str) -> String {
    std::fs::read_to_string(fixtures_dir().join(format!("{name}.raw")))
        .unwrap_or_else(|e| panic!("reading {name}.raw: {e}"))
}

fn load_golden(name: &str) -> String {
    std::fs::read_to_string(fixtures_dir().join(format!("{name}.golden.txt")))
        .unwrap_or_else(|e| panic!("reading {name}.golden.txt: {e}"))
}

fn pct_reduction(original: usize, normalized: usize) -> f64 {
    if original == 0 {
        0.0
    } else {
        100.0 * (1.0 - (normalized as f64 / original as f64))
    }
}

// ---- dev/01: fixture suite normalizes to final-rendered content, with the
// cargo/npm fixtures clearing an 80% byte-reduction floor ------------------

#[test]
fn cargo_and_npm_fixtures_meet_the_80_percent_reduction_floor() {
    for name in ["cargo_build", "npm_install"] {
        let raw = load_raw(name);
        let golden = load_golden(name);
        let normalized = normalize::normalize(&raw);
        assert_eq!(
            normalized, golden,
            "{name}: normalize() must match the checked-in golden"
        );
        let pct = pct_reduction(raw.len(), normalized.len());
        assert!(
            pct >= 80.0,
            "{name}: reduction {pct:.1}% must be >= 80% (orig={}, normalized={})",
            raw.len(),
            normalized.len()
        );
        println!(
            "{name}: {} B -> {} B ({pct:.1}% reduction)",
            raw.len(),
            normalized.len()
        );
    }
}

#[test]
fn pip_and_docker_fixtures_normalize_to_golden_final_rendered_content() {
    for name in ["pip_download", "docker_pull"] {
        let raw = load_raw(name);
        let golden = load_golden(name);
        let normalized = normalize::normalize(&raw);
        assert_eq!(
            normalized, golden,
            "{name}: normalize() must match the checked-in golden"
        );
        let pct = pct_reduction(raw.len(), normalized.len());
        assert!(
            pct > 0.0,
            "{name}: normalization must report a nonzero savings figure, got {pct:.1}%"
        );
        println!(
            "{name}: {} B -> {} B ({pct:.1}% reduction)",
            raw.len(),
            normalized.len()
        );
    }
}

// ---- shared harness for the full-pipeline tests below ---------------------

/// An assistant turn invoking `bash` (or another `NORMALIZE_TOOLS` name)
/// with tool-call id `call_id` — T30's candidate rule is keyed on the
/// INVOKING call's function name (paired via `tool_call_id`, exactly like
/// A8's `detect_reads`), not `ChatMessage::name` on the tool result itself
/// (see `reduce.rs`'s `detect_normalize_candidates` doc comment for why).
fn assistant_calling(call_id: &str, tool_name: &str) -> ChatMessage {
    ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(vec![ToolCall {
            id: call_id.to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: tool_name.to_string(),
                arguments: r#"{"command":"cargo build"}"#.to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

/// Build a minimal one-tool-result message slice: an assistant turn calling
/// `bash`, followed by its (noisy) tool result — enough for
/// [`project_messages`]'s T30 candidate detection (paired via
/// `tool_call_id`) to see it. `protect_last_n_tool_results` defaults to 3,
/// so a lone tool result would normally be "protected" from A7 truncation,
/// but `OutputNormalized` deliberately does not consult `protected` (see
/// `reduce.rs`'s T30 pass) — this harness intentionally exercises that most
/// recent-tool-result case, not an artificially aged one.
fn bash_result_messages(content: &str) -> Vec<ChatMessage> {
    vec![
        ChatMessage::user("please build the project"),
        assistant_calling("call-1", "bash"),
        ChatMessage::tool_result("call-1", "bash", content.to_string()),
    ]
}

fn bash_idx() -> usize {
    2
}

/// Wraps `msgs` in a bare `Session` (mirrors `reduce_dedup.rs::session_of`)
/// so it can serve as the `sidecar_session` argument `invert` needs — the
/// sidecar is just the unreduced message list.
fn session_of(msgs: Vec<ChatMessage>) -> Session {
    let mut session = Session::from_claude_code_str("").unwrap();
    session.messages = msgs;
    session
}

/// Find the (assumed unique) `OutputNormalized` reduction in `log`.
fn find_output_normalized(log: &ReductionLog) -> &reduce::Reduction {
    log.reductions
        .iter()
        .find(|r| matches!(r.kind, ReductionKind::OutputNormalized { .. }))
        .expect("expected an OutputNormalized reduction in the log")
}

// ---- dev/01 (continued) + dev/05: the reduction record + stub -------------

#[test]
fn project_messages_creates_output_normalized_reduction_for_a_noisy_bash_result() {
    let raw = load_raw("cargo_build");
    let msgs = bash_result_messages(&raw);
    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());

    assert_eq!(log.reductions.len(), 1, "{:?}", log.reductions);
    let r = find_output_normalized(&log);
    let (original_bytes, normalized_bytes) = match r.kind {
        ReductionKind::OutputNormalized {
            original_bytes,
            normalized_bytes,
        } => (original_bytes, normalized_bytes),
        _ => unreachable!(),
    };
    assert_eq!(original_bytes, raw.len());
    assert_eq!(normalized_bytes, normalize::normalize(&raw).len());
    assert!(original_bytes - normalized_bytes >= normalize::DEFAULT_MIN_SAVINGS);

    // The view's content is the normalized text, a blank-line separator,
    // then the stub placeholder — mirroring A7's own
    // `kept-prefix + "\n\n" + placeholder` construction.
    let expected_normalized = normalize::normalize(&raw);
    let view_content = view[bash_idx()].content.as_deref().unwrap();
    assert!(view_content.starts_with(&expected_normalized));
    assert!(view_content.ends_with(&r.placeholder));
    assert!(view_content.contains(REDUCTION_SENTINEL));

    // dev/05: the stub/trailer carries the reduction id via the shared `sc.
    // reduction` metadata mechanism (not just embedded in the text).
    assert_eq!(reduction_id(&view[bash_idx()]), Some(r.id.as_str()));

    // The placeholder follows the shared `[sc-reduced <kind> <id>: ...]`
    // grammar (reused rather than a bespoke sentinel — see `normalize::summary`'s
    // doc comment) so `stub::parse`/`Kind::from` work with no special-casing.
    let (kind, id, summary) = stub::parse(&r.placeholder).expect("placeholder must parse");
    assert_eq!(kind, stub::Kind::OutputNormalized);
    assert_eq!(kind.as_str(), "output-normalized");
    assert_eq!(id, r.id);
    assert!(summary.contains(&format!("{}", original_bytes)) || summary.contains("collapsed"));
}

// ---- dev/02: byte-exact invert ---------------------------------------------

fn load_codex_session() -> Session {
    Session::from_codex(
        Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/codex_session.jsonl"),
    )
    .unwrap()
}

/// Overwrite the `ordinal`-th `Role::Tool` message in `session` to look like
/// a `bash` result carrying `content` — same "overwrite an existing tool
/// message" idiom `reduce_projection.rs::pad_tool_output` /
/// `reduce_loop.rs::pad_tool_output` use for A7, extended to also set `name`
/// since T30's candidate rule is keyed on tool name.
fn bashify_tool_output(session: &mut Session, ordinal: usize, content: &str) -> usize {
    let idx = session
        .messages
        .iter()
        .enumerate()
        .filter(|(_, m)| m.role == Role::Tool)
        .map(|(i, _)| i)
        .nth(ordinal)
        .expect("session must have at least ordinal+1 tool messages");
    session.messages[idx].name = Some("bash".to_string());
    session.messages[idx].content = Some(content.to_string());
    idx
}

#[test]
fn invert_restores_raw_bytes_byte_exact_after_output_normalization() {
    let raw = load_raw("cargo_build");
    let mut session = load_codex_session();
    let idx = bashify_tool_output(&mut session, 0, &raw);

    let (view, log) = reduce::project(
        &session,
        &ReductionPolicy::default(),
        &ReductionLog::default(),
    );
    assert!(log.reductions.iter().any(
        |r| r.ptr.addr.index == idx && matches!(r.kind, ReductionKind::OutputNormalized { .. })
    ));

    verify_log(&log, &session).expect("log must verify cleanly against the sidecar");

    let restored = invert(&view, &log, &session).expect("invert must succeed");
    assert_eq!(
        restored[idx].content.as_deref(),
        Some(raw.as_str()),
        "invert must restore the exact raw (pre-normalization) bytes"
    );
    assert_eq!(
        reduction_id(&restored[idx]),
        None,
        "sc.reduction must be stripped after invert"
    );
}

#[test]
fn reduction_is_prefix_stable_across_reprojection() {
    let raw = load_raw("npm_install");
    let mut session = load_codex_session();
    let idx = bashify_tool_output(&mut session, 0, &raw);

    let (view1, log1) = reduce::project(
        &session,
        &ReductionPolicy::default(),
        &ReductionLog::default(),
    );
    // Re-projecting with the prior log as input must reproduce the SAME
    // reduction (same id, same placeholder, byte-identical content) rather
    // than minting a new one — the same prefix-stability guarantee A7/A8/A9
    // already carry.
    let (view2, log2) = reduce::project(&session, &ReductionPolicy::default(), &log1);

    assert_eq!(log1.reductions.len(), 1);
    assert_eq!(log1.reductions, log2.reductions);
    assert_eq!(view1[idx].content, view2[idx].content);
    assert_eq!(reduction_id(&view1[idx]), reduction_id(&view2[idx]));
}

// ---- dev/03: idempotence + unsupported-sequence passthrough through the
// full pipeline (not just the isolated `normalize()` unit) -----------------

#[test]
fn unsupported_escape_sequence_survives_through_the_full_pipeline() {
    // A cursor-position device-status-report (DSR, `ESC[6n`) — TR-4.md's own
    // named example of a sequence this module must never guess at — embedded
    // in an otherwise-noisy real capture, big enough to clear the savings
    // floor.
    let mut raw = load_raw("cargo_build");
    raw.push_str("before-dsr\x1b[6nafter-dsr\n");

    let msgs = bash_result_messages(&raw);
    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    let r = find_output_normalized(&log);

    let expected_normalized = normalize::normalize(&raw);
    let view_content = view[bash_idx()].content.as_deref().unwrap();
    assert!(view_content.starts_with(&expected_normalized));
    assert!(
        expected_normalized.contains("before-dsr\x1b[6nafter-dsr"),
        "the unsupported DSR sequence must survive verbatim in the normalized text: {expected_normalized:?}"
    );

    // Idempotence: normalizing the already-normalized text again changes
    // nothing further (computed independently of the view's exact
    // separator/trailer bytes, which are not this test's concern).
    assert_eq!(
        normalize::normalize(&expected_normalized),
        expected_normalized
    );

    // And it still round-trips byte-exact back to the raw pre-normalization
    // bytes (DSR sequence included) via the ordinary invert path.
    let mut session = load_codex_session();
    let idx = bashify_tool_output(&mut session, 0, &raw);
    let (view2, log2) = reduce::project(
        &session,
        &ReductionPolicy::default(),
        &ReductionLog::default(),
    );
    let restored = invert(&view2, &log2, &session).unwrap();
    assert_eq!(restored[idx].content.as_deref(), Some(raw.as_str()));
    assert_eq!(reduction_id(&view[bash_idx()]), Some(r.id.as_str()));
}

// ---- P7 safety net: a normalized rendering that is STILL oversized must
// fall through to A7's bounded truncation, never ride the wire uncapped
// (the "one reduction per message" invariant every kind in this pipeline
// shares, PLUS the wire-boundedness invariant A7 exists to guarantee) ------
//
// This test used to assert the opposite (that an oversized-after-
// normalization message is claimed by `OutputNormalized` and left
// unbounded on the wire) — that was the P7 runaway-output regression this
// fix closes: OutputNormalized only strips ANSI/CR bytes, it never bounds
// the REMAINING plain-text size, so a genuinely large, mostly-distinct
// terminal output (cargo/npm diagnostics, not just redraw noise) rode the
// wire uncapped once claimed. `reduce.rs`'s T30 pass now refuses to mint an
// `OutputNormalized` reduction whenever the normalized rendering still
// exceeds `tool_output_trigger_bytes`, leaving the message raw for A7's
// candidate scan to pick up and bound normally — reproducing this exact
// input proves the deferral, not just the "never both" invariant.
#[test]
fn oversized_normalized_output_falls_through_to_bounded_a7_truncation() {
    // Real ANSI noise (cargo_build) plus enough plain filler that the
    // NORMALIZED text still comfortably exceeds A7's default
    // `tool_output_trigger_bytes` (8,192B) — this is exactly the input that
    // used to trigger the P7 regression (OutputNormalized claiming an
    // unbounded view). Followed by 3 more (small) bash results so the noisy
    // one ages out of `protect_last_n_tool_results` (default 3) and is a
    // genuine A7 candidate on its own terms — proving the fallthrough is the
    // `reduced_this_run` bookkeeping (`reduce.rs`'s T30 pass deliberately NOT
    // claiming the index), not simply "recent tool results never get
    // truncated anyway".
    let mut raw = load_raw("cargo_build");
    raw.push_str(&"y".repeat(20_000));

    let normalized_bytes = normalize::normalize(&raw).len();
    let policy = ReductionPolicy::default();
    assert!(
        normalized_bytes > policy.tool_output_trigger_bytes,
        "test fixture must exercise the still-oversized-after-normalization case; got \
         {normalized_bytes}B normalized vs a {}B trigger",
        policy.tool_output_trigger_bytes
    );

    let mut msgs = vec![
        ChatMessage::user("please build the project"),
        assistant_calling("call-1", "bash"),
        ChatMessage::tool_result("call-1", "bash", raw.clone()),
    ];
    // A distinct tool identity ("noop", never "bash") for the padding calls:
    // this fixture predates TR-6 (T16 -- same-tool/same-args supersession),
    // and `assistant_calling` hardcodes its `command` argument regardless of
    // `tool_name` -- reusing "bash" here would incidentally make these 3
    // padding calls share TR-6's `(tool, canonicalized-args)` key with the
    // noisy `cargo build` call above, and (once aged past
    // `supersede_protect_last_n`) get it evicted as `Superseded` before ever
    // reaching this test's actual subject, T30-vs-A7 precedence.
    for i in 0..3 {
        let call_id = format!("call-{}", i + 2);
        msgs.push(assistant_calling(&call_id, "noop"));
        msgs.push(ChatMessage::tool_result(call_id, "noop", "ok"));
    }
    let noisy_idx = 2;

    let (view, log) = project_messages(&msgs, &policy, &ReductionLog::default());

    let claiming: Vec<&reduce::Reduction> = log
        .reductions
        .iter()
        .filter(|r| r.ptr.addr.index == noisy_idx)
        .collect();
    assert_eq!(
        claiming.len(),
        1,
        "exactly one reduction must claim the noisy message, never two: {:?}",
        log.reductions
    );
    // The still-oversized-after-normalization message must fall through to
    // A7's bounded truncation, NOT be claimed by OutputNormalized.
    assert!(
        matches!(claiming[0].kind, ReductionKind::ToolOutputTruncated { .. }),
        "a normalized rendering still over the trigger must defer to A7's bounded truncation, \
         not be claimed by OutputNormalized (the P7 regression this fix closes): {:?}",
        claiming[0].kind
    );

    // P7 safety net, made explicit: the actual WIRE bytes for this message
    // must be bounded by `tool_output_trigger_bytes` — this is the
    // assertion the pre-fix test never made, and whose absence let the
    // regression through. A7's kept-prefix (`tool_output_keep_bytes`,
    // 4,096B) plus its placeholder trailer must land comfortably under the
    // 8,192B trigger, nowhere near the ~22KB normalized (let alone ~34KB
    // raw) size.
    let view_content = view[noisy_idx].content.as_deref().unwrap();
    assert!(
        view_content.len() <= policy.tool_output_trigger_bytes,
        "P7 safety net violated: projected wire bytes ({}) exceed tool_output_trigger_bytes \
         ({}) — a normalized-but-still-huge terminal output must never ride the wire uncapped",
        view_content.len(),
        policy.tool_output_trigger_bytes
    );
    assert!(
        view_content.len() < normalized_bytes,
        "wire content ({}) must be strictly smaller than the (still oversized) normalized \
         rendering ({normalized_bytes}) — proof A7 actually truncated raw bytes, not the \
         normalized text",
        view_content.len()
    );

    // The RAW content (never the normalized rendering) is what A7 truncated
    // from — the kept prefix is real, unnormalized bytes.
    assert!(view_content.starts_with(&raw[..policy.tool_output_keep_bytes.min(raw.len())]));
}

// ---- TR-2 vs OutputNormalized precedence: a bash output that is BOTH a
// byte-identical duplicate of an earlier tool result AND ANSI/CR-noisy must
// be claimed by TR-2's DuplicateOutput, never independently normalized —
// TR-2 runs first in `project_messages` and claims the later occurrence's
// index in `reduced_this_run` before T30/TR-4's own candidate scan ever
// looks at it. The code already gets this right (verified by inspection);
// this test closes the coverage gap by actually exercising it. -------------

#[test]
fn duplicate_ansi_noisy_output_is_deduped_not_normalized() {
    // Real ANSI/CR noise (cargo_build), well over both the TR-2 dedup floor
    // (`duplicate_output_min_bytes`, default 256B) and the normalize savings
    // floor (`terminal_output_min_savings`, default 128B) — a genuine
    // candidate for EITHER pass, repeated byte-for-byte across two separate
    // bash calls.
    let raw = load_raw("cargo_build");
    let msgs = vec![
        ChatMessage::user("please build the project twice"),
        assistant_calling("call-1", "bash"),
        ChatMessage::tool_result("call-1", "bash", raw.clone()),
        assistant_calling("call-2", "bash"),
        ChatMessage::tool_result("call-2", "bash", raw.clone()),
    ];
    let first_idx = 2;
    let second_idx = 4;

    // No protection: only two tool results exist, and the default
    // `protect_last_n_tool_results` (3) would otherwise shield the later
    // (duplicate) occurrence from ever becoming a new TR-2 candidate at
    // all, defeating the point of this test.
    let policy = ReductionPolicy {
        protect_last_n_tool_results: 0,
        ..ReductionPolicy::default()
    };
    let (view, log) = project_messages(&msgs, &policy, &ReductionLog::default());

    // The later, byte-identical occurrence must be `DuplicateOutput`, never
    // `OutputNormalized` -- proof TR-2's pass claimed it before T30/TR-4's
    // own candidate scan ran.
    let second_claims: Vec<&reduce::Reduction> = log
        .reductions
        .iter()
        .filter(|r| r.ptr.addr.index == second_idx)
        .collect();
    assert_eq!(
        second_claims.len(),
        1,
        "exactly one reduction must claim the later (duplicate) occurrence: {:?}",
        log.reductions
    );
    assert!(
        matches!(second_claims[0].kind, ReductionKind::DuplicateOutput { .. }),
        "TR-2 must win precedence over OutputNormalized for a byte-identical later occurrence: \
         {:?}",
        second_claims[0].kind
    );

    // The canonical (first) occurrence, meanwhile, IS independently
    // normalized -- proof this is genuinely a TR-2-vs-normalize race on a
    // real ANSI-noisy fixture, not "normalize never fires here at all".
    let first_claim = log
        .reductions
        .iter()
        .find(|r| r.ptr.addr.index == first_idx)
        .expect("canonical occurrence must also have a reduction");
    assert!(
        matches!(first_claim.kind, ReductionKind::OutputNormalized { .. }),
        "canonical occurrence must be normalized independently: {:?}",
        first_claim.kind
    );

    // invert() restores BOTH occurrences byte-exact regardless of which
    // kind claimed which index (A6).
    let session = session_of(msgs.clone());
    let inverted = invert(&view, &log, &session).expect("invert must succeed");
    assert_eq!(inverted[first_idx].content.as_deref(), Some(raw.as_str()));
    assert_eq!(inverted[second_idx].content.as_deref(), Some(raw.as_str()));
}

// ---- dev/04: plain output (no ANSI, no CR) is left untouched --------------

#[test]
fn plain_bash_output_yields_no_reduction() {
    let raw = load_raw("plain_output");
    let msgs = bash_result_messages(&raw);
    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());

    assert!(
        log.reductions.is_empty(),
        "plain (no ANSI/CR) output must yield NO reduction: {:?}",
        log.reductions
    );
    assert_eq!(view[bash_idx()].content.as_deref(), Some(raw.as_str()));
    assert_eq!(reduction_id(&view[bash_idx()]), None);
}

// ---- dev/05: expand_reduction / sidecar_search recover the raw bytes ------

#[test]
fn expand_reduction_returns_the_exact_raw_bytes() {
    let raw = load_raw("cargo_build");
    let msgs = bash_result_messages(&raw);
    let (_view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    let r = find_output_normalized(&log);

    // `minted_view` is the messages the reductions were minted against —
    // `msgs` (unmutated `history`, in the real `Agent`), NOT the returned
    // (already-reduced) `view` (see `rehydrate.rs`'s module doc comment: the
    // reduce/project layer never mutates its input, only the derived view).
    let outcome = expand_reduction(&log, &msgs, None, &r.id, None).expect("expand must succeed");
    assert_eq!(
        outcome.content, raw,
        "expand_reduction must return the exact raw bytes"
    );
    assert_eq!(outcome.total_bytes, raw.len());
}

#[test]
fn sidecar_search_finds_raw_ansi_content_hidden_from_the_view() {
    let raw = load_raw("cargo_build");
    let msgs = bash_result_messages(&raw);
    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    let r = find_output_normalized(&log);

    // The SGR "bold bright green" sequence is all over the raw capture, and
    // is exactly what normalization strips — so a match here proves
    // `sidecar_search` is searching the hidden RAW bytes, not the (already
    // ANSI-free) normalized view. `msgs` (unmutated), not `view` — see
    // `expand_reduction_returns_the_exact_raw_bytes` above.
    let hits =
        sidecar_search(&log, &msgs, None, "\u{1b}[1m\u{1b}[32m").expect("search must succeed");
    assert!(
        !hits.matches.is_empty(),
        "expected matches in the raw ANSI bytes"
    );
    assert!(hits.matches.iter().all(|m| m.reduction_id == r.id));
    assert!(hits.matches.iter().all(|m| m.kind == "output-normalized"));

    // And the normalized VIEW itself must not contain that raw escape
    // sequence at all (proving it was truly stripped, not just hidden from
    // search).
    let view_content = view[bash_idx()].content.as_deref().unwrap();
    assert!(!view_content.contains("\u{1b}[1m\u{1b}[32m"));
}