supercode-harness 0.4.4

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
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
//! Acceptance tests for TR-6 (T16 — `.volter/tracker/markdown/TR-6.md`):
//! `ReductionKind::Superseded` (keep-latest for the same tool + same
//! canonicalized arguments) plus TR-6's errored-call input-pruning
//! complement to TR-10's `ToolInputElided`.
//!
//! Each test is labeled with the TR-6.md acceptance-criterion id it proves.
//! Exercises the real pipeline paths (`project_messages`, `invert`,
//! `verify_log`, `rehydrate::expand_reduction`) rather than a hand-rolled
//! simulation, following the idiom of `reduce_dedup.rs`/`tool_input_elision.rs`.

use std::collections::HashSet;

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

// ---- shared helpers ---------------------------------------------------------

/// Wraps `msgs` in a bare `Session` (mirrors `reduce_dedup.rs::session_of`) so
/// it can serve as the `sidecar_session` argument `invert`/`verify_log` need
/// — 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
}

/// A deterministic all-ASCII filler string of exactly `len` bytes.
fn filler(len: usize) -> String {
    (0..len).map(|i| (b'a' + (i % 26) as u8) as char).collect()
}

/// An assistant message issuing one `bash(command)` tool call with the given
/// call id.
fn bash_call(id: &str, command: &str) -> 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: "bash".to_string(),
                arguments: serde_json::json!({ "command": command }).to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

/// A `bash` result message paired to `id`.
fn bash_result(id: &str, content: impl Into<String>) -> ChatMessage {
    ChatMessage::tool_result(id, "bash", content)
}

/// A policy with every recency-protection knob (A7's and TR-6's own) zeroed
/// out, mirroring `reduce_dedup.rs::no_protection_policy` — lets a small
/// fixture put its supersession candidates anywhere without needing padding
/// turns to age them out of a protected tail.
fn no_protection_policy() -> ReductionPolicy {
    ReductionPolicy {
        protect_last_n_tool_results: 0,
        supersede_protect_last_n: 0,
        ..ReductionPolicy::default()
    }
}

/// Every `ReductionKind::Superseded` record's own (addressed) index, from a
/// log.
fn superseded_indices(log: &ReductionLog) -> HashSet<usize> {
    log.reductions
        .iter()
        .filter_map(|r| match r.kind {
            ReductionKind::Superseded { .. } => Some(r.ptr.addr.index),
            _ => None,
        })
        .collect()
}

// ---- dev/01: 4 runs of the same command, keep-latest over age-bias ---------

/// A `cargo test` run 4x: three different failures, then a pass. The first
/// three must be reduced to `Superseded` stubs all naming the 4th (the
/// newest) as their successor — not each other — and the 4th stays fully
/// visible even though it is the OLDEST-position survivor A10's own
/// age-based clearing logic would never specifically favor (A10 has no
/// notion of "same command, keep latest" at all — it only ever clears a
/// contiguous OLD range). `invert` restores every one of the four runs
/// byte-exact.
#[test]
fn dev01_four_runs_same_command_first_three_superseded_naming_the_fourth() {
    let bodies: Vec<String> = vec![
        format!("FAIL(assertion 1): {}", filler(500)),
        format!("FAIL(assertion 2): {}", filler(500)),
        format!("FAIL(timeout): {}", filler(500)),
        format!("PASS: {}", filler(500)),
    ];
    let mut msgs = vec![ChatMessage::user("run the test suite")];
    let mut result_idx = Vec::new();
    for (i, body) in bodies.iter().enumerate() {
        let id = format!("c{i}");
        msgs.push(bash_call(&id, "cargo test"));
        result_idx.push(msgs.len());
        msgs.push(bash_result(&id, body.clone()));
    }

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

    let superseded: Vec<_> = log
        .reductions
        .iter()
        .filter(|r| matches!(r.kind, ReductionKind::Superseded { .. }))
        .collect();
    assert_eq!(
        superseded.len(),
        3,
        "the first three runs must all be superseded: {:?}",
        log.reductions
    );

    let newest_idx = result_idx[3];
    for (i, &idx) in result_idx[..3].iter().enumerate() {
        let r = superseded
            .iter()
            .find(|r| r.ptr.addr.index == idx)
            .unwrap_or_else(|| panic!("run {i} (msg #{idx}) must be superseded: {log:?}"));
        match r.kind {
            ReductionKind::Superseded { by, original_bytes } => {
                assert_eq!(
                    by.index, newest_idx,
                    "every superseded run must name the 4th (newest), not its immediate successor"
                );
                assert_eq!(by.role, Role::Tool);
                assert_eq!(original_bytes, bodies[i].len());
            }
            _ => unreachable!(),
        }
        let content = view[idx].content.as_deref().unwrap();
        assert!(
            content.starts_with("[sc-reduced superseded"),
            "message {idx}: {content}"
        );
        let (kind, rid, summary) = stub::parse(content).expect("stub must parse");
        assert_eq!(kind, stub::Kind::Superseded);
        assert_eq!(rid, r.id);
        assert!(
            summary.contains(&format!("msg #{newest_idx}")),
            "stub must honestly name the successor: {summary}"
        );
        assert!(
            summary.contains(&format!("expand_reduction(\"{}\")", r.id)),
            "stub must tell the model how to restore it: {summary}"
        );
    }

    // The 4th (newest) run is kept fully visible, untouched.
    assert_eq!(
        view[newest_idx].content.as_deref(),
        Some(bodies[3].as_str())
    );
    assert!(reduction_id(&view[newest_idx]).is_none());

    // `invert` restores all four runs byte-exact.
    let sidecar = session_of(msgs.clone());
    verify_log(&log, &sidecar).expect("verify_log must pass clean");
    let inverted = invert(&view, &log, &sidecar).expect("invert must pass clean");
    for (&idx, body) in result_idx.iter().zip(bodies.iter()) {
        assert_eq!(
            inverted[idx].content.as_deref(),
            Some(body.as_str()),
            "run at msg #{idx} must invert byte-exact"
        );
    }

    // `expand_reduction` (TR-1) — the exact intrinsic the stub names — also
    // restores the same byte-exact original directly, with no `invert` round
    // trip needed.
    let first_id = superseded
        .iter()
        .find(|r| r.ptr.addr.index == result_idx[0])
        .unwrap()
        .id
        .clone();
    let expanded = expand_reduction(&log, &msgs, None, &first_id, None).unwrap();
    assert_eq!(expanded.content, bodies[0]);
}

// ---- dev/02: different args are never superseded ---------------------------

#[test]
fn dev02_different_args_never_superseded_git_diff_vs_stat() {
    let body_plain = format!("diff-plain-{}", filler(300));
    let body_stat = format!("diff-stat-{}", filler(300));
    let msgs = vec![
        ChatMessage::user("diff please"),
        bash_call("c0", "git diff"),
        bash_result("c0", body_plain.clone()),
        bash_call("c1", "git diff --stat"),
        bash_result("c1", body_stat.clone()),
    ];

    let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "different arguments must never be superseded: {:?}",
        log.reductions
    );
    assert_eq!(view[2].content.as_deref(), Some(body_plain.as_str()));
    assert_eq!(view[4].content.as_deref(), Some(body_stat.as_str()));
}

#[test]
fn dev02_different_args_never_superseded_ls_a_vs_b() {
    let body_a = format!("listing-a-{}", filler(300));
    let body_b = format!("listing-b-{}", filler(300));
    let msgs = vec![
        ChatMessage::user("list both dirs"),
        bash_call("c0", "ls a/"),
        bash_result("c0", body_a.clone()),
        bash_call("c1", "ls b/"),
        bash_result("c1", body_b.clone()),
    ];

    let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "different arguments must never be superseded: {:?}",
        log.reductions
    );
    assert_eq!(view[2].content.as_deref(), Some(body_a.as_str()));
    assert_eq!(view[4].content.as_deref(), Some(body_b.as_str()));
}

#[test]
fn dev02_v1_never_guesses_flag_reordered_commands_are_equivalent() {
    // TR-6.md is explicit: `ls -la` != `ls -al` in v1 -- a false supersession
    // is worse than a missed one, so no token/flag-level reasoning is applied.
    let body_la = format!("la-{}", filler(300));
    let body_al = format!("al-{}", filler(300));
    let msgs = vec![
        ChatMessage::user("list with flags"),
        bash_call("c0", "ls -la"),
        bash_result("c0", body_la.clone()),
        bash_call("c1", "ls -al"),
        bash_result("c1", body_al.clone()),
    ];

    let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "v1 must never treat `ls -la`/`ls -al` as the same key: {:?}",
        log.reductions
    );
    assert_eq!(view[2].content.as_deref(), Some(body_la.as_str()));
    assert_eq!(view[4].content.as_deref(), Some(body_al.as_str()));
}

// ---- dev/03: protected recency zone respected, at the boundary --------------

#[test]
fn dev03_protected_recency_zone_respects_the_boundary() {
    let bodies: Vec<String> = (0..4).map(|i| format!("RUN-{i}-{}", filler(400))).collect();
    let mut msgs = vec![ChatMessage::user("run it repeatedly")];
    let mut result_idx = Vec::new();
    for (i, body) in bodies.iter().enumerate() {
        let id = format!("c{i}");
        msgs.push(bash_call(&id, "cargo test"));
        result_idx.push(msgs.len());
        msgs.push(bash_result(&id, body.clone()));
    }

    // K = 2: the newest 2 tool-result messages (occurrences #2 and #3, 0-
    // indexed) are protected. Occurrence #2 sits exactly at the boundary --
    // older than the newest (#3), but still inside the protected zone -- and
    // must survive untouched; occurrence #1, just outside the zone, must be
    // superseded.
    let policy = ReductionPolicy {
        protect_last_n_tool_results: 0,
        supersede_protect_last_n: 2,
        ..ReductionPolicy::default()
    };
    let (view, log) = project_messages(&msgs, &policy, &ReductionLog::default());

    let got = superseded_indices(&log);
    let want: HashSet<usize> = [result_idx[0], result_idx[1]].into_iter().collect();
    assert_eq!(
        got, want,
        "only occurrences outside the protected zone may be superseded"
    );

    // Occurrence #2: at the boundary, protected -- stays full, untouched.
    assert_eq!(
        view[result_idx[2]].content.as_deref(),
        Some(bodies[2].as_str())
    );
    assert!(reduction_id(&view[result_idx[2]]).is_none());

    // Occurrence #3: newest, also untouched.
    assert_eq!(
        view[result_idx[3]].content.as_deref(),
        Some(bodies[3].as_str())
    );
}

// ---- dev/04: errored-call input pruning, after N turns, error stays visible ----

/// An assistant message issuing one `write_file(path, content)` tool call —
/// mirrors `tool_input_elision.rs::write_call`.
fn write_call(id: &str, path: &str, content: &str) -> 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: "write_file".to_string(),
                arguments: serde_json::json!({ "path": path, "content": content }).to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

/// An ERRORED `write_file` result paired to `id` (mirrors
/// `tool_input_elision.rs::write_err_result`).
fn write_err_result(id: &str) -> ChatMessage {
    let mut m = ChatMessage::tool_result(id, "write_file", "Error: disk full");
    mark_tool_error(&mut m);
    m
}

fn args_of(msgs: &[ChatMessage], msg_index: usize) -> String {
    msgs[msg_index].tool_calls()[0].function.arguments.clone()
}

fn parsed_args(msgs: &[ChatMessage], msg_index: usize) -> serde_json::Value {
    serde_json::from_str(&args_of(msgs, msg_index)).unwrap()
}

#[test]
fn dev04_errored_call_large_input_pruned_only_after_n_turns_error_stays_visible_and_inverts() {
    let big = filler(20_000);
    let policy = ReductionPolicy::default();
    let mut msgs = vec![write_call("w1", "out.txt", &big), write_err_result("w1")];
    assert!(is_tool_error(&msgs[1]));

    // Not yet aged: must NOT be pruned.
    let (view0, log0) = project_messages(&msgs, &policy, &ReductionLog::default());
    assert!(
        log0.reductions.is_empty(),
        "an errored call's oversized input must not be pruned before N turns elapse: {:?}",
        log0.reductions
    );
    assert_eq!(args_of(&view0, 0), args_of(&msgs, 0));

    // Age it past the threshold with further assistant turns.
    for i in 0..policy.errored_input_prune_after_turns {
        msgs.push(ChatMessage::assistant(format!("turn {i}")));
    }

    let (view, log) = project_messages(&msgs, &policy, &ReductionLog::default());
    assert_eq!(log.reductions.len(), 1, "{:?}", log.reductions);
    let r = &log.reductions[0];
    match &r.kind {
        ReductionKind::ToolInputElided {
            call_id,
            field,
            original_bytes,
            ..
        } => {
            assert_eq!(call_id, "w1");
            assert_eq!(field, "content");
            assert_eq!(*original_bytes, big.len());
        }
        other => panic!("expected ToolInputElided, got {other:?}"),
    }

    let reduced = parsed_args(&view, 0);
    let content_val = reduced.get("content").unwrap().as_str().unwrap();
    assert!(content_val.contains(REDUCTION_SENTINEL), "{content_val}");
    assert!(content_val.contains("tool-input"), "{content_val}");
    assert!(
        content_val.contains("errored call"),
        "the stub should be honest that this is the errored-call case: {content_val}"
    );

    // The error message itself (the paired tool-result content) stays fully
    // visible, untouched by this pass.
    assert_eq!(view[1].content.as_deref(), Some("Error: disk full"));
    assert!(reduction_id(&view[1]).is_none());

    // `invert` restores the pruned input byte-exact.
    let sidecar = session_of(msgs.clone());
    verify_log(&log, &sidecar).expect("verify_log must pass clean");
    let inverted = invert(&view, &log, &sidecar).unwrap();
    assert_eq!(
        args_of(&inverted, 0),
        args_of(&msgs, 0),
        "invert must restore the original tool_call arguments byte-for-byte"
    );
}

#[test]
fn dev04_successful_call_never_taken_by_errored_input_pruning() {
    // The TR-6/TR-10 boundary: a SUCCESSFUL call's oversized input is TR-10's
    // territory (immediate, no aging clock) -- it must never additionally be
    // picked up by TR-6's errored-only pass, and must never wait for the
    // aging clock either.
    let big = filler(20_000);
    let msgs = vec![
        write_call("w1", "out.txt", &big),
        ChatMessage::tool_result("w1", "write_file", format!("Wrote {} bytes", big.len())),
    ];
    let (_, log) = project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    assert_eq!(log.reductions.len(), 1, "{:?}", log.reductions);
    match &log.reductions[0].kind {
        ReductionKind::ToolInputElided { .. } => {}
        other => panic!("expected ToolInputElided (TR-10's success path), got {other:?}"),
    }
}

// ---- dev/05: determinism ----------------------------------------------------

#[test]
fn dev05_reprojecting_the_same_transcript_twice_yields_identical_logs() {
    let bodies: Vec<String> = vec![
        format!("FAIL-1-{}", filler(400)),
        format!("FAIL-2-{}", filler(400)),
        format!("PASS-{}", filler(400)),
    ];
    let mut msgs = vec![ChatMessage::user("run it")];
    for (i, body) in bodies.iter().enumerate() {
        let id = format!("c{i}");
        msgs.push(bash_call(&id, "cargo test"));
        msgs.push(bash_result(&id, body.clone()));
    }
    let policy = no_protection_policy();

    let (_, log1) = project_messages(&msgs, &policy, &ReductionLog::default());
    let (_, log2) = project_messages(&msgs, &policy, &ReductionLog::default());
    assert_eq!(
        log1, log2,
        "reducing the same transcript twice from scratch must yield identical logs"
    );
    assert!(
        !log1.reductions.is_empty(),
        "sanity: this fixture must actually mint Superseded reductions"
    );

    // Prefix stability: re-projecting FROM the already-established log must
    // reproduce it byte-identically too (no ambient/ordinal drift).
    let (view3, log3) = project_messages(&msgs, &policy, &log1);
    assert_eq!(log3, log1);

    let sidecar = session_of(msgs.clone());
    verify_log(&log3, &sidecar).expect("verify_log must pass clean");
    let inverted = invert(&view3, &log3, &sidecar).expect("invert must pass clean");
    for (a, b) in inverted.iter().zip(msgs.iter()) {
        assert_eq!(a.content, b.content);
    }
}

// ---- extra: min-size floor, the enable gate, and non-command-tool keys -----

#[test]
fn tiny_repeated_results_below_the_floor_are_never_superseded() {
    let tiny = "ok"; // well under the default 256B floor
    let msgs = vec![
        ChatMessage::user("run it"),
        bash_call("c0", "cargo test"),
        bash_result("c0", tiny),
        bash_call("c1", "cargo test"),
        bash_result("c1", tiny),
    ];
    let (_, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "content below the savings floor must never be superseded: {:?}",
        log.reductions
    );
}

#[test]
fn supersede_enabled_false_disables_minting_entirely() {
    let bodies: Vec<String> = vec![
        format!("FAIL-{}", filler(400)),
        format!("PASS-{}", filler(400)),
    ];
    let mut msgs = vec![ChatMessage::user("run it")];
    for (i, body) in bodies.iter().enumerate() {
        let id = format!("c{i}");
        msgs.push(bash_call(&id, "cargo test"));
        msgs.push(bash_result(&id, body.clone()));
    }
    let policy = ReductionPolicy {
        supersede_enabled: false,
        ..no_protection_policy()
    };
    let (_, log) = project_messages(&msgs, &policy, &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "supersede_enabled = false must mint no Superseded reductions: {:?}",
        log.reductions
    );
}

#[test]
fn non_command_tool_supersedes_on_the_whole_trimmed_arguments() {
    // A tool with no configured "command" field (e.g. a directory listing)
    // still participates in supersession -- its whole (trimmed) arguments
    // string is the key.
    let call = |id: &str, path: &str| 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: "list_dir".to_string(),
                arguments: serde_json::json!({ "path": path }).to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };
    let old_listing = format!("old-listing-{}", filler(400));
    let new_listing = format!("new-listing-{}", filler(400));
    let msgs = vec![
        ChatMessage::user("list the dir twice"),
        call("c0", "/repo"),
        ChatMessage::tool_result("c0", "list_dir", old_listing.clone()),
        call("c1", "/repo"),
        ChatMessage::tool_result("c1", "list_dir", new_listing.clone()),
    ];
    let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert_eq!(
        superseded_indices(&log),
        [2usize].into_iter().collect::<HashSet<_>>(),
        "the older same-path listing must be superseded by the newer one: {:?}",
        log.reductions
    );
    assert_eq!(view[4].content.as_deref(), Some(new_listing.as_str()));

    // A DIFFERENT path never collides.
    let other_listing = format!("other-listing-{}", filler(400));
    let msgs2 = vec![
        ChatMessage::user("list a different dir"),
        call("c0", "/repo"),
        ChatMessage::tool_result("c0", "list_dir", old_listing.clone()),
        call("c1", "/elsewhere"),
        ChatMessage::tool_result("c1", "list_dir", other_listing.clone()),
    ];
    let (view2, log2) = project_messages(&msgs2, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log2).is_empty(),
        "a different path must never be superseded: {:?}",
        log2.reductions
    );
    assert_eq!(view2[2].content.as_deref(), Some(old_listing.as_str()));
    assert_eq!(view2[4].content.as_deref(), Some(other_listing.as_str()));
}

// ---- fix: quote-aware whitespace collapse (false-supersession fix) ---------

/// End-to-end (not just `canonical_key`-level) regression for the false-
/// supersession bug: whitespace INSIDE a quoted shell literal must never
/// collapse, or `echo "a  b"` and `echo "a b"` — two DIFFERENT commands —
/// would wrongly key identically and the older, still-relevant result would
/// be silently evicted. TR-6.md: a false supersession is worse than a missed
/// one.
#[test]
fn quote_aware_collapse_never_falsely_supersedes_differently_spaced_quoted_literals() {
    let body_two_spaces = format!("two-spaces-{}", filler(300));
    let body_one_space = format!("one-space-{}", filler(300));
    let msgs = vec![
        ChatMessage::user("echo twice, differently spaced inside the quotes"),
        bash_call("c0", r#"echo "a  b""#),
        bash_result("c0", body_two_spaces.clone()),
        bash_call("c1", r#"echo "a b""#),
        bash_result("c1", body_one_space.clone()),
    ];

    let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "differently-spaced quoted literals must never be superseded: {:?}",
        log.reductions
    );
    assert_eq!(view[2].content.as_deref(), Some(body_two_spaces.as_str()));
    assert_eq!(view[4].content.as_deref(), Some(body_one_space.as_str()));
}

/// The same fix, single-quoted, plus the companion positive case: unquoted
/// separator whitespace still collapses so a genuine re-run of the exact
/// same command is still superseded (the fix must not regress the intended
/// behavior into over-preservation).
#[test]
fn quote_aware_collapse_single_quoted_never_falsely_supersedes_but_unquoted_reruns_still_do() {
    let body_two_spaces = format!("two-spaces-{}", filler(300));
    let body_one_space = format!("one-space-{}", filler(300));
    let msgs = vec![
        ChatMessage::user("echo twice with single quotes, differently spaced"),
        bash_call("c0", "echo 'a  b'"),
        bash_result("c0", body_two_spaces.clone()),
        bash_call("c1", "echo 'a b'"),
        bash_result("c1", body_one_space.clone()),
    ];
    let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "differently-spaced single-quoted literals must never be superseded: {:?}",
        log.reductions
    );
    assert_eq!(view[2].content.as_deref(), Some(body_two_spaces.as_str()));
    assert_eq!(view[4].content.as_deref(), Some(body_one_space.as_str()));

    // Companion positive case: `cargo  test` (extra unquoted whitespace) and
    // `cargo test` are still the SAME command and a genuine re-run must
    // still be superseded.
    let body_fail = format!("FAIL-{}", filler(300));
    let body_pass = format!("PASS-{}", filler(300));
    let msgs2 = vec![
        ChatMessage::user("run it twice"),
        bash_call("c0", "cargo  test"),
        bash_result("c0", body_fail.clone()),
        bash_call("c1", "cargo test"),
        bash_result("c1", body_pass.clone()),
    ];
    let (view2, log2) = project_messages(&msgs2, &no_protection_policy(), &ReductionLog::default());
    assert_eq!(
        superseded_indices(&log2),
        [2usize].into_iter().collect::<HashSet<_>>(),
        "unquoted separator whitespace must still collapse so a genuine re-run is superseded: {:?}",
        log2.reductions
    );
    assert_eq!(view2[4].content.as_deref(), Some(body_pass.as_str()));
}

/// A quoted grep pattern is the concrete real-world trigger named in the
/// fix: `grep "foo  bar" f` vs `grep "foo bar" f` must stay two distinct
/// keys end-to-end.
#[test]
fn quote_aware_collapse_grep_pattern_never_falsely_supersedes() {
    let body_two_spaces = format!("match-two-spaces-{}", filler(300));
    let body_one_space = format!("match-one-space-{}", filler(300));
    let msgs = vec![
        ChatMessage::user("grep twice, differently spaced pattern"),
        bash_call("c0", r#"grep "foo  bar" f"#),
        bash_result("c0", body_two_spaces.clone()),
        bash_call("c1", r#"grep "foo bar" f"#),
        bash_result("c1", body_one_space.clone()),
    ];
    let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "differently-spaced quoted grep patterns must never be superseded: {:?}",
        log.reductions
    );
    assert_eq!(view[2].content.as_deref(), Some(body_two_spaces.as_str()));
    assert_eq!(view[4].content.as_deref(), Some(body_one_space.as_str()));
}

/// An unbalanced (unterminated) quote makes the lex ambiguous end-to-end.
/// The conservative fallback (trim-only, no internal collapse) must still
/// mean it is never falsely equated with a well-formed, differently-spaced
/// command whose collapsed form happens to coincide.
#[test]
fn quote_aware_collapse_unbalanced_quote_command_never_falsely_supersedes() {
    let body_unterminated = format!("unterminated-{}", filler(300));
    let body_well_formed = format!("well-formed-{}", filler(300));
    let msgs = vec![
        ChatMessage::user("one unterminated quote, one well-formed command"),
        bash_call("c0", r#"echo "unterminated"#),
        bash_result("c0", body_unterminated.clone()),
        bash_call("c1", "echo unterminated"),
        bash_result("c1", body_well_formed.clone()),
    ];
    let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
    assert!(
        superseded_indices(&log).is_empty(),
        "an unbalanced-quote command must never be falsely equated with another command: {:?}",
        log.reductions
    );
    assert_eq!(view[2].content.as_deref(), Some(body_unterminated.as_str()));
    assert_eq!(view[4].content.as_deref(), Some(body_well_formed.as_str()));
}

// ---- recurring_hashes / TR-2 anchor boundary (currently-untested guard) ----

/// The `recurring_hashes` guard (reduce.rs): content whose hash recurs
/// ANYWHERE among candidate tool results is TR-2's exclusive territory, never
/// Superseded's. Four same-tool/same-args occurrences: the first two are
/// byte-identical to each other (`body_x`), the third differs (`body_y`),
/// the fourth is newest and distinct (`body_z`).
///
/// Expected split:
/// - occurrence #0 (the byte-identical PAIR's first/earliest copy): this is
///   TR-2's own "first_seen" canonical for that hash — kept FULLY VISIBLE,
///   untouched by any reduction. **Known limitation** (TR-15 follow-up
///   territory, reversible, spec-acceptable "missed not wrong"): the
///   recurring-hash guard's own address space is computed from ALL
///   occurrences of a hash regardless of which is TR-2's chosen canonical,
///   so this anchor occurrence is excluded from Superseded consideration by
///   the SAME guard that (correctly) protects TR-2's canonical — but nothing
///   else ever supersedes or dedups it either, so it is simply never reduced
///   at all, even though it is chronologically superseded by both the
///   differing run and the newest run. This test PINS that current
///   behavior; it is not asserting it is ideal.
/// - occurrence #1 (byte-identical to #0): TR-2's `DuplicateOutput`,
///   pointing back at occurrence #0 as canonical.
/// - occurrence #2 (`body_y`, unique hash): Superseded, naming occurrence #3
///   (the newest) as successor — this is `recurring_hashes` correctly
///   staying OUT of TR-6's way for a hash that does NOT recur elsewhere.
/// - occurrence #3 (`body_z`, newest): kept fully visible (never superseded,
///   it is nothing's elder).
///
/// `invert` restores all four occurrences byte-exact.
#[test]
fn recurring_hashes_guard_defers_byte_identical_pair_to_tr2_and_supersedes_the_differing_run() {
    let body_x = format!("FAIL-X-{}", filler(400));
    let body_y = format!("FAIL-Y-{}", filler(400));
    let body_z = format!("PASS-Z-{}", filler(400));
    let bodies = [
        body_x.clone(),
        body_x.clone(),
        body_y.clone(),
        body_z.clone(),
    ];

    let mut msgs = vec![ChatMessage::user("run the flaky test repeatedly")];
    let mut result_idx = Vec::new();
    for (i, body) in bodies.iter().enumerate() {
        let id = format!("c{i}");
        msgs.push(bash_call(&id, "cargo test"));
        result_idx.push(msgs.len());
        msgs.push(bash_result(&id, body.clone()));
    }

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

    // Occurrence #0: the byte-identical pair's anchor. KNOWN LIMITATION —
    // left fully visible, not reduced by anything (see doc comment above).
    assert_eq!(
        view[result_idx[0]].content.as_deref(),
        Some(body_x.as_str()),
        "the recurring-hash anchor occurrence is currently left unreduced (known limitation)"
    );
    assert!(reduction_id(&view[result_idx[0]]).is_none());

    // Occurrence #1: TR-2's DuplicateOutput, canonical = occurrence #0.
    let dup = log
        .reductions
        .iter()
        .find(|r| r.ptr.addr.index == result_idx[1])
        .unwrap_or_else(|| panic!("occurrence #1 must be reduced: {:?}", log.reductions));
    match &dup.kind {
        ReductionKind::DuplicateOutput {
            canonical,
            original_bytes,
        } => {
            assert_eq!(canonical.index, result_idx[0]);
            assert_eq!(*original_bytes, body_x.len());
        }
        other => panic!("expected DuplicateOutput for occurrence #1, got {other:?}"),
    }

    // Occurrence #2: Superseded, naming occurrence #3 (the newest) as
    // successor — `recurring_hashes` must NOT block this one, since its
    // hash (body_y's) does not recur anywhere else.
    assert_eq!(
        superseded_indices(&log),
        [result_idx[2]].into_iter().collect::<HashSet<_>>(),
        "only the differing (unique-hash) run may be Superseded: {:?}",
        log.reductions
    );
    let superseded = log
        .reductions
        .iter()
        .find(|r| r.ptr.addr.index == result_idx[2])
        .unwrap();
    match superseded.kind {
        ReductionKind::Superseded { by, .. } => assert_eq!(by.index, result_idx[3]),
        _ => unreachable!(),
    }

    // Occurrence #3: newest, kept fully visible.
    assert_eq!(
        view[result_idx[3]].content.as_deref(),
        Some(body_z.as_str())
    );
    assert!(reduction_id(&view[result_idx[3]]).is_none());

    // The whole thing inverts byte-exact.
    let sidecar = session_of(msgs.clone());
    verify_log(&log, &sidecar).expect("verify_log must pass clean");
    let inverted = invert(&view, &log, &sidecar).expect("invert must pass clean");
    for (&idx, body) in result_idx.iter().zip(bodies.iter()) {
        assert_eq!(
            inverted[idx].content.as_deref(),
            Some(body.as_str()),
            "occurrence at msg #{idx} must invert byte-exact"
        );
    }
}