lean-ctx-proxy 3.12.3

The LeanCTX model-API proxy: provider adapters, compression and accounting on top of LeanCTX | OSS.
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
// SPDX-License-Identifier: Apache-2.0
use super::super::compress::compress_tool_result;
use super::*;

fn source_file_body() -> Vec<u8> {
    let code = (0..60)
        .map(|i| format!("    let binding_{i} = compute_value_{i}(context, options);"))
        .collect::<Vec<_>>()
        .join("\n");
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "messages": [
            {
                "role": "assistant",
                "content": [{"type": "tool_use", "id": "toolu_1", "name": "Read", "input": {"file_path": "src/app.rs"}}]
            },
            {
                "role": "user",
                "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": code}]
            }
        ]
    });
    serde_json::to_vec(&body).unwrap()
}

#[test]
fn read_tool_result_is_never_truncated() {
    let bytes = source_file_body();
    let body: Value = serde_json::from_slice(&bytes).unwrap();
    let (out, _orig, _comp) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();
    let content = parsed["messages"][1]["content"][0]["content"]
        .as_str()
        .unwrap();
    assert!(
        content.contains("binding_59"),
        "the full source body must survive — refactors need it intact"
    );
    assert!(!content.contains("lines omitted"));
}

fn forge_log_body(tool_name: &str) -> Value {
    // Generic, highly-repetitive log with no `$ cmd` hint, so routing falls
    // back to the tool name (exercising the foreign-tool classification)
    // and the generic compressor (not a command-specific pattern).
    let mut log = String::new();
    for i in 0..90 {
        log.push_str(&format!(
            "INFO  processing item {i}: ok, latency={i}ms, queue depth normal, retries 0\n"
        ));
    }
    serde_json::json!({
        "messages": [
            {"role": "assistant", "content": [{"type": "tool_use", "id": "f1", "name": tool_name, "input": {}}]},
            {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "f1", "content": log}]}
        ]
    })
}

#[test]
fn forge_shell_tool_result_compresses() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    // A vendor-prefixed foreign shell tool reaches the proxy; its log output
    // must still be compressed (rtk/ctx_* never see another server's tools).
    let body = forge_log_body("forge_shell");
    let bytes = serde_json::to_vec(&body).unwrap();
    let (_out, orig, comp) = compress_request_body(body, bytes.len());
    assert!(comp < orig, "foreign shell output must be compressed");
}

#[test]
fn foreign_read_tool_protects_source() {
    // `forge_read` is classified FileRead via the segment fallback, so the
    // source body must reach the model intact (it is what gets edited).
    let code = (0..60)
        .map(|i| format!("    let binding_{i} = compute_value_{i}(context, options);"))
        .collect::<Vec<_>>()
        .join("\n");
    let body = serde_json::json!({
        "messages": [
            {"role": "assistant", "content": [{"type": "tool_use", "id": "r1", "name": "forge_read", "input": {"path": "src/app.rs"}}]},
            {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "r1", "content": code}]}
        ]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _orig, _comp) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();
    let content = parsed["messages"][1]["content"][0]["content"]
        .as_str()
        .unwrap();
    assert!(
        content.contains("binding_59"),
        "source body must survive intact"
    );
}

#[test]
fn compress_request_body_is_deterministic() {
    // Config and tee paths are process-global; isolate them so concurrent tests
    // cannot change proxy behavior between the two identical inputs. The
    // isolated data dir also holds the env lock, so a parallel test never
    // swaps LEAN_CTX_DATA_DIR between the two compressions.
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    // #498: the proxy rewrite must be a pure function of the body so the
    // provider prompt-cache prefix stays byte-identical across turns.
    let bytes = serde_json::to_vec(&forge_log_body("Bash")).unwrap();
    let a = compress_request_body(serde_json::from_slice(&bytes).unwrap(), bytes.len()).0;
    let b = compress_request_body(serde_json::from_slice(&bytes).unwrap(), bytes.len()).0;
    assert_eq!(a, b, "identical input must yield byte-identical output");
}

/// A large, highly-compressible foreign log so the live path tees + stubs it.
fn big_log() -> String {
    (0..200)
        .map(|i| format!("[info] processed item {i:04} ok, latency {i}ms, queue normal"))
        .collect::<Vec<_>>()
        .join("\n")
}

#[test]
fn inband_ccr_emit_echo_splice_round_trip() {
    // Full #493 cycle through the real Anthropic request path: a lossy stub
    // emits an <lc_expand:HASH> marker, the model echoes it, and the proxy
    // splices the verbatim original back inline on the next request.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CCR_INBAND");
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.ccr_inband = Some(true);
    })
    .unwrap();

    // EMIT: live-compress a foreign tool_result → recovery stub with a marker.
    let log = big_log();
    let emit = serde_json::json!({
        "messages": [
            {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "bash", "input": {}}]},
            {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": log}]}
        ]
    });
    let bytes = serde_json::to_vec(&emit).unwrap();
    let (out, _o, _c) = compress_request_body(emit, bytes.len());
    let emitted: Value = serde_json::from_slice(&out).unwrap();
    let stub = emitted["messages"][1]["content"][0]["content"]
        .as_str()
        .unwrap();
    assert!(
        stub.contains("<lc_expand:"),
        "in-band stub must advertise an echo-able marker: {stub}"
    );
    assert!(
        !stub.contains("/tee/proxy_"),
        "in-band stub must not leak the unreachable local tee path: {stub}"
    );

    // The marker the model would copy into its next turn.
    let start = stub.find("<lc_expand:").unwrap();
    let end = stub[start..].find('>').unwrap() + start + 1;
    let marker = &stub[start..end];

    // ECHO + SPLICE: the model echoes the marker; the proxy splices the
    // verbatim original (recovered from the local tee store) back inline.
    let echo = serde_json::json!({
        "messages": [
            {"role": "user", "content": [{"type": "text", "text": "look again"}]},
            {"role": "assistant", "content": format!("revisiting that output: {marker}")}
        ]
    });
    let bytes = serde_json::to_vec(&echo).unwrap();
    let (out, _o, _c) = compress_request_body(echo, bytes.len());
    let spliced: Value = serde_json::from_slice(&out).unwrap();
    let assistant = spliced["messages"][1]["content"].as_str().unwrap();
    assert!(
        assistant.contains("processed item 0007 ok")
            && assistant.contains("processed item 0199 ok"),
        "the verbatim original must be spliced back in full: {assistant}"
    );
    assert!(
        !assistant.contains("<lc_expand:"),
        "the marker must be consumed by the splice"
    );
}

/// Long-session elision through the real request path: old tool output
/// leaves as a stub, the client's marker survives, and a prompt turn after
/// the tool turn sends the same prefix bytes.
#[test]
fn long_session_elision_keeps_the_prefix_across_prompt_turns() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    // Opt-in since 3.12.1.
    let _elide = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_PROXY_LONG_SESSION_ELIDE", "on");
    let mut messages = vec![serde_json::json!({"role": "user", "content": "fix the build"})];
    for turn in 0..40 {
        let id = format!("t{turn}");
        messages.push(serde_json::json!({"role": "assistant", "content": [
            {"type": "tool_use", "id": id, "name": "Bash", "input": {"command": format!("make step{turn}")}}
        ]}));
        let output = (0..400)
            .map(|line| format!("step {turn} line {line}: compiled module_{line}.o"))
            .collect::<Vec<_>>()
            .join("\n");
        messages.push(serde_json::json!({"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": id, "content": output}
        ]}));
    }
    let last = messages.len() - 1;
    messages[last]["content"][0]["cache_control"] = serde_json::json!({"type": "ephemeral"});
    let run = |messages: Vec<Value>| {
        let body = serde_json::json!({"model": "claude-haiku-5-5", "messages": messages});
        let bytes = serde_json::to_vec(&body).unwrap();
        let out = compress_request_body(body, bytes.len()).0;
        serde_json::from_slice::<Value>(&out).unwrap()
    };

    let looped = run(messages.clone());
    let stub = looped["messages"][2]["content"][0]["content"]
        .as_str()
        .unwrap();
    assert!(
        stub.starts_with(super::super::session_elide::STUB_OPEN),
        "{stub}"
    );
    assert!(
        looped["messages"][last]["content"][0]
            .get("cache_control")
            .is_some(),
        "the client's marker stays"
    );

    // The person's next prompt (81 → 83 messages, same stride boundary 64)
    // sends the same elided prefix: it reads the cache the tool turn wrote
    // instead of falling back to the whole history.
    messages.push(serde_json::json!({"role": "assistant", "content": "done"}));
    messages.push(serde_json::json!({"role": "user", "content": "now the docs"}));
    let prompted = run(messages);
    let prefix =
        |doc: &Value| serde_json::to_vec(&doc["messages"].as_array().unwrap()[..64]).unwrap();
    assert_eq!(prefix(&prompted), prefix(&looped));
}

#[test]
fn inband_marker_less_turn_is_byte_identical_on_or_off() {
    // Cache-safety (#493): enabling in-band must be a strict no-op on a turn
    // with no marker — same bytes on the wire, so the provider cache prefix is
    // never perturbed unless the model actually asked to expand. Uses a body
    // with nothing to prune/compress, isolating the splice from stub emission.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CCR_INBAND");
    let body = serde_json::json!({
        "messages": [
            {"role": "user", "content": [{"type": "text", "text": "hello there"}]},
            {"role": "assistant", "content": "hi — how can I help?"}
        ]
    });
    let bytes = serde_json::to_vec(&body).unwrap();

    lean_ctx::core::config::Config::update_global(|c| c.proxy.ccr_inband = Some(false)).unwrap();
    let off = compress_request_body(body.clone(), bytes.len()).0;
    lean_ctx::core::config::Config::update_global(|c| c.proxy.ccr_inband = Some(true)).unwrap();
    let on = compress_request_body(body, bytes.len()).0;

    assert_eq!(
        off, on,
        "a marker-less request must be byte-identical whether in-band is on or off"
    );
}

/// Long, duplicate-rich natural-language prose that compresses cleanly.
fn big_prose() -> String {
    let p = "You are a careful, senior software engineer. You always explain your \
             reasoning before making changes, you prefer small reviewable diffs, and \
             you never introduce mock data or placeholders into production code. ";
    [p; 6].join("\n")
}

#[test]
fn system_prose_compressed_and_assistant_untouched() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.system = Some(0.6);
        c.proxy.role_aggressiveness.user = Some(0.6);
    })
    .unwrap();

    let prose = big_prose();
    let assistant_text = big_prose();
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": prose,
        "messages": [
            {"role": "user", "content": [{"type": "text", "text": prose}]},
            {"role": "assistant", "content": assistant_text},
        ]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _orig, _comp) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();

    assert!(
        parsed["system"].as_str().unwrap().len() < prose.len(),
        "system prose must be compressed when enabled"
    );
    assert_eq!(
        parsed["messages"][1]["content"].as_str().unwrap(),
        assistant_text,
        "assistant turns must pass through verbatim (#710)"
    );
}

#[test]
fn user_prose_compressed_only_in_frozen_region() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.user = Some(0.7);
    })
    .unwrap();

    let prose = big_prose();
    // 30 messages → cache-aware boundary = ((30-8)/16)*16 = 16.
    let mut messages = Vec::new();
    for i in 0..30 {
        let role = if i % 2 == 0 { "user" } else { "assistant" };
        messages.push(serde_json::json!({
            "role": role,
            "content": [{"type": "text", "text": prose}]
        }));
    }
    let body = serde_json::json!({ "messages": messages });
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();

    let frozen_user = parsed["messages"][0]["content"][0]["text"]
        .as_str()
        .unwrap();
    assert!(
        frozen_user.len() < prose.len(),
        "user prose in the frozen region must be compressed"
    );
    assert_eq!(
        parsed["messages"][1]["content"][0]["text"]
            .as_str()
            .unwrap(),
        prose,
        "assistant prose is never compressed"
    );
    let live_tail_user = parsed["messages"][28]["content"][0]["text"]
        .as_str()
        .unwrap();
    assert_eq!(
        live_tail_user, prose,
        "user prose in the live tail (>= boundary) must be preserved for quality"
    );
}

#[test]
fn client_cached_prefix_disables_system_prose() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.system = Some(0.9);
    })
    .unwrap();

    let prose = big_prose();
    let body = serde_json::json!({
        "system": prose,
        "messages": [
            {"role": "user", "content": [
                {"type": "text", "text": "hi", "cache_control": {"type": "ephemeral"}}
            ]},
            {"role": "assistant", "content": "ok"}
        ]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        parsed["system"].as_str().unwrap(),
        prose,
        "system must stay verbatim when the client caches a message prefix (#448)"
    );
}

#[test]
fn prose_compression_is_deterministic() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.system = Some(0.6);
    })
    .unwrap();
    let prose = big_prose();
    let mk =
        || serde_json::json!({"system": prose, "messages": [{"role": "user", "content": "hi"}]});
    let (a, b) = (mk(), mk());
    let la = serde_json::to_vec(&a).unwrap().len();
    let lb = serde_json::to_vec(&b).unwrap().len();
    assert_eq!(
        compress_request_body(a, la).0,
        compress_request_body(b, lb).0,
        "prose compression must be byte-identical for identical input (#498)"
    );
}

#[test]
fn bash_tool_result_still_compresses() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    let log = {
        let mut s = String::from(
            "$ git status\nOn branch main\nYour branch is up to date with 'origin/main'.\n\nChanges not staged for commit:\n  (use \"git add <file>...\" to update what will be committed)\n",
        );
        for i in 0..90 {
            s.push_str(&format!("\tmodified:   src/module_{i}/file_{i}.rs\n"));
        }
        s.push_str("\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n");
        s
    };
    let body = serde_json::json!({
        "messages": [
            {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "Bash", "input": {}}]},
            {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": log}]}
        ]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    let (_out, orig, comp) = compress_request_body(body, bytes.len());
    assert!(comp < orig, "shell output must still be compressed");
}

#[test]
fn json_envelope_tool_result_is_compressed() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    let log = long_git_status();
    let expected = compress_tool_result(&log, Some("Bash"));
    let envelope = serde_json::to_string(&serde_json::json!({
        "content": [{"type": "text", "text": log}],
        "isError": false,
    }))
    .unwrap();
    let body = serde_json::json!({
        "messages": [
            {"role": "assistant", "content": [{
                "type": "tool_use",
                "id": "t1",
                "name": "Bash",
                "input": {}
            }]},
            {"role": "user", "content": [{
                "type": "tool_result",
                "tool_use_id": "t1",
                "content": envelope
            }]}
        ]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, orig, comp) = compress_request_body(body, bytes.len());

    assert!(comp < orig, "JSON envelope tool result should shrink");
    let parsed: Value = serde_json::from_slice(&out).unwrap();
    let content = parsed["messages"][1]["content"][0]["content"]
        .as_str()
        .unwrap();
    let envelope: Value = serde_json::from_str(content).unwrap();
    assert_eq!(envelope["content"][0]["text"].as_str().unwrap(), expected);
}

fn long_git_status() -> String {
    let mut s = String::from(
        "$ git status\nOn branch main\nYour branch is up to date with 'origin/main'.\n\nChanges not staged for commit:\n  (use \"git add <file>...\" to update what will be committed)\n",
    );
    for i in 0..80 {
        s.push_str(&format!("\tmodified:   src/module_{i}/file_{i}.rs\n"));
    }
    s.push_str("\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n");
    s
}

/// A client-cached message anchors the prefix; `system` precedes it, so the
/// cached prefix is `cached > 0` and system prose is normally protected.
/// System-prose verbatim-vs-rewritten is therefore a clean binary signal for
/// whether the #480 cold-prefix repack fired.
///
/// `first_text` must be UNIQUE per test: it is `messages[0]`, which the
/// cold-prefix tracker hashes into the conversation key. A shared global
/// last-touch store has no test-clear hook (that would race with the unit
/// tests), so distinct keys are how parallel tests stay isolated.
fn cached_prefix_body(first_text: &str, prose: &str) -> (Vec<Value>, Value) {
    let messages = vec![
        serde_json::json!({"role": "user", "content": [
            {"type": "text", "text": first_text, "cache_control": {"type": "ephemeral"}}
        ]}),
        serde_json::json!({"role": "assistant", "content": "ok"}),
    ];
    let body = serde_json::json!({ "system": prose, "messages": messages.clone() });
    (messages, body)
}

#[test]
fn cold_prefix_repack_rewrites_protected_system_prose_when_enabled() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    // Restored on drop, before the environment lock above is released: the
    // mode of this test is not the mode of whatever test runs next.
    let _mode = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_PROXY_MODE", "cache");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_COLD_PREFIX_REPACK");
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.system = Some(0.9);
        c.proxy.cold_prefix_repack = Some(true);
    })
    .unwrap();

    // The prefix must clear the cacheable floor: with premium defaults the
    // net-cost gate (#986, on by default) skips repacking a sub-1024-token
    // prefix the provider could never cache. A real cold prefix worth
    // re-seeding is large, so size the system prose accordingly.
    let prose = big_prose().repeat(6);
    let (messages, body) = cached_prefix_body("cold-repack-enabled-session", &prose);
    // Predict cold: last touched 3h ago, well past the 5m default TTL × margin.
    super::super::cold_prefix::test_seed_last_touch(&messages, 3 * 60 * 60);

    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();
    assert!(
        parsed["system"].as_str().unwrap().len() < prose.len(),
        "a predicted-cold prefix must let the proxy repack the otherwise-protected system prose"
    );
}

#[test]
fn cold_prefix_repack_skipped_for_subcacheable_prefix_by_default() {
    // #986 premium default: cache_policy is on, so the net-cost gate skips a
    // cold repack of a prefix below the provider's cacheable minimum —
    // re-seeding it could never produce a cache the provider keeps. Repack is
    // enabled and the prefix is cold, but it is too small (≈345 tokens) to
    // cache, so the system prose must stay protected (unchanged).
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_COLD_PREFIX_REPACK");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_POLICY");
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.system = Some(0.9);
        c.proxy.cold_prefix_repack = Some(true);
    })
    .unwrap();

    let prose = big_prose();
    let (messages, body) = cached_prefix_body("cold-repack-subcacheable-session", &prose);
    super::super::cold_prefix::test_seed_last_touch(&messages, 3 * 60 * 60);

    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        parsed["system"].as_str().unwrap(),
        prose,
        "the net-cost gate must skip repacking a sub-cacheable prefix (premium default)"
    );
}

#[test]
fn cold_prefix_repack_off_by_default_keeps_prefix_protected() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_COLD_PREFIX_REPACK");
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.system = Some(0.9);
        c.proxy.cold_prefix_repack = Some(false);
    })
    .unwrap();

    let prose = big_prose();
    let (messages, body) = cached_prefix_body("cold-repack-disabled-session", &prose);
    // Even with a huge idle gap, default-off must never touch the prefix.
    super::super::cold_prefix::test_seed_last_touch(&messages, 24 * 60 * 60);

    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        parsed["system"].as_str().unwrap(),
        prose,
        "with repack off the cached prefix stays byte-stable regardless of idle time (#448)"
    );
}

#[test]
fn cold_prefix_repack_protects_warm_prefix_even_when_enabled() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_COLD_PREFIX_REPACK");
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.system = Some(0.9);
        c.proxy.cold_prefix_repack = Some(true);
    })
    .unwrap();

    let prose = big_prose();
    let (messages, body) = cached_prefix_body("cold-repack-warm-session", &prose);
    // Warm: touched 1 minute ago → the prediction must keep protecting.
    super::super::cold_prefix::test_seed_last_touch(&messages, 60);

    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let parsed: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        parsed["system"].as_str().unwrap(),
        prose,
        "a warm prefix must stay protected even with repack enabled — only LARGE gaps trigger"
    );
}

#[test]
fn cache_policy_attribution_is_measurement_only() {
    // #986: enabling cache-economics records miss-attribution telemetry but
    // must never change the bytes on the wire — the same request compressed
    // with the policy off vs on is byte-identical (strictly cache-safe).
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_POLICY");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_COLD_PREFIX_REPACK");

    let prose = big_prose();
    let (_messages, body) = cached_prefix_body("cache-policy-measurement-session", &prose);
    let bytes = serde_json::to_vec(&body).unwrap();

    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.cache_policy = Some(false);
    })
    .unwrap();
    let (off, _o, _c) = compress_request_body(body.clone(), bytes.len());

    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.cache_policy = Some(true);
    })
    .unwrap();
    let (on, _o, _c) = compress_request_body(body, bytes.len());

    assert_eq!(
        off, on,
        "miss attribution is measurement-only: the wire bytes must not change"
    );
}

#[test]
fn effort_control_dials_adaptive_thinking_only() {
    // #834 end-to-end: fill output_config.effort when the client already
    // asked for adaptive thinking, but never enable thinking otherwise.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_EFFORT");
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.effort = Some("medium".into());
    })
    .unwrap();

    let adaptive = serde_json::json!({
        "model": "claude-opus-4-8",
        "thinking": {"type": "adaptive"},
        "messages": [{"role": "user", "content": "hi"}]
    });
    let bytes = serde_json::to_vec(&adaptive).unwrap();
    let (out, _o, _c) = compress_request_body(adaptive, bytes.len());
    assert_eq!(
        serde_json::from_slice::<Value>(&out).unwrap()["output_config"]["effort"],
        "medium"
    );

    // No thinking field → the proxy must not add output_config (no surprise
    // reasoning cost, no 400 risk).
    let plain = serde_json::json!({
        "model": "claude-opus-4-8",
        "messages": [{"role": "user", "content": "hi"}]
    });
    let bytes = serde_json::to_vec(&plain).unwrap();
    let (out, _o, _c) = compress_request_body(plain, bytes.len());
    assert!(
        serde_json::from_slice::<Value>(&out)
            .unwrap()
            .get("output_config")
            .is_none()
    );
}

#[test]
fn verbosity_steer_applies_to_treatment_skips_control() {
    // #895: the holdout control arm must be byte-unchanged (so its output is
    // the measurement baseline); the treatment arm gets the constant steer.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_VERBOSITY_STEER");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_OUTPUT_HOLDOUT");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_EFFORT");

    let req = serde_json::json!({
        "model": "claude-opus-4-8",
        "messages": [{"role": "user", "content": "Summarize the design."}]
    });
    let bytes = serde_json::to_vec(&req).unwrap();

    // Steer on, holdout = 0 → everyone Treatment → steered.
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.verbosity_steer = Some(true);
        c.proxy.output_holdout = Some(0.0);
    })
    .unwrap();
    let (out, _o, _c) = compress_request_body(req.clone(), bytes.len());
    let v: Value = serde_json::from_slice(&out).unwrap();
    assert!(
        v["messages"][0]["content"]
            .as_str()
            .unwrap()
            .contains(crate::verbosity::STEER),
        "treatment arm must receive the verbosity steer"
    );

    // Steer on, holdout = 1.0 → everyone Control → byte-unchanged, no steer.
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.output_holdout = Some(1.0);
    })
    .unwrap();
    let (out2, _o, _c) = compress_request_body(req, bytes.len());
    let v2: Value = serde_json::from_slice(&out2).unwrap();
    assert!(
        !v2["messages"][0]["content"]
            .as_str()
            .unwrap()
            .contains(crate::verbosity::STEER),
        "control arm must NOT be steered (measurement baseline)"
    );
}

/// A system prompt comfortably over Anthropic's minimum cacheable size, so
/// the #939 breakpoint gate fires.
fn cacheable_system() -> String {
    "You are a careful, senior software engineer who writes maintainable code. ".repeat(400)
}

#[test]
fn cache_breakpoint_injected_on_unanchored_system_when_opt_in() {
    // #939: opt-in on AND the client set no cache_control of its own → exactly
    // one ephemeral breakpoint lands on `system`, wrapping the verbatim text.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    // Stated, not inherited: like its siblings this test is about cache mode.
    let _mode = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_PROXY_MODE", "cache");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_BREAKPOINT");
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": cacheable_system(),
        "messages": [{"role": "user", "content": "Refactor the parser."}]
    });
    let bytes = serde_json::to_vec(&body).unwrap();

    lean_ctx::core::config::Config::update_global(|c| c.proxy.cache_breakpoint = Some(true))
        .unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let v: Value = serde_json::from_slice(&out).unwrap();

    assert_eq!(
        v["system"][0]["cache_control"]["type"], "ephemeral",
        "an unanchored system prompt must receive one ephemeral breakpoint"
    );
    assert!(
        v["system"][0]["text"]
            .as_str()
            .unwrap()
            .contains("senior software engineer"),
        "the system text must be preserved verbatim under the marker"
    );
}

#[test]
fn cache_breakpoint_off_by_default_is_byte_unchanged() {
    // Default off → the request must be byte-identical (no system reshape),
    // preserving the meter-only / cache-stable contract.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    // Restored on drop, before the environment lock above is released: the
    // mode of this test is not the mode of whatever test runs next.
    let _mode = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_PROXY_MODE", "cache");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_BREAKPOINT");
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": cacheable_system(),
        "messages": [{"role": "user", "content": "Refactor the parser."}]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    assert_eq!(
        out, bytes,
        "default-off must leave the request byte-identical"
    );
}

#[test]
fn cache_breakpoint_respects_client_anchor() {
    // #939 safety: a client cache_control on a message means `system` is part
    // of the already-cached prefix — never add a second, prefix-shifting anchor.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_BREAKPOINT");
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": cacheable_system(),
        "messages": [{
            "role": "user",
            "content": [{
                "type": "text",
                "text": "hello",
                "cache_control": {"type": "ephemeral"}
            }]
        }]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    lean_ctx::core::config::Config::update_global(|c| c.proxy.cache_breakpoint = Some(true))
        .unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let v: Value = serde_json::from_slice(&out).unwrap();
    assert!(
        v["system"].is_string(),
        "with a client anchor present, system must be left untouched (no second breakpoint)"
    );
}

#[test]
fn cache_aligner_measures_without_mutating_body() {
    // #940: the volatile-field scan is telemetry-only — enabling it must leave
    // the request byte-identical (measurement, not a rewrite), even on a
    // volatile-field-rich system prompt.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    // Restored on drop, before the environment lock above is released: the
    // mode of this test is not the mode of whatever test runs next.
    let _mode = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_PROXY_MODE", "cache");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_ALIGNER");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_BREAKPOINT");
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": "Today is 2026-06-22. Session 550e8400-e29b-41d4-a716-446655440000.",
        "messages": [{"role": "user", "content": "Hello."}]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    lean_ctx::core::config::Config::update_global(|c| c.proxy.cache_aligner = Some(true)).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    assert_eq!(
        out, bytes,
        "cache-aligner telemetry must never mutate the request body"
    );
}

/// A cacheable-size system prompt that carries one volatile field (a date),
/// so the #974 relocate has something to move and clears the size floor.
fn cacheable_system_with_date() -> String {
    format!("Today is 2026-06-27. {}", cacheable_system())
}

fn clear_relocate_env() {
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_ALIGN_RELOCATE");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_BREAKPOINT");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_ALIGNER");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_OUTPUT_HOLDOUT");
}

#[test]
fn cache_align_relocate_moves_volatiles_to_tail_when_opt_in() {
    // #974: opt-in on, client anchored nothing → the date leaves the cacheable
    // prefix for an uncached tail block, and the stable block carries the one
    // ephemeral breakpoint.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    clear_relocate_env();
    // Restored on drop, before the environment lock above is released: the
    // mode of this test is not the mode of whatever test runs next.
    let _mode = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_PROXY_MODE", "cache");
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": cacheable_system_with_date(),
        "messages": [{"role": "user", "content": "Refactor the parser."}]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.cache_align_relocate = Some(true);
        c.proxy.output_holdout = Some(0.0);
    })
    .unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let v: Value = serde_json::from_slice(&out).unwrap();

    assert!(v["system"].is_array(), "system reshaped into a block array");
    assert_eq!(v["system"][0]["cache_control"]["type"], "ephemeral");
    assert!(
        !v["system"][0]["text"]
            .as_str()
            .unwrap()
            .contains("2026-06-27"),
        "the volatile date must leave the cacheable prefix"
    );
    assert!(
        v["system"][1].get("cache_control").is_none(),
        "the relocated tail block stays uncached"
    );
    assert!(
        v["system"][1]["text"]
            .as_str()
            .unwrap()
            .contains("2026-06-27"),
        "the date must be re-stated in the tail"
    );
}

#[test]
fn cache_align_relocate_off_by_default_is_byte_unchanged() {
    // Default off → byte-identical request, preserving the cache-stable
    // contract even with a volatile-rich system prompt.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    // Restored on drop, before the environment lock above is released: the
    // mode of this test is not the mode of whatever test runs next.
    let _mode = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_PROXY_MODE", "cache");
    clear_relocate_env();
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": cacheable_system_with_date(),
        "messages": [{"role": "user", "content": "Refactor the parser."}]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    assert_eq!(
        out, bytes,
        "default-off must leave the request byte-identical"
    );
}

#[test]
fn cache_align_relocate_skips_control_arm() {
    // #895 holdout: a control-arm conversation must be byte-unchanged so its
    // cache behaviour is the measurement baseline.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    clear_relocate_env();
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": cacheable_system_with_date(),
        "messages": [{"role": "user", "content": "Refactor the parser."}]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.cache_align_relocate = Some(true);
        c.proxy.output_holdout = Some(1.0);
    })
    .unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let v: Value = serde_json::from_slice(&out).unwrap();
    assert!(
        v["system"].is_string(),
        "control arm must not be relocated (measurement baseline)"
    );
}

#[test]
fn cache_align_relocate_respects_client_anchor() {
    // Safety: a client cache_control means `system` is part of the cached
    // prefix — never relocate it (that would shift the cached prefix, #448).
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    clear_relocate_env();
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": cacheable_system_with_date(),
        "messages": [{
            "role": "user",
            "content": [{
                "type": "text",
                "text": "hello",
                "cache_control": {"type": "ephemeral"}
            }]
        }]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.cache_align_relocate = Some(true);
        c.proxy.output_holdout = Some(0.0);
    })
    .unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let v: Value = serde_json::from_slice(&out).unwrap();
    assert!(
        v["system"].is_string(),
        "with a client anchor present, system must be left untouched"
    );
}

#[test]
fn cache_align_relocate_composes_with_breakpoint_to_one_anchor() {
    // Both opt-ins on: relocate adds the breakpoint to the stable block, so the
    // #939 injection sees an anchored prefix and stays a no-op — exactly one
    // breakpoint, on the stable block, with the volatile tail uncached.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    clear_relocate_env();
    // Restored on drop, before the environment lock above is released: the
    // mode of this test is not the mode of whatever test runs next.
    let _mode = lean_ctx::test_env::EnvVarGuard::set("LEAN_CTX_PROXY_MODE", "cache");
    let body = serde_json::json!({
        "model": "claude-opus-4-8",
        "system": cacheable_system_with_date(),
        "messages": [{"role": "user", "content": "Refactor the parser."}]
    });
    let bytes = serde_json::to_vec(&body).unwrap();
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.cache_align_relocate = Some(true);
        c.proxy.cache_breakpoint = Some(true);
        c.proxy.output_holdout = Some(0.0);
    })
    .unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    let v: Value = serde_json::from_slice(&out).unwrap();
    let blocks = v["system"].as_array().expect("system is a block array");
    assert_eq!(blocks.len(), 2, "stable block + volatile tail");
    assert_eq!(blocks[0]["cache_control"]["type"], "ephemeral");
    assert!(
        blocks[1].get("cache_control").is_none(),
        "no second breakpoint — the tail stays uncached"
    );
}

#[test]
fn copilot_detected_by_editor_version_header() {
    let req = Request::builder()
        .uri("/v1/messages")
        .header("editor-version", "vscode/1.0")
        .header("content-type", "application/json")
        .body(Body::empty())
        .unwrap();
    assert!(super::is_copilot_request(&req, "https://api.openai.com"));
}

#[test]
fn copilot_detected_by_integration_id_header() {
    let req = Request::builder()
        .uri("/v1/messages")
        .header("copilot-integration-id", "vscode-chat")
        .body(Body::empty())
        .unwrap();
    assert!(super::is_copilot_request(&req, "https://api.openai.com"));
}

#[test]
fn copilot_detected_by_ghu_token() {
    let req = Request::builder()
        .uri("/v1/messages")
        .header("authorization", "Bearer ghu_abc123")
        .body(Body::empty())
        .unwrap();
    assert!(super::is_copilot_request(&req, "https://api.openai.com"));
}

#[test]
fn copilot_detected_by_upstream_host() {
    let req = Request::builder()
        .uri("/v1/messages")
        .body(Body::empty())
        .unwrap();
    assert!(super::is_copilot_request(
        &req,
        "https://api.githubcopilot.com"
    ));
}

#[test]
fn not_copilot_when_standard_anthropic() {
    let req = Request::builder()
        .uri("/v1/messages")
        .header("x-api-key", "sk-ant-abc123")
        .header("anthropic-version", "2023-06-01")
        .body(Body::empty())
        .unwrap();
    assert!(!super::is_copilot_request(&req, "https://api.openai.com"));
}

#[test]
fn extract_proxy_ep_from_token() {
    assert_eq!(
        super::extract_proxy_ep("tid=abc;exp=123;proxy-ep=api.business.githubcopilot.com"),
        Some("api.business.githubcopilot.com")
    );
    assert_eq!(super::extract_proxy_ep("ghu_abc123"), None);
    assert_eq!(super::extract_proxy_ep(""), None);
}

#[test]
fn copilot_upstream_uses_proxy_ep() {
    let req = Request::builder()
        .uri("/v1/messages")
        .header(
            "authorization",
            "Bearer tid=x;exp=9;proxy-ep=api.business.githubcopilot.com",
        )
        .body(Body::empty())
        .unwrap();
    let upstream = super::resolve_copilot_upstream(&req, "https://api.githubcopilot.com");
    assert_eq!(upstream, "https://api.business.githubcopilot.com");
}

#[test]
fn copilot_upstream_falls_back_to_openai_upstream() {
    let req = Request::builder()
        .uri("/v1/messages")
        .header("authorization", "Bearer ghu_simple_token")
        .body(Body::empty())
        .unwrap();
    let upstream = super::resolve_copilot_upstream(&req, "https://api.githubcopilot.com");
    assert_eq!(upstream, "https://api.githubcopilot.com");
}

/// A caller header must not choose where an admitted body goes: an endpoint
/// that is not a GitHub Copilot host is ignored.
#[test]
fn copilot_upstream_ignores_a_caller_chosen_foreign_endpoint() {
    for endpoint in [
        "collector.example",
        "githubcopilot.com.collector.example",
        "api.githubcopilot.com@collector.example",
        "api.githubcopilot.com:8443",
        "api.githubcopilot.com/redirect",
    ] {
        let req = Request::builder()
            .uri("/v1/messages")
            .header(
                "authorization",
                format!("Bearer tid=x;exp=9;proxy-ep={endpoint}"),
            )
            .body(Body::empty())
            .unwrap();
        assert_eq!(
            super::resolve_copilot_upstream(&req, "https://api.githubcopilot.com"),
            "https://api.githubcopilot.com",
            "{endpoint}"
        );
    }
}

#[test]
fn is_copilot_host_detects_variants() {
    assert!(super::is_copilot_host("https://api.githubcopilot.com"));
    assert!(super::is_copilot_host(
        "https://api.business.githubcopilot.com"
    ));
    assert!(super::is_copilot_host(
        "https://api.individual.githubcopilot.com"
    ));
    assert!(!super::is_copilot_host("https://api.anthropic.com"));
    assert!(!super::is_copilot_host("https://api.openai.com"));
}

/// A warm conversation whose whole message history is client-cached: the
/// opening turn (unique `first_text` → unique conversation key), `turns` prior
/// exchanges, and a closing user turn carrying the cache breakpoint.
fn warm_body(first_text: &str, system: &str, turns: usize, filler: &str) -> Value {
    let mut messages = vec![serde_json::json!({"role": "user", "content": first_text})];
    for i in 0..turns {
        messages.push(serde_json::json!({"role": "assistant", "content": format!("done {i}")}));
        messages.push(serde_json::json!({"role": "user", "content": filler}));
    }
    messages.push(serde_json::json!({"role": "user", "content": [
        {"type": "text", "text": "continue", "cache_control": {"type": "ephemeral"}}
    ]}));
    serde_json::json!({"model": "claude-opus-4-5", "system": system, "messages": messages})
}

fn warm_gate_config(cache_policy: bool) {
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_CACHE_POLICY");
    lean_ctx::test_env::remove_var("LEAN_CTX_PROXY_COLD_PREFIX_REPACK");
    lean_ctx::core::config::Config::update_global(|c| {
        c.proxy.role_aggressiveness.system = Some(0.9);
        c.proxy.cold_prefix_repack = Some(false);
        c.proxy.cache_policy = Some(cache_policy);
    })
    .unwrap();
}

fn system_after(body: Value) -> String {
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, _o, _c) = compress_request_body(body, bytes.len());
    serde_json::from_slice::<Value>(&out).unwrap()["system"]
        .as_str()
        .unwrap()
        .to_owned()
}

#[test]
fn warm_system_gate_preserves_when_the_bust_does_not_pay() {
    // #1912: one prior turn in front of a huge cached tail — rewriting the
    // system block would re-write the whole prefix for a tiny per-turn saving.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    warm_gate_config(true);
    let prose = big_prose().repeat(8);
    let huge_tail = "lorem ipsum dolor sit amet consectetur ".repeat(4000);
    let body = warm_body("warm-gate-preserve-session", &prose, 1, &huge_tail);
    assert_eq!(
        system_after(body),
        prose,
        "Preserve must keep the prefix verbatim"
    );
}

#[test]
fn warm_system_gate_mutates_long_sessions_and_latches() {
    // #1912: a long session repays the one-off bust, so the gate compresses the
    // system prompt — and the per-conversation latch keeps every later turn on
    // that same compressed prefix, even a turn the gate alone would preserve.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    warm_gate_config(true);
    let prose = big_prose().repeat(8);
    let first = "warm-gate-latch-session";

    let compressed = system_after(warm_body(first, &prose, 200, "next"));
    assert!(
        compressed.len() < prose.len(),
        "a paying rewrite must compress"
    );
    assert_eq!(
        system_after(warm_body(first, &prose, 200, "next")),
        compressed,
        "a replayed turn must produce the identical prefix"
    );

    let huge_tail = "lorem ipsum dolor sit amet consectetur ".repeat(4000);
    assert_eq!(
        system_after(warm_body(first, &prose, 1, &huge_tail)),
        compressed,
        "once latched, the conversation must never flip back to the verbatim prefix"
    );
}

#[test]
fn warm_system_gate_needs_cache_economics() {
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    warm_gate_config(false);
    let prose = big_prose().repeat(8);
    let body = warm_body("warm-gate-policy-off-session", &prose, 200, "next");
    assert_eq!(
        system_after(body),
        prose,
        "without cache economics a cached prefix is never rewritten (#448)"
    );
}

/// A Claude Code request with MCP tool search on (the default behind a gateway
/// since Claude Code v2.1.304): deferred tool definitions carry `defer_loading`,
/// and a `ToolSearch` result returns `tool_reference` blocks. Long enough that
/// history pruning and live compression both rewrite the body.
fn tool_search_body() -> Value {
    let mut messages = vec![
        serde_json::json!({"role": "user", "content": "find the issue tracker tools"}),
        serde_json::json!({"role": "assistant", "content": [
            {"type": "tool_use", "id": "ts1", "name": "ToolSearch", "input": {"query": "issues"}}
        ]}),
        serde_json::json!({"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": "ts1", "content": [
                {"type": "tool_reference", "tool_name": "mcp__tracker__list_issues"},
                {"type": "tool_reference", "tool_name": "mcp__tracker__get_issue"}
            ]}
        ]}),
    ];
    for i in 0..30 {
        let id = format!("b{i}");
        messages.push(serde_json::json!({"role": "assistant", "content": [
            {"type": "tool_use", "id": id, "name": "Bash", "input": {"command": "cargo test"}}
        ]}));
        messages.push(serde_json::json!({"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": id, "content": big_log()}
        ]}));
    }
    serde_json::json!({
        "model": "claude-opus-5-5",
        "tools": [
            {"name": "Bash", "description": "Run a shell command.", "input_schema": {"type": "object"}},
            {"name": "ToolSearch", "description": "Search deferred tools.", "input_schema": {"type": "object"}},
            {"name": "mcp__tracker__list_issues", "description": "List issues.",
             "input_schema": {"type": "object"}, "defer_loading": true},
            {"name": "mcp__tracker__get_issue", "description": "Get one issue.",
             "input_schema": {"type": "object"}, "defer_loading": true,
             "cache_control": {"type": "ephemeral"}}
        ],
        "messages": messages
    })
}

#[test]
fn tool_search_fields_survive_rewrites() {
    // Claude Code expects a gateway to forward `defer_loading` and
    // `tool_reference` unchanged; dropping either fails the request with a 400.
    let _iso = lean_ctx::core::data_dir::isolated_data_dir();
    let body = tool_search_body();
    let bytes = serde_json::to_vec(&body).unwrap();
    let (out, orig, comp) = compress_request_body(body.clone(), bytes.len());
    assert!(comp < orig, "the fixture must exercise a real rewrite");
    let parsed: Value = serde_json::from_slice(&out).unwrap();

    let sent = parsed["tools"].as_array().unwrap();
    for tool in body["tools"].as_array().unwrap() {
        assert!(
            sent.contains(tool),
            "tool definition must be forwarded verbatim: {tool}"
        );
    }
    assert_eq!(
        parsed["messages"][2], body["messages"][2],
        "tool_reference blocks must reach the provider unchanged"
    );
}