supercode-harness 0.4.12

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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//! Acceptance tests for SPEC.md A5 (`project()`) and A6 (`invert()` /
//! `invert_one()`) — the reversible projection engine and its identity
//! invariant.
//!
//! `sidecar_session` in every `invert` call below is the very `Session` that
//! was fed to `project` (or a deliberately tampered/edited clone of it) —
//! per SPEC.md A6, `project`'s input *is* the sidecar reconstruction, so
//! there is exactly one canonical model in play, never a second one.

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

use supercode_harness::reduce::{
    content_hash, invert, invert_one, prepare_read_freshness, probe_read_freshness, project,
    project_messages, reduce_to_fit, reduction_id, ReductionKind, ReductionLog, ReductionPolicy,
    REDUCTION_SENTINEL,
};
use supercode_harness::{ChatMessage, FunctionCall, Role, Session, ToolCall};

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

#[test]
fn prepared_stale_reads_count_before_context_pressure_escalation() {
    let dir = a8_temp_dir("preflight-pressure");
    let file_path = dir.join("f.txt");
    let content = eight_kb_content();
    std::fs::write(&file_path, &content).unwrap();
    let msgs = vec![
        ChatMessage::user("please read the file"),
        read_call("call_1", &file_path),
        ChatMessage::tool_result("call_1", "read_file", content),
    ];
    let mut policy = ReductionPolicy {
        elide_stale_reads: true,
        protect_last_n_tool_results: 0,
        ..ReductionPolicy::default()
    };
    prepare_read_freshness(&mut policy, &msgs);
    let (base_view, _) = project_messages(&msgs, &policy, &ReductionLog::default());
    let fit_bytes = serde_json::to_vec(&base_view).unwrap().len();

    let (_view, log, applied) =
        reduce_to_fit(&msgs, &policy, &ReductionLog::default(), |candidate| {
            serde_json::to_vec(candidate).unwrap().len() <= fit_bytes
        });
    assert_eq!(
        applied, policy,
        "verified stale-read savings must satisfy preflight at the base policy"
    );
    assert_eq!(log.reductions.len(), 1);
    assert!(matches!(
        log.reductions[0].kind,
        ReductionKind::FileReadElided { .. }
    ));
    std::fs::remove_dir_all(dir).ok();
}

fn load_codex() -> Session {
    Session::from_codex(fixture("codex_session.jsonl")).unwrap()
}

fn load_claude() -> Session {
    Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap()
}

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

/// Indices of every `Tool`-role message in `session.messages`, in order.
fn tool_indices(session: &Session) -> Vec<usize> {
    session
        .messages
        .iter()
        .enumerate()
        .filter(|(_, m)| m.role == Role::Tool)
        .map(|(i, _)| i)
        .collect()
}

/// Overwrite the `ordinal`-th tool result's content with a deterministic,
/// all-ASCII filler string of exactly `target_len` bytes — big enough to
/// force a truncation candidate regardless of the fixture's real content.
fn pad_tool_output(session: &mut Session, ordinal: usize, target_len: usize) {
    let idx = tool_indices(session)[ordinal];
    let filler: String = (0..target_len)
        .map(|i| (b'a' + (i % 26) as u8) as char)
        .collect();
    session.messages[idx].content = Some(filler);
}

/// Append `n` synthetic (user, assistant) turns to the end of `session` —
/// the "2 synthetic appended turns" scenario the A5/A6 acceptance criteria
/// call for. Appending only ever grows the message list, so every existing
/// `MessageAddr` stays valid.
fn append_synthetic_turns(session: &mut Session, n: usize) {
    for i in 0..n {
        session
            .messages
            .push(ChatMessage::user(format!("synthetic follow-up {i}")));
        session
            .messages
            .push(ChatMessage::assistant(format!("synthetic reply {i}")));
    }
}

fn tool_calls_identical(a: &[ToolCall], b: &[ToolCall]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b).all(|(x, y)| {
            x.id == y.id
                && x.kind == y.kind
                && x.function.name == y.function.name
                && x.function.arguments == y.function.arguments
        })
}

/// Byte-identical comparison (used for the determinism/prefix-stability
/// tests): every field, including `metadata`, must match exactly.
fn messages_identical(a: &[ChatMessage], b: &[ChatMessage]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b).all(|(x, y)| {
            x.role == y.role
                && x.content == y.content
                && x.content_parts == y.content_parts
                && x.tool_call_id == y.tool_call_id
                && x.name == y.name
                && x.metadata == y.metadata
                && tool_calls_identical(x.tool_calls(), y.tool_calls())
        })
}

fn strip_sc(meta: &BTreeMap<String, String>) -> BTreeMap<String, String> {
    meta.iter()
        .filter(|(k, _)| !k.starts_with("sc."))
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect()
}

/// The A6 identity invariant's equality: `roundtrip_regression.rs::msg_eq`
/// (role, content, tool_call_id, tool calls with parsed args) extended with
/// metadata equality modulo the `sc.` namespace, and with `content_parts`
/// equality (A9: `invert` must restore a redacted image part byte-identically,
/// which a comparison over `content` alone — multimodal messages carry `None`
/// there — would never catch).
fn msg_eq_ext(a: &ChatMessage, b: &ChatMessage) -> bool {
    if a.role != b.role
        || a.content != b.content
        || a.content_parts != b.content_parts
        || a.tool_call_id != b.tool_call_id
    {
        return false;
    }
    let (ca, cb) = (a.tool_calls(), b.tool_calls());
    if ca.len() != cb.len() {
        return false;
    }
    let calls_ok = ca.iter().zip(cb).all(|(x, y)| {
        x.id == y.id
            && x.function.name == y.function.name
            && x.function.parsed_arguments().ok() == y.function.parsed_arguments().ok()
    });
    calls_ok && strip_sc(&a.metadata) == strip_sc(&b.metadata)
}

fn assert_identity(label: &str, inverted: &[ChatMessage], original: &[ChatMessage]) {
    assert_eq!(
        inverted.len(),
        original.len(),
        "{label}: message count changed after invert(project(..))"
    );
    for (i, (x, y)) in inverted.iter().zip(original).enumerate() {
        assert!(
            msg_eq_ext(x, y),
            "{label}: message {i} differs after invert(project(..)):\n  inverted: {x:?}\n  original: {y:?}"
        );
    }
}

/// A synthetic `data:` URL of a given declared media type and payload length
/// — big enough (with `payload_len >= 8192`) to cross
/// [`ReductionPolicy::image_redact_min_bytes`]'s default trigger.
fn big_data_url(mime: &str, payload_len: usize) -> String {
    format!("data:{mime};base64,{}", "A".repeat(payload_len))
}

fn forcing_policy() -> ReductionPolicy {
    ReductionPolicy {
        tool_output_keep_bytes: 64,
        tool_output_trigger_bytes: 128,
        protect_last_n_tool_results: 0,
        ..ReductionPolicy::default()
    }
}

// ---- A5: project() ----------------------------------------------------------

#[test]
fn project_is_deterministic_and_prefix_stable() {
    let mut session = load_codex();
    pad_tool_output(&mut session, 0, 100_000);

    let policy = forcing_policy();
    let prior = ReductionLog::default();

    let (view1, log1) = project(&session, &policy, &prior);
    let (view2, log2) = project(&session, &policy, &prior);

    assert!(
        messages_identical(&view1, &view2),
        "project() is not deterministic: two runs over identical inputs produced different views"
    );
    assert_eq!(
        log1, log2,
        "project() is not deterministic: two runs over identical inputs produced different logs"
    );
    assert!(
        !log1.reductions.is_empty(),
        "the 100 KB padded tool output should have triggered at least one reduction"
    );

    // Prefix stability: append 2 messages, re-project with the prior log —
    // the earlier reduction's placeholder must survive byte-for-byte.
    let mut grown = session.clone();
    append_synthetic_turns(&mut grown, 1); // 2 messages: one user, one assistant

    let (view3, log3) = project(&grown, &policy, &log1);

    assert_eq!(
        log3.reductions.len(),
        log1.reductions.len(),
        "re-projecting an already-fully-reduced session with a stable prior log should not \
         invent new reductions"
    );
    for r in &log1.reductions {
        let r3 = log3
            .reductions
            .iter()
            .find(|x| x.id == r.id)
            .unwrap_or_else(|| panic!("prior reduction {} vanished on re-projection", r.id));
        assert_eq!(
            r, r3,
            "prior reduction {} churned across re-projection",
            r.id
        );
        let msg1 = &view1[r.ptr.addr.index];
        let msg3 = &view3[r.ptr.addr.index];
        assert_eq!(
            msg1.content, msg3.content,
            "placeholder for {} changed byte-for-byte after appending messages",
            r.id
        );
    }
}

#[test]
fn project_never_orphans_tool_pairs() {
    let policies = [
        ReductionPolicy::default(),
        forcing_policy(),
        ReductionPolicy {
            tool_output_keep_bytes: 0,
            tool_output_trigger_bytes: 0,
            protect_last_n_tool_results: 1,
            ..ReductionPolicy::default()
        },
        ReductionPolicy {
            tool_output_keep_bytes: 10,
            tool_output_trigger_bytes: 20,
            protect_last_n_tool_results: 3,
            ..ReductionPolicy::default()
        },
    ];

    for fixture_name in ["codex_session.jsonl", "claude_code_session.jsonl"] {
        let mut session = if fixture_name == "codex_session.jsonl" {
            load_codex()
        } else {
            load_claude()
        };
        pad_tool_output(&mut session, 0, 60_000);

        for policy in &policies {
            let (view, _log) = project(&session, policy, &ReductionLog::default());

            for (i, msg) in view.iter().enumerate() {
                for call in msg.tool_calls() {
                    if call.id.is_empty() {
                        continue;
                    }
                    let has_pair = view[i + 1..].iter().any(|m| {
                        m.role == Role::Tool && m.tool_call_id.as_deref() == Some(call.id.as_str())
                    });
                    assert!(
                        has_pair,
                        "{fixture_name}: tool_calls id {} at message {i} has no following tool \
                         result under policy {policy:?}",
                        call.id
                    );
                }
            }
        }
    }
}

// ---- A6: invert() / invert_one(), the identity invariant --------------------

#[test]
fn invert_project_is_identity() {
    for fixture_name in ["codex", "claude"] {
        let mut base = if fixture_name == "codex" {
            load_codex()
        } else {
            load_claude()
        };
        pad_tool_output(&mut base, 0, 50_000);
        // A9 matrix cell: an appended multimodal message with an
        // over-threshold `data:` image alongside the existing A7/A8/A10
        // kinds, so the invert-identity invariant is exercised for
        // `ImageRedacted` too (content_parts, not just content).
        base.messages.push(ChatMessage::user_with_images(
            "check this out",
            &[big_data_url("image/png", 20_000)],
        ));
        let policy = forcing_policy();

        // Fresh log.
        let (view, log) = project(&base, &policy, &ReductionLog::default());
        assert!(
            !log.reductions.is_empty(),
            "{fixture_name}: expected at least one reduction with the forcing policy"
        );
        assert!(
            log.reductions
                .iter()
                .any(|r| matches!(r.kind, ReductionKind::ImageRedacted { .. })),
            "{fixture_name}: expected an ImageRedacted reduction for the appended image message"
        );
        let inverted = invert(&view, &log, &base).unwrap();
        assert_identity(
            &format!("{fixture_name} fresh log"),
            &inverted,
            &base.messages,
        );

        // Incremental log after 2 synthetic appended turns.
        let mut grown = base.clone();
        append_synthetic_turns(&mut grown, 2);
        let (view2, log2) = project(&grown, &policy, &log);
        let inverted2 = invert(&view2, &log2, &grown).unwrap();
        assert_identity(
            &format!("{fixture_name} incremental log"),
            &inverted2,
            &grown.messages,
        );
    }
}

/// A minimal deterministic LCG — no `rand` dependency needed for the property
/// stress test.
struct Lcg(u64);

impl Lcg {
    fn next_u64(&mut self) -> u64 {
        // Numerical Recipes constants.
        self.0 = self
            .0
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        self.0
    }

    fn range(&mut self, lo: u64, hi_inclusive: u64) -> u64 {
        lo + self.next_u64() % (hi_inclusive - lo + 1)
    }
}

#[test]
fn invert_project_is_identity_property_stress() {
    let mut base = load_codex();
    pad_tool_output(&mut base, 0, 80_000);
    if tool_indices(&base).len() > 1 {
        pad_tool_output(&mut base, 1, 30_000);
    }
    // A9 coverage: an over-threshold `data:` image alongside the tool-output
    // padding, so every randomized policy below also exercises `ImageRedacted`
    // (image_redact_min_bytes is never randomized, so it triggers every
    // iteration).
    base.messages.push(ChatMessage::user_with_images(
        "photo",
        &[big_data_url("image/jpeg", 50_000)],
    ));

    let mut rng = Lcg(0x9E3779B97F4A7C15);
    for iter in 0..200 {
        let policy = ReductionPolicy {
            tool_output_keep_bytes: rng.range(0, 100_000) as usize,
            tool_output_trigger_bytes: rng.range(0, 100_000) as usize,
            protect_last_n_tool_results: rng.range(0, 4) as usize,
            ..ReductionPolicy::default()
        };
        let (view, log) = project(&base, &policy, &ReductionLog::default());
        let inverted = invert(&view, &log, &base).unwrap_or_else(|e| {
            panic!("iteration {iter} with policy {policy:?} failed to invert: {e}")
        });
        assert_identity(
            &format!("property stress iteration {iter} (policy {policy:?})"),
            &inverted,
            &base.messages,
        );
    }
}

#[test]
fn invert_errors_on_deleted_log_entry() {
    let mut base = load_codex();
    pad_tool_output(&mut base, 0, 50_000);
    let policy = forcing_policy();

    let (view, log) = project(&base, &policy, &ReductionLog::default());
    assert!(!log.reductions.is_empty());

    let mut tampered_log = log.clone();
    tampered_log.reductions.remove(0);

    let result = invert(&view, &tampered_log, &base);
    assert!(
        result.is_err(),
        "invert() should fail loudly when a reduction record is missing from the log, not \
         silently reproduce partial content"
    );
}

#[test]
fn invert_errors_on_tampered_sidecar_content() {
    let mut base = load_codex();
    pad_tool_output(&mut base, 0, 50_000);
    let policy = forcing_policy();

    let (view, log) = project(&base, &policy, &ReductionLog::default());
    assert!(!log.reductions.is_empty());

    let first = &log.reductions[0];
    let mut tampered = base.clone();
    let idx = first.ptr.addr.index;
    let mut content = tampered.messages[idx].content.clone().unwrap_or_default();
    content.push('X'); // flips the hash while staying valid UTF-8
    tampered.messages[idx].content = Some(content);

    let result = invert(&view, &log, &tampered);
    assert!(
        result.is_err(),
        "invert() should fail loudly (hash mismatch) against a tampered sidecar, never \
         substitute the wrong content"
    );
}

#[test]
fn invert_one_restores_exactly_one_record() {
    let mut base = load_codex();
    pad_tool_output(&mut base, 0, 80_000);
    if tool_indices(&base).len() > 1 {
        pad_tool_output(&mut base, 1, 40_000);
    }
    let policy = forcing_policy();

    let (view, log) = project(&base, &policy, &ReductionLog::default());
    assert!(
        log.reductions.len() >= 2,
        "need at least 2 reductions for this test to be meaningful (got {})",
        log.reductions.len()
    );

    let target = &log.reductions[0];
    let target_id = target.id.clone();
    let target_idx = target.ptr.addr.index;
    let other = &log.reductions[1];
    let other_idx = other.ptr.addr.index;
    let other_content_before = view[other_idx].content.clone();

    let (expanded, new_log) = invert_one(&view, &log, &target_id, &base).unwrap();

    // The targeted record was restored to the exact original content.
    let expected_original = base.messages[target_idx].content.clone();
    assert_eq!(
        expanded[target_idx].content, expected_original,
        "invert_one did not restore the targeted reduction's exact original content"
    );
    assert!(
        reduction_id(&expanded[target_idx]).is_none(),
        "invert_one should strip the sc.reduction metadata key from the expanded message"
    );

    // Every other stub is untouched, byte-for-byte.
    assert_eq!(
        expanded[other_idx].content, other_content_before,
        "invert_one must not touch other reductions' placeholders"
    );

    // The log no longer carries the expanded record.
    assert!(
        !new_log.reductions.iter().any(|r| r.id == target_id),
        "invert_one's returned log should no longer contain the expanded record"
    );
    assert_eq!(new_log.reductions.len(), log.reductions.len() - 1);
}

// ---- A10: TurnsCleared projection unit --------------------------------------

fn empty_session() -> Session {
    Session::from_claude_code_str("").unwrap()
}

#[test]
fn turns_cleared_is_deterministic_prefix_stable_and_invertible() {
    let mut session = empty_session();
    append_synthetic_turns(&mut session, 10); // 20 messages: 10 user, 10 assistant

    let policy = ReductionPolicy {
        clear_turns_older_than: Some(8),
        ..ReductionPolicy::default()
    };
    let prior = ReductionLog::default();

    // Determinism.
    let (view1, log1) = project(&session, &policy, &prior);
    let (view2, log2) = project(&session, &policy, &prior);
    assert!(
        messages_identical(&view1, &view2),
        "project() is not deterministic for TurnsCleared"
    );
    assert_eq!(log1, log2);

    // Exactly one TurnsCleared reduction, replacing a contiguous run of the
    // oldest messages with ONE system-role placeholder.
    assert_eq!(log1.reductions.len(), 1);
    let r = &log1.reductions[0];
    let (first, last) = match r.kind {
        ReductionKind::TurnsCleared { first, last, .. } => (first, last),
        ref other => panic!("expected TurnsCleared, got {other:?}"),
    };
    assert_eq!(first, 0, "clearing starts from the oldest message");
    assert!(last >= first);
    assert_eq!(r.ptr.span, None, "TurnsCleared pointers carry no byte span");
    assert!(r.placeholder.contains("turns-cleared"), "{}", r.placeholder);
    assert!(r.placeholder.contains(&r.id), "{}", r.placeholder);
    assert_eq!(
        view1.len(),
        session.messages.len() - (last - first + 1) + 1,
        "the cleared range collapses to exactly one placeholder message"
    );
    let placeholder_msg = &view1[first];
    assert_eq!(placeholder_msg.role, Role::System);
    assert_eq!(reduction_id(placeholder_msg), Some(r.id.as_str()));

    // Prefix stability: once established, the SAME reduction (same id, same
    // range, same byte-identical placeholder) reproduces verbatim on
    // re-projection even as the session keeps growing — it is never
    // recreated or widened (unlike `ToolOutputTruncated`). This test only
    // ever exercises the AUTO-COMPACTOR path (`clear_turns_older_than`),
    // which mints at most one `TurnsCleared` reduction, ever — a `/handoff`
    // (TR-9/T24), by contrast, can mint several (one per disjoint gap
    // between kept turns), which is why `project_messages`'s reapplication
    // step treats `TurnsCleared` records as a bag rather than a singleton.
    let mut grown = session.clone();
    append_synthetic_turns(&mut grown, 4);
    let (view3, log3) = project(&grown, &policy, &log1);
    assert_eq!(
        log3.reductions.len(),
        1,
        "TurnsCleared is a singleton reduction: further growth must not create a second one"
    );
    assert_eq!(
        log3.reductions[0], log1.reductions[0],
        "the established TurnsCleared reduction must reproduce verbatim"
    );
    assert_eq!(
        view1[first].content, view3[first].content,
        "the placeholder's byte content must not churn across re-projection"
    );

    // Invert restores the exact original messages (A6).
    let inverted = invert(&view1, &log1, &session).unwrap();
    assert_identity("turns-cleared", &inverted, &session.messages);
}

/// B7 coordination clamp: `ReductionPolicy::protect_imported_prefix` must
/// stop A10 turn-clearing from ever establishing a range that dips into the
/// protected leading messages (the imported session prefix a `CachePlan`
/// cache breakpoint depends on staying byte-identical).
#[test]
fn turns_cleared_never_crosses_the_protected_imported_prefix() {
    let mut session = empty_session();
    append_synthetic_turns(&mut session, 10); // 20 messages: 10 user, 10 assistant

    // Without the clamp this threshold clears starting at index 0 (proven by
    // the sibling test above). With `protect_imported_prefix` covering the
    // first 12 messages, clearing must start no earlier than index 12.
    let policy = ReductionPolicy {
        clear_turns_older_than: Some(8),
        protect_imported_prefix: Some(12),
        ..ReductionPolicy::default()
    };
    let prior = ReductionLog::default();

    let (view, log) = project(&session, &policy, &prior);
    assert_eq!(
        log.reductions.len(),
        1,
        "clearing must still occur beyond the protected prefix"
    );
    let (first, last) = match log.reductions[0].kind {
        ReductionKind::TurnsCleared { first, last, .. } => (first, last),
        ref other => panic!("expected TurnsCleared, got {other:?}"),
    };
    assert!(
        first >= 12,
        "clear range must never start inside the protected imported prefix: first={first}"
    );
    assert!(last >= first);

    // The protected prefix's messages are byte-identical, untouched.
    for (i, original) in session.messages.iter().take(12).enumerate() {
        assert_eq!(
            view[i].content, original.content,
            "protected message {i} must be untouched"
        );
        assert_eq!(
            reduction_id(&view[i]),
            None,
            "protected message {i} must carry no reduction"
        );
    }

    // A protection wide enough to leave no room beyond it (>= would-be `cut`)
    // must simply skip clearing entirely rather than ever violate the clamp.
    let too_wide_policy = ReductionPolicy {
        clear_turns_older_than: Some(8),
        protect_imported_prefix: Some(session.messages.len()), // the whole session
        ..ReductionPolicy::default()
    };
    let (view_none, log_none) = project(&session, &too_wide_policy, &ReductionLog::default());
    assert!(
        log_none.reductions.is_empty(),
        "no room beyond a full-session protection: clearing must not happen at all"
    );
    assert_eq!(view_none.len(), session.messages.len());
}

// ---- A8: stale-file-read elision with a recorded read-log -------------------

/// A dedicated temp directory per test invocation (mirrors
/// `reduce_loop.rs::temp_dir`), so parallel test runs never collide.
fn a8_temp_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("supercode-a8-{tag}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

/// Build an assistant message issuing a single `read_file` tool call for
/// `path`, with call id `id`.
fn read_call(id: &str, path: &Path) -> 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: "read_file".to_string(),
                arguments: serde_json::json!({ "path": path.to_string_lossy() }).to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

/// A deterministic all-ASCII 8 KB string — the "temp file F" content the A8
/// acceptance test reads.
fn eight_kb_content() -> String {
    (0..8192).map(|i| (b'a' + (i % 26) as u8) as char).collect()
}

/// Wraps `msgs` in a bare `Session` (via the empty-Claude-Code parse, same
/// idiom as `empty_session()` above) 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 = empty_session();
    session.messages = msgs;
    session
}

#[test]
fn stale_read_elided_fresh_read_kept() {
    let dir = a8_temp_dir("stale-read");
    let file_path = dir.join("f.txt");
    let original_content = eight_kb_content();
    std::fs::write(&file_path, &original_content).unwrap();

    // assistant read_file(F) -> tool result carrying F's content, then some
    // filler turns (so the read result isn't the newest tool result and
    // there's real conversation around it).
    let mut msgs = vec![
        ChatMessage::user("please read the file"),
        read_call("call_1", &file_path),
        ChatMessage::tool_result("call_1", "read_file", original_content.clone()),
    ];
    for i in 0..2 {
        msgs.push(ChatMessage::user(format!("filler {i}")));
        msgs.push(ChatMessage::assistant(format!("filler reply {i}")));
    }
    let read_idx = 2; // index of the tool-result message above

    let policy = ReductionPolicy {
        elide_stale_reads: true,
        protect_last_n_tool_results: 0,
        ..ReductionPolicy::default()
    };

    // ---- (i) F unchanged -> elided, and invert restores it exactly. ----
    let freshness = probe_read_freshness(&msgs);
    let policy_with_fresh = ReductionPolicy {
        read_freshness: freshness,
        ..policy.clone()
    };
    let (view, log) = project_messages(&msgs, &policy_with_fresh, &ReductionLog::default());

    assert_eq!(
        log.reductions.len(),
        1,
        "the fresh read should have produced exactly one reduction"
    );
    let r = &log.reductions[0];
    match &r.kind {
        ReductionKind::FileReadElided { path, read_log } => {
            assert_eq!(path, &file_path);
            assert_eq!(read_log.path, file_path);
            assert_eq!(read_log.addr.index, read_idx);
            assert_eq!(read_log.content_hash, r.ptr.content_hash);
        }
        other => panic!("expected FileReadElided, got {other:?}"),
    }
    assert_eq!(r.ptr.span, None, "whole-content elision carries no span");
    let placeholder = view[read_idx].content.clone().unwrap();
    assert!(
        placeholder.contains("file-read"),
        "placeholder should use the file-read stub kind: {placeholder}"
    );
    assert!(
        placeholder.contains(&file_path.to_string_lossy().to_string()),
        "placeholder should name the read path: {placeholder}"
    );
    assert!(
        placeholder.contains("unchanged on disk"),
        "placeholder should explain why it was elided: {placeholder}"
    );
    assert_eq!(reduction_id(&view[read_idx]), Some(r.id.as_str()));

    assert_eq!(
        log.read_log.len(),
        1,
        "every detected read appends to the read-log, elided or not"
    );
    assert_eq!(log.read_log[0].path, file_path);
    assert_eq!(log.read_log[0].addr.index, read_idx);

    let sidecar = session_of(msgs.clone());
    let inverted = invert(&view, &log, &sidecar).unwrap();
    assert_eq!(
        inverted[read_idx].content.as_deref(),
        Some(original_content.as_str()),
        "invert must restore the original 8KB content exactly"
    );
    assert_identity("stale-read fresh case", &inverted, &msgs);

    // ---- (ii) modify F on disk; re-project from the SAME prior log. ----
    // The previously-elided entry must stay elided verbatim (prefix
    // stability), and a second, brand-new read of F (added below, still
    // carrying the ORIGINAL pre-modification content, as if it had happened
    // before F changed) must NOT be newly elided once F no longer matches it.
    let mut grown = msgs.clone();
    grown.push(read_call("call_2", &file_path));
    grown.push(ChatMessage::tool_result(
        "call_2",
        "read_file",
        original_content.clone(),
    ));
    let second_read_idx = grown.len() - 1;

    let modified_content = format!("{original_content}-modified-on-disk");
    std::fs::write(&file_path, &modified_content).unwrap();

    let freshness2 = probe_read_freshness(&grown);
    let policy2 = ReductionPolicy {
        read_freshness: freshness2,
        ..policy.clone()
    };
    let (view2, log2) = project_messages(&grown, &policy2, &log);

    // The original elision reproduces byte-for-byte.
    assert_eq!(
        view2[read_idx].content, view[read_idx].content,
        "the previously-elided read must stay elided verbatim even though F changed"
    );
    let file_read_reductions: Vec<_> = log2
        .reductions
        .iter()
        .filter(|r| matches!(r.kind, ReductionKind::FileReadElided { .. }))
        .collect();
    assert_eq!(
        file_read_reductions.len(),
        1,
        "the changed file must not gain a NEW elision; only the original one survives"
    );
    assert_eq!(file_read_reductions[0], &log.reductions[0]);

    // The second read is present, unelided, content untouched.
    assert_eq!(
        view2[second_read_idx].content.as_deref(),
        Some(original_content.as_str()),
        "the second (now-stale) read must not be elided"
    );
    assert!(reduction_id(&view2[second_read_idx]).is_none());

    // The read-log now has two entries (deduped: re-projecting never
    // duplicates the first).
    assert_eq!(
        log2.read_log.len(),
        2,
        "read-log should record both reads, deduplicated across re-projection"
    );
    assert_eq!(log2.read_log[0].addr.index, read_idx);
    assert_eq!(log2.read_log[1].addr.index, second_read_idx);
    assert_eq!(log2.read_log[1].path, file_path);

    let sidecar2 = session_of(grown.clone());
    let inverted2 = invert(&view2, &log2, &sidecar2).unwrap();
    assert_identity("stale-read after on-disk modification", &inverted2, &grown);

    // ---- (iii) ReductionLog round-trips through JSON exactly. ----
    let json = serde_json::to_string(&log2).unwrap();
    let reloaded: ReductionLog = serde_json::from_str(&json).unwrap();
    assert_eq!(reloaded, log2, "ReductionLog must serde round-trip exactly");

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

#[test]
fn stale_read_unreadable_file_not_elided() {
    let dir = a8_temp_dir("unreadable");
    let file_path = dir.join("gone.txt");
    let content = eight_kb_content();
    std::fs::write(&file_path, &content).unwrap();

    let msgs = vec![
        ChatMessage::user("please read the file"),
        read_call("call_1", &file_path),
        ChatMessage::tool_result("call_1", "read_file", content.clone()),
    ];

    // The file no longer exists by the time projection probes it.
    std::fs::remove_file(&file_path).unwrap();

    let freshness = probe_read_freshness(&msgs);
    let policy = ReductionPolicy {
        elide_stale_reads: true,
        protect_last_n_tool_results: 0,
        read_freshness: freshness,
        ..ReductionPolicy::default()
    };
    let (view, log) = project_messages(&msgs, &policy, &ReductionLog::default());

    assert!(
        log.reductions.is_empty(),
        "an unreadable/deleted file must never be elided"
    );
    assert_eq!(
        log.read_log.len(),
        1,
        "the read is still recorded in the read-log even though it wasn't elided"
    );
    assert_eq!(view[2].content.as_deref(), Some(content.as_str()));

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

// ---- A9: image / base64 stripping to a redaction stub + pointer ------------

#[test]
fn image_redaction_data_url_threshold_mime_and_reversible() {
    let big = big_data_url("image/png", 20_000); // well over the 8192 default threshold
    let small = big_data_url("image/gif", 100); // well under it
    let remote = "https://example.com/photo.jpg".to_string();

    let msgs = vec![
        ChatMessage::user("hello"),
        ChatMessage::user_with_images("look", &[big.clone(), small.clone(), remote.clone()]),
    ];
    let policy = ReductionPolicy::default(); // redact_images: true by default (D14).
    let (view, log) = project_messages(&msgs, &policy, &ReductionLog::default());

    assert_eq!(
        log.reductions.len(),
        1,
        "only the over-threshold data: URL should become a candidate"
    );
    let r = &log.reductions[0];
    let part_index = match r.kind {
        ReductionKind::ImageRedacted { part_index } => part_index,
        ref other => panic!("expected ImageRedacted, got {other:?}"),
    };
    assert_eq!(
        part_index, 1,
        "the big image is content_parts[1] (after the caption text)"
    );
    assert_eq!(
        r.ptr.span, None,
        "whole-part redaction carries no byte span"
    );

    let parts = view[1].content_parts.as_ref().unwrap();
    assert_eq!(
        parts.len(),
        4,
        "redaction replaces a part in place; it never changes the part count"
    );
    assert_eq!(parts[0]["type"], "text");
    assert_eq!(parts[0]["text"], "look");

    // The redacted part becomes a text part carrying the frozen stub grammar.
    assert_eq!(parts[1]["type"], "text");
    let stub_text = parts[1]["text"].as_str().unwrap();
    assert!(stub_text.starts_with(REDUCTION_SENTINEL), "{stub_text}");
    assert!(stub_text.contains("image/png"), "{stub_text}");
    assert!(stub_text.contains("KB)"), "{stub_text}");
    assert_eq!(stub_text, r.placeholder);
    assert_eq!(reduction_id(&view[1]), Some(r.id.as_str()));

    // Under-threshold and remote-URL images are left untouched, byte-for-byte.
    assert_eq!(parts[2]["image_url"]["url"], small);
    assert_eq!(parts[3]["image_url"]["url"], remote);

    // No `data:` substring anywhere in the reduced view's serialized wire body.
    let body = serde_json::to_string(&view).unwrap();
    assert!(
        !body.contains("data:image/png"),
        "the redacted image's bytes must not reach the wire: {body}"
    );

    // Invert restores the exact original content part.
    let sidecar = session_of(msgs.clone());
    let inverted = invert(&view, &log, &sidecar).unwrap();
    assert_eq!(inverted[1].content_parts, msgs[1].content_parts);
    assert_identity("image redaction", &inverted, &msgs);

    // Prefix stability: re-projecting with the prior log reproduces the same
    // stub verbatim and does not create a second reduction.
    let (view2, log2) = project_messages(&msgs, &policy, &log);
    assert_eq!(log2, log);
    assert_eq!(view2[1].content_parts, view[1].content_parts);
}

/// Fixture guard (SPEC.md A9(b)): the two committed fixtures carry no
/// multimodal `content_parts` at all, so projecting them with
/// `redact_images = true` must be a complete no-op — same message count, zero
/// `ImageRedacted` records — keeping `roundtrip_regression.rs:74-133`'s
/// non-vacuity floors meaningful.
#[test]
fn image_redaction_is_noop_on_image_free_fixtures() {
    for (label, session) in [("codex", load_codex()), ("claude", load_claude())] {
        let policy = ReductionPolicy {
            redact_images: true,
            ..ReductionPolicy::default()
        };
        let before_count = session.messages.len();
        let (view, log) = project(&session, &policy, &ReductionLog::default());
        assert_eq!(
            view.len(),
            before_count,
            "{label}: redact_images must be a no-op on message count for an image-free fixture"
        );
        assert!(
            log.reductions
                .iter()
                .all(|r| !matches!(r.kind, ReductionKind::ImageRedacted { .. })),
            "{label}: an image-free fixture must never produce an ImageRedacted record"
        );
    }
}

// ---- TR-3 (T26): diff-only re-read representation (FileReadDiffed) --------

/// Deterministic multi-line file content: `n` lines of `"line NNNN\n"`.
fn n_line_file(n: usize) -> String {
    use std::fmt::Write;
    let mut out = String::with_capacity(n * 10);
    for i in 0..n {
        writeln!(out, "line {i:04}").unwrap();
    }
    out
}

/// `content` (as produced by [`n_line_file`]) with lines `[from, from+len)`
/// (0-indexed) replaced by `"CHANGED <i>"` — a small, contiguous, localized
/// edit that leaves the line count unchanged.
fn edit_lines(content: &str, from: usize, len: usize) -> String {
    let mut out = String::with_capacity(content.len());
    for (i, line) in content.lines().enumerate() {
        if i >= from && i < from + len {
            out.push_str(&format!("CHANGED {i}"));
        } else {
            out.push_str(line);
        }
        out.push('\n');
    }
    out
}

/// A policy that disables A7 entirely (`tool_output_trigger_bytes:
/// usize::MAX`) and never protects a tail, so a read-tool result is never
/// claimed by `ToolOutputTruncated` before TR-3 gets a chance to see it —
/// isolates the read-diffing pass from A7's own (already-covered) behavior.
/// `diff_rereads`/`diff_max_percent` are left at their defaults (`true`/`50`).
fn tr3_policy() -> ReductionPolicy {
    ReductionPolicy {
        tool_output_trigger_bytes: usize::MAX,
        protect_last_n_tool_results: 0,
        ..ReductionPolicy::default()
    }
}

/// dev/01 + dev/02: a small (3-line) edit in a 2,000-line file produces a
/// `FileReadDiffed` reduction whose projected bytes are a small fraction of
/// the full re-read (~95%+ saving), whose diff patch-applies cleanly onto
/// the base read's content to reproduce the new content exactly, and whose
/// `invert()` restores the verbatim full re-read.
#[test]
fn dev01_dev02_small_edit_re_read_diffs_and_invert_and_patch_apply() {
    let file_path = PathBuf::from("/workspace/src/foo.rs");
    let base_content = n_line_file(2000);
    let new_content = edit_lines(&base_content, 1000, 3);
    assert_ne!(base_content, new_content);

    let msgs = vec![
        ChatMessage::user("read the file"),
        read_call("c1", &file_path),
        ChatMessage::tool_result("c1", "read_file", base_content.clone()),
        ChatMessage::user("make a small edit"),
        ChatMessage::assistant("done"),
        read_call("c2", &file_path),
        ChatMessage::tool_result("c2", "read_file", new_content.clone()),
    ];
    let base_idx = 2;
    let new_idx = 6;

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

    assert_eq!(
        log.reductions.len(),
        1,
        "only the re-read should produce a reduction; the base read stays untouched: {log:#?}"
    );
    let r = &log.reductions[0];
    let (path, base, base_hash, new_hash, original_bytes, diff_bytes) = match &r.kind {
        ReductionKind::FileReadDiffed {
            path,
            base,
            base_hash,
            new_hash,
            original_bytes,
            diff_bytes,
        } => (
            path.clone(),
            *base,
            base_hash.clone(),
            new_hash.clone(),
            *original_bytes,
            *diff_bytes,
        ),
        other => panic!("expected FileReadDiffed, got {other:?}"),
    };
    assert_eq!(path, file_path);
    assert_eq!(base.index, base_idx);
    assert_eq!(base_hash, content_hash(base_content.as_bytes()));
    assert_eq!(new_hash, content_hash(new_content.as_bytes()));
    assert_eq!(original_bytes, new_content.len());
    assert_eq!(r.ptr.content_hash, new_hash);
    assert_eq!(
        r.ptr.span, None,
        "whole-content replacement carries no span"
    );
    assert_eq!(r.ptr.addr.index, new_idx);

    // dev/01: ~95%+ saving -- the diff is a small fraction of the full
    // re-read for a 3-line edit in a 2,000-line file.
    assert!(
        (diff_bytes as f64) <= (original_bytes as f64) * 0.10,
        "expected the diff to be a small fraction of the full content: {diff_bytes} / {original_bytes}"
    );

    let placeholder = view[new_idx].content.clone().unwrap();
    assert!(placeholder.starts_with(REDUCTION_SENTINEL));
    assert!(placeholder.contains("file-read-diffed"));
    assert_eq!(reduction_id(&view[new_idx]), Some(r.id.as_str()));
    assert!(
        placeholder.len() <= new_content.len() / 2,
        "projected bytes must be <= 50% of the full re-read: {} vs {}",
        placeholder.len(),
        new_content.len()
    );

    // dev/02: the projected diff, applied to the BASE read's content,
    // reproduces the new content exactly.
    let stub_line_end = placeholder.find('\n').expect("stub line then diff text");
    let diff_text = &placeholder[stub_line_end + 1..];
    let patch = diffy::Patch::from_str(diff_text).expect("projected diff must parse");
    let applied = diffy::apply(&base_content, &patch).expect("projected diff must apply cleanly");
    assert_eq!(
        applied, new_content,
        "patch-apply must reproduce the new content exactly"
    );

    // dev/01: invert() restores the verbatim full re-read.
    let sidecar = session_of(msgs.clone());
    let inverted = invert(&view, &log, &sidecar).unwrap();
    assert_eq!(
        inverted[new_idx].content.as_deref(),
        Some(new_content.as_str())
    );
    assert_identity("TR-3 small-edit re-read", &inverted, &msgs);

    // Prefix stability: re-projecting from the prior log reproduces the same
    // reduction verbatim.
    let (view2, log2) = project_messages(&msgs, &policy, &log);
    assert_eq!(log2, log);
    assert_eq!(view2[new_idx].content, view[new_idx].content);
}

/// dev/03: a rewrite whose diff would be >= the size guard produces NO
/// `FileReadDiffed` reduction at all — the full re-read stays untouched.
#[test]
fn dev03_large_change_guard_keeps_full_re_read() {
    let file_path = PathBuf::from("/workspace/src/rewrite.rs");
    let base_content = eight_kb_content(); // deterministic a-z cycling filler
    let new_content: String = (0..base_content.len())
        .map(|i| (b'0' + (i % 10) as u8) as char)
        .collect(); // disjoint character set -- a near-total rewrite

    let msgs = vec![
        ChatMessage::user("read the file"),
        read_call("c1", &file_path),
        ChatMessage::tool_result("c1", "read_file", base_content.clone()),
        ChatMessage::user("rewrite it completely"),
        ChatMessage::assistant("done"),
        read_call("c2", &file_path),
        ChatMessage::tool_result("c2", "read_file", new_content.clone()),
    ];
    let new_idx = 6;

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

    assert!(
        log.reductions.is_empty(),
        "a full rewrite must produce NO reduction at all (guard tripped): {log:#?}"
    );
    assert_eq!(
        view[new_idx].content.as_deref(),
        Some(new_content.as_str()),
        "the full re-read must stay untouched when the diff is too large to compress usefully"
    );
    assert!(reduction_id(&view[new_idx]).is_none());
    assert_eq!(
        log.read_log.len(),
        2,
        "both reads are still recorded in the read-log even though neither was reduced"
    );
}

/// dev/04: chained re-reads (read, edit, re-read, edit, re-read) each diff
/// against the correct base, all invert byte-exact, and the second diff's
/// base is the FIRST re-read's ORIGINAL bytes — never the base of the first
/// diff, and never a diff-of-diff.
#[test]
fn dev04_chained_re_reads_never_compound_diffs() {
    let file_path = PathBuf::from("/workspace/src/chain.rs");
    let v1 = n_line_file(500);
    let v2 = edit_lines(&v1, 100, 2); // edit A: lines 100-101
    let v3 = edit_lines(&v2, 300, 2); // edit B: lines 300-301, on top of v2

    let msgs = vec![
        ChatMessage::user("read"),
        read_call("c1", &file_path),
        ChatMessage::tool_result("c1", "read_file", v1.clone()),
        ChatMessage::user("edit A"),
        ChatMessage::assistant("done"),
        read_call("c2", &file_path),
        ChatMessage::tool_result("c2", "read_file", v2.clone()),
        ChatMessage::user("edit B"),
        ChatMessage::assistant("done"),
        read_call("c3", &file_path),
        ChatMessage::tool_result("c3", "read_file", v3.clone()),
    ];
    let idx1 = 2;
    let idx2 = 6;
    let idx3 = 10;

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

    assert_eq!(
        log.reductions.len(),
        2,
        "read1 has no prior read to diff against; read2 and read3 each diff: {log:#?}"
    );

    let r2 = log
        .reductions
        .iter()
        .find(|r| r.ptr.addr.index == idx2)
        .expect("read2's reduction");
    let r3 = log
        .reductions
        .iter()
        .find(|r| r.ptr.addr.index == idx3)
        .expect("read3's reduction");

    match &r2.kind {
        ReductionKind::FileReadDiffed {
            base, base_hash, ..
        } => {
            assert_eq!(base.index, idx1, "read2's base must be read1");
            assert_eq!(base_hash, &content_hash(v1.as_bytes()));
        }
        other => panic!("expected FileReadDiffed for read2, got {other:?}"),
    }
    match &r3.kind {
        ReductionKind::FileReadDiffed {
            base, base_hash, ..
        } => {
            assert_eq!(
                base.index, idx2,
                "read3's base must be read2 (its ORIGINAL bytes) -- never read1, and never a diff-of-diff"
            );
            assert_eq!(base_hash, &content_hash(v2.as_bytes()));
        }
        other => panic!("expected FileReadDiffed for read3, got {other:?}"),
    }

    // Patch-apply proof: read3's projected diff, applied to v2 (read2's
    // ORIGINAL bytes), reproduces v3 exactly.
    let placeholder3 = view[idx3].content.clone().unwrap();
    let diff_text3 = &placeholder3[placeholder3.find('\n').unwrap() + 1..];
    let patch3 = diffy::Patch::from_str(diff_text3).unwrap();
    let applied3 = diffy::apply(&v2, &patch3).unwrap();
    assert_eq!(applied3, v3);

    // Every re-read still inverts byte-exact.
    let sidecar = session_of(msgs.clone());
    let inverted = invert(&view, &log, &sidecar).unwrap();
    assert_eq!(inverted[idx2].content.as_deref(), Some(v2.as_str()));
    assert_eq!(inverted[idx3].content.as_deref(), Some(v3.as_str()));
    assert_identity("TR-3 chained re-reads", &inverted, &msgs);
}

/// dev/05: the A8-vs-TR-3 precedence rule. An UNCHANGED re-read still takes
/// the A8 elision path (never a zero-hunk diff); a CHANGED re-read takes the
/// TR-3 diff path even when A8's own disk-freshness probe would also
/// consider it "fresh" (matches the current disk state) -- TR-3 has
/// exclusive claim on any re-read whose content differs from the prior read
/// of the same path.
#[test]
fn dev05_a8_vs_tr3_precedence_by_case() {
    // ---- (a) unchanged re-read: A8 elides it, never a zero-hunk diff. ----
    let dir_a = a8_temp_dir("tr3-precedence-unchanged");
    let path_a = dir_a.join("f.txt");
    let content_a = eight_kb_content();
    std::fs::write(&path_a, &content_a).unwrap();

    let msgs_a = vec![
        ChatMessage::user("read"),
        read_call("ca1", &path_a),
        ChatMessage::tool_result("ca1", "read_file", content_a.clone()),
        ChatMessage::user("read again"),
        read_call("ca2", &path_a),
        ChatMessage::tool_result("ca2", "read_file", content_a.clone()),
    ];
    let idx_a2 = 5;

    let freshness_a = probe_read_freshness(&msgs_a);
    let policy_a = ReductionPolicy {
        elide_stale_reads: true,
        diff_rereads: true,
        protect_last_n_tool_results: 0,
        tool_output_trigger_bytes: usize::MAX,
        read_freshness: freshness_a,
        ..ReductionPolicy::default()
    };
    let (_, log_a) = project_messages(&msgs_a, &policy_a, &ReductionLog::default());
    let r_a2 = log_a
        .reductions
        .iter()
        .find(|r| r.ptr.addr.index == idx_a2)
        .expect("the unchanged re-read must be reduced");
    assert!(
        matches!(r_a2.kind, ReductionKind::FileReadElided { .. }),
        "an unchanged re-read must take the A8 elision path, not a zero-hunk diff: {:?}",
        r_a2.kind
    );

    std::fs::remove_dir_all(&dir_a).ok();

    // ---- (b) changed re-read: TR-3 claims it even though A8's own
    // freshness probe ALSO says it's "fresh" (matches current disk). ----
    let dir_b = a8_temp_dir("tr3-precedence-changed");
    let path_b = dir_b.join("f.txt");
    let content_b1 = n_line_file(500);
    let content_b2 = edit_lines(&content_b1, 250, 2);
    std::fs::write(&path_b, &content_b1).unwrap();

    let msgs_b = vec![
        ChatMessage::user("read"),
        read_call("cb1", &path_b),
        ChatMessage::tool_result("cb1", "read_file", content_b1.clone()),
        ChatMessage::user("edit"),
        ChatMessage::assistant("done"),
        read_call("cb2", &path_b),
        ChatMessage::tool_result("cb2", "read_file", content_b2.clone()),
    ];
    let idx_b1 = 2;
    let idx_b2 = 6;

    // The file on disk now matches content_b2 (the edit really happened) --
    // so read_b2's OWN freshness probe says "fresh" too, exactly what A8
    // would ordinarily require for elision.
    std::fs::write(&path_b, &content_b2).unwrap();
    let freshness_b = probe_read_freshness(&msgs_b);
    let policy_b = ReductionPolicy {
        elide_stale_reads: true,
        diff_rereads: true,
        protect_last_n_tool_results: 0,
        tool_output_trigger_bytes: usize::MAX,
        read_freshness: freshness_b,
        ..ReductionPolicy::default()
    };
    let (view_b, log_b) = project_messages(&msgs_b, &policy_b, &ReductionLog::default());
    let r_b2 = log_b
        .reductions
        .iter()
        .find(|r| r.ptr.addr.index == idx_b2)
        .expect("the changed re-read must be reduced");
    assert!(
        matches!(r_b2.kind, ReductionKind::FileReadDiffed { .. }),
        "a changed re-read must take the TR-3 diff path even when A8 also considers it fresh: {:?}",
        r_b2.kind
    );
    // read_b1 is now stale versus the post-edit disk state, so A8 correctly
    // leaves it untouched -- confirms the fixture behaves as described.
    assert!(reduction_id(&view_b[idx_b1]).is_none());

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

// ---- fix pass (FIX #4): partial-window reads are out of TR-3's v1 scope ----

/// Build an assistant message issuing a single `read_file` tool call for
/// `path` with a partial-window `offset`/`limit` (mirrors `read_call` above,
/// but stamps the window arguments TR-3.md's frozen spec excludes from v1:
/// "Partial-window reads (offset/limit) are out of scope for v1 — full-file
/// reads only").
fn read_call_windowed(id: &str, path: &Path, offset: usize, limit: usize) -> 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: "read_file".to_string(),
                arguments: serde_json::json!({
                    "path": path.to_string_lossy(),
                    "offset": offset,
                    "limit": limit,
                })
                .to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

/// Two same-path reads with DIFFERENT offset/limit windows and a small
/// textual difference must never mint a `FileReadDiffed` — a unified diff
/// between two arbitrary windows would misrepresent a window change as a
/// file change, exactly what TR-3.md's frozen v1 scope exclusion (full-file
/// reads only) rules out. The full re-read must stay untouched in the view.
#[test]
fn windowed_re_read_never_mints_file_read_diffed() {
    let file_path = PathBuf::from("/workspace/src/windowed.rs");
    let base_content = n_line_file(200);
    // A genuinely different window's content AND a small textual tweak, so
    // if the guard were absent this would otherwise be a small, well-within-
    // guard diff candidate.
    let new_content = edit_lines(&base_content, 50, 2);

    let msgs = vec![
        ChatMessage::user("read a slice of the file"),
        read_call_windowed("c1", &file_path, 1, 100),
        ChatMessage::tool_result("c1", "read_file", base_content.clone()),
        ChatMessage::user("read a different slice"),
        read_call_windowed("c2", &file_path, 50, 100),
        ChatMessage::tool_result("c2", "read_file", new_content.clone()),
    ];
    let idx1 = 2;
    let idx2 = 5;

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

    assert!(
        !log.reductions
            .iter()
            .any(|r| matches!(r.kind, ReductionKind::FileReadDiffed { .. })),
        "a partial-window re-read must never mint FileReadDiffed: {:?}",
        log.reductions
    );
    // The full re-read stays completely untouched in the view.
    assert_eq!(view[idx1].content.as_deref(), Some(base_content.as_str()));
    assert_eq!(view[idx2].content.as_deref(), Some(new_content.as_str()));
    assert!(reduction_id(&view[idx1]).is_none());
    assert!(reduction_id(&view[idx2]).is_none());
}