velesdb-memory 0.14.1

VelesDB-memory: local-first MCP memory server for AI agents (remember/recall/relate/forget/why + deterministic context compiler).
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
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
//! BDD integration tests for the deterministic context compiler core
//! (`velesdb_memory::context`, US-001 of EPIC-P-070).
//!
//! Categories: Nominal (≥60%), Edge (~20%), Negative (≥20%).
//!
//! The compiler under test is *memoryless*: pure fragments in, compiled
//! context out. Memory-backed selection, events, and handles round-trips are
//! covered by `context_memory_bdd.rs` (US-002).

#![cfg(feature = "context")]

use serde_json::{Map, Value};
use velesdb_memory::context::{
    segment_transcript, CompilePolicy, CompileRequest, CompiledContext, ContextAction,
    ContextCompiler, ContextFragment, FidelityRisk, HeuristicEstimator, SegmentationPolicy,
    TokenEstimator,
};
use velesdb_memory::{ErrorCategory, MemoryError};

/// Build a plain fragment with no id, kind, priority, or metadata.
fn fragment(content: &str) -> ContextFragment {
    ContextFragment {
        path: None,
        id: None,
        content: content.to_owned(),
        kind: None,
        priority: None,
        metadata: None,
        media: None,
    }
}

/// Build a fragment carrying caller metadata.
fn fragment_with_meta(content: &str, pairs: &[(&str, Value)]) -> ContextFragment {
    let mut meta = Map::new();
    for (key, value) in pairs {
        meta.insert((*key).to_owned(), value.clone());
    }
    ContextFragment {
        metadata: Some(meta),
        ..fragment(content)
    }
}

/// Build a request over `fragments` with the given token budget and the
/// default policy.
fn request(fragments: Vec<ContextFragment>, token_budget: u64) -> CompileRequest {
    CompileRequest {
        query: "what changed in the deploy pipeline".to_owned(),
        fragments,
        project: None,
        target_model: None,
        token_budget,
        memory_scope: None,
        policy: None,
    }
}

/// Compile with the default compiler (default policy, heuristic estimator,
/// no pricing).
fn compile(req: &CompileRequest) -> CompiledContext {
    ContextCompiler::new(CompilePolicy::default())
        .compile(req)
        .expect("compile")
}

/// The decision recorded for the fragment whose content is `content`.
fn decision_for<'a>(
    out: &'a CompiledContext,
    content: &str,
) -> &'a velesdb_memory::context::ContextDecision {
    let id = velesdb_memory::context::fragment_id(content);
    out.decisions
        .iter()
        .find(|d| d.fragment_id == id)
        .expect("a decision must be recorded for every fragment")
}

// --- Nominal -----------------------------------------------------------------

#[test]
fn test_compile_same_input_twice_produces_identical_output() {
    // Given a mixed corpus of prose, code, and duplicated fragments
    let fragments = vec![
        fragment("The deploy pipeline runs clippy before tests."),
        fragment("fn main() {\n    println!(\"hello\");\n}"),
        fragment("The deploy pipeline runs clippy before tests."),
        fragment("Contact the on-call engineer at https://oncall.example.com/veles."),
    ];
    let req = request(fragments, 10_000);

    // When compiling the same request twice
    let first = compile(&req);
    let second = compile(&req);

    // Then the outputs are identical byte for byte, decisions included
    let first_json = serde_json::to_string(&first).expect("serialize first");
    let second_json = serde_json::to_string(&second).expect("serialize second");
    assert_eq!(
        first_json, second_json,
        "the compiler must be fully deterministic"
    );
}

#[test]
fn test_compile_output_never_exceeds_token_budget() {
    // Given corpora of growing size and a range of budgets
    let estimator = HeuristicEstimator;
    for budget in [64_u64, 128, 256, 1_024] {
        let fragments: Vec<ContextFragment> = (0..40)
            .map(|i| {
                fragment(&format!(
                    "Observation {i}: the ingestion worker retried the batch \
                     because the upstream connection dropped mid-transfer."
                ))
            })
            .collect();
        let req = request(fragments, budget);

        // When compiling
        let out = compile(&req);

        // Then the assembled content never exceeds the budget
        let used = estimator.estimate(&out.content);
        assert!(
            used <= budget,
            "budget {budget} exceeded: assembled content estimates to {used} tokens"
        );
    }
}

#[test]
fn test_compile_preserves_code_blocks_verbatim() {
    // Given a fenced code block among prose
    let code = "```rust\nlet x = compute(41) + 1;\nassert_eq!(x, 42);\n```";
    let req = request(vec![fragment("Some prose."), fragment(code)], 10_000);

    // When compiling with a generous budget
    let out = compile(&req);

    // Then the code block is preserved verbatim and the decision says why
    assert!(
        out.content.contains(code),
        "code must survive verbatim, got:\n{}",
        out.content
    );
    let decision = decision_for(&out, code);
    assert!(matches!(decision.action, ContextAction::Preserve));
    assert_eq!(decision.rule_id, "preserve.code_fence");
}

#[test]
fn test_compile_preserves_numbers_dates_ids_verbatim() {
    // Given a fragment dense with exact values
    let facts = "Order 8f3a-11 shipped 2026-07-14 with 1_048_576 bytes for 42.50 EUR.";
    let req = request(vec![fragment(facts)], 10_000);

    // When compiling
    let out = compile(&req);

    // Then the exact values survive verbatim
    assert!(out.content.contains(facts));
    let decision = decision_for(&out, facts);
    assert!(matches!(decision.action, ContextAction::Preserve));
    assert_eq!(decision.rule_id, "preserve.exact_values");
}

#[test]
fn test_compile_preserves_urls_verbatim() {
    // Given a fragment carrying a URL
    let with_url = "Runbook lives at https://wiki.example.com/velesdb/runbook#deploy.";
    let req = request(vec![fragment(with_url)], 10_000);

    // When compiling
    let out = compile(&req);

    // Then the URL survives verbatim
    assert!(out
        .content
        .contains("https://wiki.example.com/velesdb/runbook#deploy"));
    let decision = decision_for(&out, with_url);
    assert!(matches!(decision.action, ContextAction::Preserve));
}

#[test]
fn test_compile_preserves_negative_constraints_verbatim() {
    // Given a negative constraint an agent must never lose
    let constraint = "Never restart the primary node during a rebalance.";
    let req = request(
        vec![fragment("Filler prose."), fragment(constraint)],
        10_000,
    );

    // When compiling
    let out = compile(&req);

    // Then the constraint is preserved verbatim with the dedicated rule
    assert!(out.content.contains(constraint));
    let decision = decision_for(&out, constraint);
    assert!(matches!(decision.action, ContextAction::Preserve));
    assert_eq!(decision.rule_id, "preserve.negative_constraint");
}

#[test]
fn test_compile_preserves_fragment_marked_verbatim() {
    // Given a plain prose fragment explicitly marked verbatim by the caller
    let marked = "Plain prose the caller insists on keeping word for word.";
    let req = request(
        vec![fragment_with_meta(
            marked,
            &[("verbatim", Value::Bool(true))],
        )],
        10_000,
    );

    // When compiling
    let out = compile(&req);

    // Then the mark wins over any other classification
    let decision = decision_for(&out, marked);
    assert!(matches!(decision.action, ContextAction::Preserve));
    assert_eq!(decision.rule_id, "preserve.marked_verbatim");
}

#[test]
fn test_compile_drops_exact_duplicates() {
    // Given the same fragment supplied twice
    let dup = "The cache invalidation job runs hourly.";
    let req = request(vec![fragment(dup), fragment(dup)], 10_000);

    // When compiling
    let out = compile(&req);

    // Then the content carries it once and one decision is a duplicate drop
    let occurrences = out.content.matches(dup).count();
    assert_eq!(
        occurrences, 1,
        "an exact duplicate must appear exactly once"
    );
    let drops: Vec<_> = out
        .decisions
        .iter()
        .filter(|d| matches!(d.action, ContextAction::Drop) && d.rule_id == "drop.duplicate")
        .collect();
    assert_eq!(drops.len(), 1, "exactly one duplicate drop expected");
}

#[test]
fn test_compile_merges_near_duplicates_keeps_one() {
    // Given two fragments identical up to case and spacing
    let original = "The server restarts at 05:00 UTC.";
    let near = "the  SERVER   restarts at 05:00 utc.";
    let req = request(vec![fragment(original), fragment(near)], 10_000);

    // When compiling
    let out = compile(&req);

    // Then only one survives and the other is dropped as a near-duplicate
    let drops: Vec<_> = out
        .decisions
        .iter()
        .filter(|d| matches!(d.action, ContextAction::Drop) && d.rule_id == "drop.near_duplicate")
        .collect();
    assert_eq!(drops.len(), 1, "exactly one near-duplicate drop expected");
    assert!(
        out.content.contains(original) != out.content.contains(near),
        "exactly one of the two variants must survive"
    );
}

#[test]
fn test_compile_abstracts_repeated_log_lines_with_count() {
    // Given a log fragment where one line repeats many times
    let mut lines = vec!["ERROR timeout connecting to shard-3"; 50];
    lines.push("INFO shard-3 recovered");
    let log = lines.join("\n");
    let req = request(
        vec![ContextFragment {
            kind: Some("log".to_owned()),
            ..fragment(&log)
        }],
        10_000,
    );

    // When compiling
    let out = compile(&req);

    // Then the repeated line is collapsed with an explicit count
    let decision = decision_for(&out, &log);
    assert!(matches!(decision.action, ContextAction::Abstract));
    assert_eq!(decision.rule_id, "abstract.log_dedup");
    assert!(
        out.content.contains("(x50)"),
        "the collapse must be annotated with its count, got:\n{}",
        out.content
    );
    assert_eq!(
        out.content
            .matches("ERROR timeout connecting to shard-3")
            .count(),
        1,
        "the repeated line must appear exactly once"
    );
    assert!(out.insights.tokens_saved > 0);
}

/// A real repetitive log where every line differs only by an ISO timestamp
/// (a shape `abstract.log_dedup`'s byte-exact grouping cannot collapse on
/// its own — see the golden test right after this one).
fn timestamped_log() -> String {
    [
        "2026-07-18T10:23:45.001Z INFO canary check passed for shard-1",
        "2026-07-18T10:23:45.501Z INFO canary check passed for shard-1",
        "2026-07-18T10:23:46.002Z INFO canary check passed for shard-1",
        "2026-07-18T10:23:46.502Z WARN retrying upstream connection",
    ]
    .join("\n")
}

#[test]
fn test_compile_timestamped_log_lines_do_not_collapse_by_default() {
    // Given a timestamped log and the default policy (normalize off) —
    // golden: this is the pre-existing, unchanged behavior. Byte-exact
    // `abstract.log_dedup` never even recognizes this fragment as
    // repetitive (every line differs by its timestamp), so it falls
    // through — here to `preserve.exact_values`, since the timestamps
    // themselves are digit-dense — exactly the documented limitation the
    // `velesdb-context-optimizer` skill's "Timestamped logs" bullet warns
    // about.
    let log = timestamped_log();
    let req = request(
        vec![ContextFragment {
            kind: Some("log".to_owned()),
            ..fragment(&log)
        }],
        10_000,
    );

    // When compiling
    let out = compile(&req);

    // Then all three timestamp variants of the repeated line survive
    // distinctly — nothing collapsed, no normalization mentioned
    let decision = decision_for(&out, &log);
    assert_ne!(
        decision.rule_id, "abstract.log_dedup",
        "byte-exact log_dedup must not recognize timestamp-only variants as repeats"
    );
    assert!(
        !decision.reason.contains("normalized"),
        "reason must not mention normalization when the policy is off, got: {}",
        decision.reason
    );
    assert_eq!(
        out.content
            .matches("INFO canary check passed for shard-1")
            .count(),
        3,
        "without normalize_log_timestamps, the three timestamp variants stay distinct:\n{}",
        out.content
    );
}

#[test]
fn test_compile_normalize_log_timestamps_collapses_timestamped_duplicates() {
    // Given the same timestamped log and normalize_log_timestamps enabled
    let log = timestamped_log();
    let mut req = request(
        vec![ContextFragment {
            kind: Some("log".to_owned()),
            ..fragment(&log)
        }],
        10_000,
    );
    req.policy = Some(CompilePolicy {
        normalize_log_timestamps: true,
        ..CompilePolicy::default()
    });

    // When compiling
    let out = compile(&req);

    // Then the three timestamp variants collapse into one annotated line,
    // and the decision reason ventilates the normalization
    let decision = decision_for(&out, &log);
    assert_eq!(decision.rule_id, "abstract.log_dedup");
    assert!(
        decision.reason.contains("normalized"),
        "reason must mention normalization once it changed the grouping, got: {}",
        decision.reason
    );
    assert_eq!(
        out.content
            .matches("INFO canary check passed for shard-1")
            .count(),
        1,
        "with normalize_log_timestamps, the three variants collapse to one line:\n{}",
        out.content
    );
    assert!(
        out.content.contains("(x3)"),
        "the collapsed line must be annotated with its count, got:\n{}",
        out.content
    );
}

#[test]
fn test_compile_places_cache_marked_fragments_first() {
    // Given a stable system-prompt-like fragment marked cacheable, listed last
    let stable = "You are the deploy assistant for the veles cluster.";
    let volatile = "Today the queue depth spiked to 900.";
    let req = request(
        vec![
            fragment(volatile),
            fragment_with_meta(stable, &[("cache", Value::Bool(true))]),
        ],
        10_000,
    );

    // When compiling
    let out = compile(&req);

    // Then the cache-marked fragment leads the assembled content
    let stable_at = out.content.find(stable).expect("stable fragment present");
    let volatile_at = out
        .content
        .find(volatile)
        .expect("volatile fragment present");
    assert!(
        stable_at < volatile_at,
        "cache-marked content must form a stable prefix"
    );
    let decision = decision_for(&out, stable);
    assert!(matches!(decision.action, ContextAction::Cache));
}

#[test]
fn test_compile_without_pricing_reports_tokens_only() {
    // Given a compiler with no pricing table configured
    let req = request(vec![fragment("a"), fragment("a")], 10_000);

    // When compiling
    let out = compile(&req);

    // Then token insights are reported and cost stays absent
    assert!(out.insights.tokens_in > 0);
    assert!(out.insights.estimated_cost_saved_micros.is_none());
    assert!(out.insights.currency.is_none());
}

#[test]
fn test_compile_records_a_decision_and_source_for_every_fragment() {
    // Given a corpus with a duplicate and an oversized budget
    let fragments = vec![
        fragment("alpha fact"),
        fragment("beta fact"),
        fragment("alpha fact"),
    ];
    let req = request(fragments, 10_000);

    // When compiling
    let out = compile(&req);

    // Then provenance covers every input fragment (dedup included)
    assert_eq!(out.decisions.len(), 3, "one decision per input fragment");
    assert_eq!(out.sources.len(), 2, "one source per distinct fragment");
    for decision in &out.decisions {
        assert!(
            !decision.reason.is_empty(),
            "reasons must be human-readable"
        );
        assert!(!decision.rule_id.is_empty());
    }
    for source in &out.sources {
        assert!(
            source.handle.starts_with("ctx://source/"),
            "sources must be addressable, got {}",
            source.handle
        );
    }
}

#[test]
fn test_compile_golden_snapshot_matches_committed_output() {
    // Given a fixed, representative request (code + prose + dup + cache +
    // log + constraint) — the serialized output is committed under
    // tests/golden/context/ and any change to it must be a conscious one
    let fragments = vec![
        fragment_with_meta(
            "You are the deploy assistant.",
            &[("cache", Value::Bool(true))],
        ),
        fragment("The deploy pipeline runs clippy before tests."),
        fragment("The deploy pipeline runs clippy before tests."),
        fragment("```rust\nlet x = 42;\n```"),
        fragment("Never restart the primary node during a rebalance."),
        ContextFragment {
            kind: Some("log".to_owned()),
            ..fragment("ERROR timeout\nERROR timeout\nINFO recovered")
        },
    ];
    let req = request(fragments, 10_000);

    // When compiling
    let out = compile(&req);

    // Then the output matches the committed golden snapshot exactly
    let actual = serde_json::to_value(&out).expect("serialize output");
    let golden: Value = serde_json::from_str(include_str!("golden/context/compile_basic.json"))
        .expect("parse committed golden snapshot");
    assert_eq!(
        actual,
        golden,
        "compiled output drifted from the golden snapshot; if intentional, \
         re-generate tests/golden/context/compile_basic.json — actual:\n{}",
        serde_json::to_string_pretty(&actual).expect("pretty-print actual")
    );
}

#[test]
fn test_compile_transcript_golden_snapshot_matches_committed_output() {
    // Given a fixed, representative transcript (system + user + assistant
    // turns, a fenced code block, a repeated-line log run) — segmented, then
    // compiled exactly like `compile_context` would with the resulting
    // fragments. Committed under tests/golden/context/; any change to it
    // must be a conscious one (V2b-2 non-regression).
    let transcript = "System: You are the deploy assistant.\n\
User: what changed in the deploy pipeline?\n\
```rust\nlet x = 42;\n```\n\
Assistant: Never restart the primary node during a rebalance.\n\
ERROR timeout\nERROR timeout\nERROR timeout\nERROR timeout\n\
ERROR timeout\nERROR timeout\nERROR timeout\nERROR timeout\n";
    let outcome = segment_transcript(transcript, &SegmentationPolicy::default())
        .expect("a well-formed transcript segments cleanly");
    let fragments: Vec<ContextFragment> = outcome
        .segments
        .into_iter()
        .map(|segment| segment.fragment)
        .collect();
    let req = request(fragments, 10_000);

    // When compiling the segmented fragments
    let out = compile(&req);

    // Then the output matches the committed golden snapshot exactly
    let actual = serde_json::to_value(&out).expect("serialize output");
    let golden: Value = serde_json::from_str(include_str!("golden/context/transcript_basic.json"))
        .expect("parse committed golden snapshot");
    assert_eq!(
        actual,
        golden,
        "compiled transcript output drifted from the golden snapshot; if intentional, \
         re-generate tests/golden/context/transcript_basic.json — actual:\n{}",
        serde_json::to_string_pretty(&actual).expect("pretty-print actual")
    );
}

#[test]
fn test_compile_overlap_policy_never_duplicates_content() {
    // Given a caller policy asking for chunk overlap and a fragment that
    // must be split into several chunks
    let sentence = "The migration copies one shard at a time and verifies checksums. ";
    let long = sentence.repeat(50);
    let policy = CompilePolicy {
        chunk: velesdb_memory::context::ChunkPolicy {
            max_chunk_bytes: 200,
            overlap_bytes: 64,
            boundary: velesdb_memory::context::ChunkBoundary::Fixed,
        },
        ..CompilePolicy::default()
    };
    let mut req = request(vec![fragment(&long)], 100_000);
    req.policy = Some(policy);

    // When compiling with a budget generous enough to take everything
    let out = compile(&req);

    // Then the emitted content reconstructs the original without repeating
    // any overlap seam (verbatim means verbatim)
    assert!(
        out.content.contains(&long),
        "the full original must be emitted exactly once, unduplicated"
    );
    assert!(out.insights.tokens_out <= out.insights.tokens_in);
}

#[test]
fn test_compile_budget_holds_with_estimator_counting_joiners_higher() {
    // Given an injected estimator that prices every char as one token, so
    // the "\n\n" joiner costs 2 tokens instead of the default estimator's 1
    struct CharEstimator;
    impl TokenEstimator for CharEstimator {
        fn estimate(&self, text: &str) -> u64 {
            u64::try_from(text.chars().count()).unwrap_or(u64::MAX)
        }
    }
    let fragments: Vec<ContextFragment> = (0..30)
        .map(|i| fragment(&format!("note {i} about the deploy")))
        .collect();
    let budget = 120_u64;
    let req = request(fragments, budget);

    // When compiling with that estimator
    let out = ContextCompiler::new(CompilePolicy::default())
        .with_estimator(Box::new(CharEstimator))
        .compile(&req)
        .expect("compile");

    // Then the budget invariant holds under the injected estimator too
    assert!(
        CharEstimator.estimate(&out.content) <= budget,
        "joiner accounting must use the injected estimator, not a constant"
    );
}

#[test]
fn test_compile_same_caller_id_different_content_keeps_handles_unambiguous() {
    // Given two fragments sharing a caller id but carrying different bytes
    let a = ContextFragment {
        id: Some(42),
        ..fragment("the secrets rotation policy")
    };
    let b = ContextFragment {
        id: Some(42),
        ..fragment("an unrelated ingestion log line")
    };
    let req = request(vec![a, b], 10_000);

    // When compiling
    let out = compile(&req);

    // Then each source stays addressable by its own content, not the id
    assert_eq!(out.sources.len(), 2);
    assert_ne!(
        out.sources[0].handle, out.sources[1].handle,
        "handles must be content-addressed so a caller-id collision cannot alias two sources"
    );
}

#[test]
fn test_compile_duplicate_of_externalized_fragment_reports_elevated_risk() {
    // Given a corpus where the kept twin cannot fit the budget but its
    // duplicate arrives later
    let big = "x".repeat(4_000);
    let filler = "the deploy pipeline note ".repeat(20);
    let req = request(
        vec![
            ContextFragment {
                priority: Some(0),
                ..fragment(&big)
            },
            ContextFragment {
                priority: Some(9),
                ..fragment(&filler)
            },
            fragment(&big),
        ],
        220,
    );

    // When compiling under a budget that externalizes the big twin
    let out = compile(&req);

    // Then the duplicate's decision must not claim its content survived
    let dup = out
        .decisions
        .iter()
        .find(|d| matches!(d.action, ContextAction::Drop))
        .expect("the second big fragment is an exact duplicate");
    assert!(
        !matches!(dup.risk, FidelityRisk::Low),
        "a duplicate of an unpacked twin cannot be risk-free"
    );
    assert!(
        dup.handle.is_some(),
        "the duplicate must stay machine-addressable through a handle"
    );
}

#[test]
fn test_compile_critical_duplicate_of_partially_emitted_twin_reports_high_risk() {
    // Given a critical (verbatim-marked) exact duplicate whose surviving
    // twin itself only partially fits the budget
    let big = "x".repeat(4_000);
    let req = request(
        vec![
            fragment(&big),
            fragment_with_meta(&big, &[("verbatim", Value::Bool(true))]),
        ],
        300,
    );

    // When compiling under a budget too small to fully emit the twin
    let out = compile(&req);

    // Then the critical duplicate's decision is High risk specifically —
    // not merely "not Low" — its own bytes are provably absent from the
    // output and it demands verbatim survival
    let dup = out
        .decisions
        .iter()
        .find(|d| matches!(d.action, ContextAction::Drop))
        .expect("the verbatim-marked copy is an exact duplicate of the first");
    assert!(
        matches!(dup.risk, FidelityRisk::High),
        "a critical duplicate of a not-fully-emitted twin must be High risk, got {:?}",
        dup.risk
    );
}

#[test]
fn test_compile_near_dup_dedup_can_be_disabled_via_policy() {
    // Given two near-duplicate (not byte-identical) fragments and a policy
    // that disables near-duplicate detection
    let policy = CompilePolicy {
        near_dup_dedup: false,
        ..CompilePolicy::default()
    };
    let mut req = request(
        vec![
            fragment("The server restarts nightly."),
            fragment("the  server   restarts  nightly."),
        ],
        10_000,
    );
    req.policy = Some(policy);

    // When compiling
    let out = compile(&req);

    // Then neither fragment is dropped as a near-duplicate — both are
    // independently classified and packed
    assert!(
        out.decisions
            .iter()
            .all(|d| d.action != ContextAction::Drop),
        "near-dup detection was disabled, nothing should be dropped as a duplicate"
    );
    assert_eq!(out.decisions.len(), 2);
}

#[test]
fn test_compile_critical_near_duplicate_is_not_dropped() {
    // Given a verbatim-marked fragment that near-duplicates a lossy log twin
    let log_twin = ContextFragment {
        kind: Some("log".to_owned()),
        ..fragment("ERROR shard timeout\nERROR shard timeout")
    };
    let marked = fragment_with_meta(
        "error shard  timeout\nerror shard  timeout",
        &[("verbatim", Value::Bool(true))],
    );
    let req = request(vec![log_twin, marked], 10_000);

    // When compiling
    let out = compile(&req);

    // Then the critical fragment is never sacrificed to near-deduplication
    let marked_decision = decision_for(&out, "error shard  timeout\nerror shard  timeout");
    assert!(
        !matches!(marked_decision.action, ContextAction::Drop),
        "a critical fragment must not be near-dup-dropped, got rule {}",
        marked_decision.rule_id
    );
}

#[test]
fn test_compile_partial_preserve_savings_are_attributed_by_rule() {
    // Given a single long prose fragment that only partially fits
    let sentence = "The migration copies one shard at a time and verifies checksums. ";
    let long = sentence.repeat(100);
    let req = request(vec![fragment(&long)], 300);

    // When compiling
    let out = compile(&req);

    // Then the partial savings are attributed to the deciding rule and the
    // by-rule map reconciles with the total (single fragment ⇒ no joiners)
    assert!(out.insights.tokens_saved > 0);
    let by_rule: u64 = out.insights.tokens_saved_by_rule.values().sum();
    assert_eq!(
        by_rule, out.insights.tokens_saved,
        "per-rule savings must reconcile with the total"
    );
}

// --- Edge --------------------------------------------------------------------

#[test]
fn test_compile_oversized_fragment_is_chunked_not_dropped() {
    // Given one fragment far larger than the per-chunk ceiling, under a
    // budget that fits only part of it
    let paragraph = "The migration copies one shard at a time and verifies checksums. ";
    let huge = paragraph.repeat(400);
    let req = request(vec![fragment(&huge)], 512);

    // When compiling
    let out = compile(&req);

    // Then part of the fragment survives instead of an all-or-nothing drop
    assert!(
        out.content.contains(paragraph.trim_end()),
        "at least one chunk of the oversized fragment must be packed"
    );
    let estimator = HeuristicEstimator;
    assert!(estimator.estimate(&out.content) <= 512);
}

#[test]
fn test_compile_over_budget_fragments_become_retrievable_handles() {
    // Given more preserved-worthy fragments than the budget can hold
    let fragments: Vec<ContextFragment> = (0..30)
        .map(|i| {
            fragment(&format!(
                "Never delete backup volume vol-{i:04} before day 30."
            ))
        })
        .collect();
    let req = request(fragments, 128);

    // When compiling
    let out = compile(&req);

    // Then the overflow is externalized as retrievable handles, not lost
    assert!(
        !out.retrieval_handles.is_empty(),
        "over-budget fragments must surface as retrieval handles"
    );
    let retrieved: Vec<_> = out
        .decisions
        .iter()
        .filter(|d| matches!(d.action, ContextAction::Retrieve))
        .collect();
    assert_eq!(retrieved.len(), out.retrieval_handles.len());
    for handle in &out.retrieval_handles {
        assert!(handle.handle.starts_with("ctx://source/"));
    }
    // And dropping critical (negative-constraint) content raises the risk
    assert!(matches!(out.risk, FidelityRisk::High));
}

#[test]
fn test_compile_empty_fragments_yields_empty_context() {
    // Given no fragments at all
    let req = request(vec![], 1_024);

    // When compiling
    let out = compile(&req);

    // Then the result is empty but well-formed
    assert!(out.content.is_empty());
    assert!(out.decisions.is_empty());
    assert_eq!(out.insights.tokens_in, 0);
    assert_eq!(out.insights.tokens_out, 0);
    assert!(matches!(out.risk, FidelityRisk::Low));
}

#[test]
fn test_compile_empty_content_critical_fragment_is_low_risk_not_a_budget_miss() {
    // Given a critical (verbatim-marked) fragment whose content is empty —
    // there is trivially nothing to lose — under a budget large enough that
    // a real fit failure cannot be the explanation
    let empty_critical = fragment_with_meta("", &[("verbatim", Value::Bool(true))]);
    let req = request(vec![empty_critical], 10_000);

    // When compiling
    let out = compile(&req);
    let decision = decision_for(&out, "");

    // Then it is reported as fully (trivially) emitted — Low risk, no
    // "did not fit the budget" story and no retrieval handle needed for
    // content that was never going to be lost
    assert_eq!(decision.action, ContextAction::Preserve);
    assert!(matches!(decision.risk, FidelityRisk::Low));
    assert_eq!(decision.rule_id, "preserve.marked_verbatim");
    assert!(matches!(out.risk, FidelityRisk::Low));
}

#[test]
fn test_compile_empty_fragments_interleaved_never_inject_unaccounted_joiners() {
    // Given real fragments with several empty (trivially emitted) fragments
    // interleaved between them — a caller can send any number of these
    let fragments = vec![
        fragment("The deploy pipeline runs clippy before promoting a build."),
        fragment(""),
        fragment(""),
        fragment("The canary stage rolls out to five percent of the fleet first."),
        fragment(""),
        fragment("Checksums are verified on every shard before the rebalance."),
    ];
    let req = request(fragments, 10_000);

    // When compiling under a budget generous enough that everything real fits
    let out = compile(&req);

    // Then the assembled output never exceeds the budget (empty fragments must
    // not inject joiner tokens the packer never accounted for) ...
    let estimator = HeuristicEstimator;
    assert!(
        estimator.estimate(&out.content) <= req.token_budget,
        "empty fragments injected unaccounted joiners: {} tokens > {} budget",
        estimator.estimate(&out.content),
        req.token_budget
    );
    // ... and no empty fragment leaves a doubled joiner in the output
    assert!(
        !out.content.contains("\n\n\n\n"),
        "an empty block produced a doubled joiner:\n{:?}",
        out.content
    );
    // ... while the real content is all present, in order
    let clippy = out.content.find("clippy").expect("first fragment present");
    let canary = out.content.find("canary").expect("second fragment present");
    let checksums = out
        .content
        .find("Checksums")
        .expect("third fragment present");
    assert!(clippy < canary && canary < checksums, "order preserved");
}

#[test]
fn test_compile_with_pricing_reports_cost_savings_in_micros() {
    // Given a compiler carrying a versioned pricing table (3 EUR / 1M input
    // tokens for the target model) and a corpus with real savings
    let mut models = std::collections::BTreeMap::new();
    models.insert(
        "claude-sonnet-5".to_owned(),
        velesdb_memory::context::ModelPricing {
            input_micros_per_million_tokens: 3_000_000,
        },
    );
    let pricing = velesdb_memory::context::PricingTable {
        version: "2026-07".to_owned(),
        currency: "EUR".to_owned(),
        models,
    };
    let duplicated = "The deploy pipeline runs clippy before promoting any build.";
    let mut req = request(
        vec![
            fragment(duplicated),
            fragment(duplicated),
            fragment(duplicated),
        ],
        10_000,
    );
    req.target_model = Some("claude-sonnet-5".to_owned());

    // When compiling with the pricing injected
    let out = ContextCompiler::new(CompilePolicy::default())
        .with_pricing(pricing)
        .compile(&req)
        .expect("compile");

    // Then the cost figure is exactly tokens_saved × rate / 1M, in
    // micro-units, with the currency and table version traceable
    assert!(out.insights.tokens_saved > 0, "duplicates must save tokens");
    let expected_micros = out.insights.tokens_saved * 3_000_000 / 1_000_000;
    assert_eq!(
        out.insights.estimated_cost_saved_micros,
        Some(expected_micros)
    );
    assert_eq!(out.insights.currency.as_deref(), Some("EUR"));
    assert_eq!(out.insights.pricing_version.as_deref(), Some("2026-07"));
}

#[test]
fn test_compile_with_pricing_but_unpriced_model_reports_tokens_only() {
    // Given a pricing table that does NOT price the request's target model
    let pricing = velesdb_memory::context::PricingTable {
        version: "2026-07".to_owned(),
        currency: "EUR".to_owned(),
        models: std::collections::BTreeMap::new(),
    };
    let dup = "A repeated observation about the canary stage.";
    let mut req = request(vec![fragment(dup), fragment(dup)], 10_000);
    req.target_model = Some("some-unknown-model".to_owned());

    // When compiling
    let out = ContextCompiler::new(CompilePolicy::default())
        .with_pricing(pricing)
        .compile(&req)
        .expect("compile");

    // Then no cost is invented — tokens only, no currency, no version
    assert!(out.insights.tokens_saved > 0);
    assert_eq!(out.insights.estimated_cost_saved_micros, None);
    assert_eq!(out.insights.currency, None);
    assert_eq!(out.insights.pricing_version, None);
}

// --- Negative ----------------------------------------------------------------

#[test]
fn test_compile_zero_budget_returns_context_budget_error() {
    // Given a zero token budget
    let req = request(vec![fragment("anything")], 0);

    // When compiling
    let err = ContextCompiler::new(CompilePolicy::default())
        .compile(&req)
        .expect_err("a zero budget cannot hold any context");

    // Then the error is a budget fault classified as invalid input
    assert!(matches!(err, MemoryError::ContextBudget { .. }));
    assert_eq!(err.category(), ErrorCategory::InvalidInput);
}

#[test]
fn test_compile_budget_below_reserve_returns_context_budget_error() {
    // Given a budget smaller than the response reserve
    let policy = CompilePolicy::default();
    let req = request(
        vec![fragment("anything")],
        policy.response_reserve_tokens / 2,
    );

    // When compiling
    let err = ContextCompiler::new(policy)
        .compile(&req)
        .expect_err("a budget below the reserve leaves no room for context");

    // Then the same budget fault is raised
    assert!(matches!(err, MemoryError::ContextBudget { .. }));
}

#[test]
fn test_compile_too_many_fragments_returns_invalid_input() {
    // Given more fragments than the DoS cap allows
    let over = velesdb_memory::limits::MAX_FRAGMENTS + 1;
    let fragments: Vec<ContextFragment> = (0..over)
        .map(|i| fragment(&format!("fragment {i}")))
        .collect();
    let req = request(fragments, 10_000);

    // When compiling
    let err = ContextCompiler::new(CompilePolicy::default())
        .compile(&req)
        .expect_err("the fragment-count cap must reject the request");

    // Then the request is rejected as invalid input
    assert_eq!(err.category(), ErrorCategory::InvalidInput);
}

#[test]
fn test_compile_single_oversized_fragment_returns_invalid_input() {
    // Given one fragment larger than the per-fragment byte cap
    let huge = "x".repeat(velesdb_memory::limits::MAX_FRAGMENT_BYTES + 1);
    let req = request(vec![fragment(&huge)], 10_000);

    // When compiling
    let err = ContextCompiler::new(CompilePolicy::default())
        .compile(&req)
        .expect_err("the fragment-size cap must reject the request");

    // Then the request is rejected as invalid input
    assert_eq!(err.category(), ErrorCategory::InvalidInput);
}

#[test]
fn test_compile_wire_request_with_policy_pricing_yields_cost_insights() {
    // Given a request built EXACTLY the way MCP/Node callers send it — raw
    // JSON, pricing carried inside the policy (the only channel a wire
    // caller has; the Rust-only with_pricing builder is out of their reach)
    let raw = r#"{
        "query": "state of the deploy pipeline",
        "token_budget": 10000,
        "target_model": "claude-sonnet-5",
        "fragments": [
            {"content": "The deploy pipeline runs clippy before promoting."},
            {"content": "The deploy pipeline runs clippy before promoting."}
        ],
        "policy": {
            "pricing": {
                "version": "2026-07",
                "currency": "EUR",
                "models": {
                    "claude-sonnet-5": {"input_micros_per_million_tokens": 3000000}
                }
            }
        }
    }"#;
    let req: CompileRequest = serde_json::from_str(raw).expect("the wire shape must deserialize");

    // When compiling with a plain compiler (no Rust-side pricing injected)
    let out = ContextCompiler::new(CompilePolicy::default())
        .compile(&req)
        .expect("compile");

    // Then the cost insights are populated from the wire-supplied table
    assert!(out.insights.tokens_saved > 0);
    let expected = out.insights.tokens_saved * 3_000_000 / 1_000_000;
    assert_eq!(
        out.insights.estimated_cost_saved_micros,
        Some(expected),
        "a wire caller must be able to obtain cost figures via policy.pricing"
    );
    assert_eq!(out.insights.currency.as_deref(), Some("EUR"));
    assert_eq!(out.insights.pricing_version.as_deref(), Some("2026-07"));
}

// --- Media fragments (US-009 of EPIC-P-071, PR1: inline images) --------------

use velesdb_memory::context::MediaRef;

/// A synthetic, well-formed PNG signature + IHDR chunk declaring 64x48
/// pixels — token cost `ceil(64*48/750) = 5`. No binary file is committed;
/// this is the base64 of a hand-built 33-byte header (see the crate's
/// `ImageTokenEstimator` unit tests for the byte-level fixture it mirrors).
const PNG_64X48_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAAEAAAAAwCAYAAAAAAAAA";
const PNG_64X48_COST: u64 = 5;

/// A synthetic PNG declaring 1024x768 pixels — token cost
/// `ceil(1024*768/750) = 1049`.
const PNG_1024X768_B64: &str = "iVBORw0KGgoAAAANSUhEUgAABAAAAAMACAYAAAAAAAAA";
const PNG_1024X768_COST: u64 = 1049;

/// Build a fragment carrying an inline PNG media payload.
fn media_fragment(caption: &str, bytes_b64: &str) -> ContextFragment {
    ContextFragment {
        media: Some(MediaRef {
            mime: "image/png".to_owned(),
            bytes_b64: bytes_b64.to_owned(),
        }),
        ..fragment(caption)
    }
}

#[test]
fn test_media_fragment_packs_atomically_and_is_preserved_when_budget_allows() {
    // Given a media fragment with a caption, and a generous budget
    let frag = media_fragment("a screenshot of the crash", PNG_64X48_B64);
    let out = compile(&request(vec![frag], 10_000));

    // Then it is preserved whole, under its own dedicated rule
    let decision = &out.decisions[0];
    assert_eq!(decision.action, ContextAction::Preserve);
    assert_eq!(decision.rule_id, "media.atomic");
    assert_eq!(decision.risk, FidelityRisk::Low);
    assert!(decision.handle.is_none());
    assert!(out.retrieval_handles.is_empty());
    assert!(out.content.contains("a screenshot of the crash"));
}

#[test]
fn test_media_fragment_with_blank_caption_is_preserved_but_contributes_no_visible_text() {
    // Given a bare screenshot with no caption (the common case)
    let frag = media_fragment("", PNG_1024X768_B64);
    let out = compile(&request(vec![frag], 10_000));

    // Then it is still preserved (the decision honestly reflects that the
    // image survived the budget), but the assembled prompt text carries
    // nothing for it — PR1 does not inject binary/image content into
    // `content`, only accounts for its token cost (see the crate README).
    assert_eq!(out.decisions[0].action, ContextAction::Preserve);
    assert_eq!(out.content, "");
    assert!(out.sections.is_empty());
}

#[test]
fn test_media_fragment_insights_tokens_in_and_out_reflect_the_image_cost() {
    // Given a single, blank-caption media fragment
    let frag = media_fragment("", PNG_1024X768_B64);
    let out = compile(&request(vec![frag], 10_000));

    // Then the image's real token cost is what gets accounted, not a
    // near-zero text-estimate of its (empty) caption
    assert_eq!(out.insights.tokens_in, PNG_1024X768_COST);
    assert_eq!(
        out.insights.tokens_saved, 0,
        "a fully preserved image must report zero tokens saved"
    );
}

#[test]
fn test_media_fragment_that_cannot_fit_the_budget_is_externalized_not_dropped() {
    // Given a media fragment far too large for the budget
    let frag = media_fragment("a huge screenshot", PNG_1024X768_B64);
    let out = compile(&request(vec![frag], 10));

    // Then it is externalized exactly like an unfit text fragment (US-009,
    // PR2: the memory bridge now persists media sources, so the PR1
    // `drop.media_unavailable` provisional verdict is gone) — a resolvable
    // handle is minted, and it appears in `retrieval_handles`.
    let decision = &out.decisions[0];
    assert_eq!(decision.action, ContextAction::Retrieve);
    assert_eq!(decision.rule_id, "budget.externalize");
    assert_eq!(decision.risk, FidelityRisk::High);
    assert!(decision.handle.is_some());
    assert!(
        decision.reason.contains("did not fit the budget"),
        "unexpected reason: {}",
        decision.reason
    );
    assert_eq!(out.retrieval_handles.len(), 1);
    assert_eq!(out.content, "");
}

#[test]
fn test_media_fragment_pack_is_all_or_nothing_at_the_exact_budget_boundary() {
    // Given the exact budget the image needs (its cost plus one joiner
    // token) versus one token short of it
    let joiner = HeuristicEstimator.estimate("\n\n");
    let exact = request(
        vec![media_fragment("", PNG_64X48_B64)],
        PNG_64X48_COST + joiner,
    );
    let one_short = request(
        vec![media_fragment("", PNG_64X48_B64)],
        PNG_64X48_COST + joiner - 1,
    );

    // Then it packs fully right at the boundary, and is externalized (never
    // partially) one token under it — atomic packing never yields a partial
    // byte-range, and an unfit media fragment externalizes exactly like an
    // unfit text one (US-009, PR2)
    assert_eq!(compile(&exact).decisions[0].action, ContextAction::Preserve);
    assert_eq!(
        compile(&one_short).decisions[0].action,
        ContextAction::Retrieve
    );
}

#[test]
fn test_externalized_media_fragment_attributes_its_full_cost_to_the_externalize_rule() {
    // Given a media fragment that cannot fit
    let frag = media_fragment("", PNG_1024X768_B64);
    let out = compile(&request(vec![frag], 10));

    // Then its full precomputed cost is attributed to the rule that dropped
    // it, exactly like every other savings-by-rule attribution
    let decision = &out.decisions[0];
    let saved = out
        .insights
        .tokens_saved_by_rule
        .get(&decision.rule_id)
        .copied()
        .unwrap_or(0);
    assert_eq!(saved, PNG_1024X768_COST);
}

#[test]
fn test_identical_media_bytes_are_deduped_even_with_different_captions() {
    // Given two fragments with byte-identical media but different captions
    let fragments = vec![
        media_fragment("shot A", PNG_64X48_B64),
        media_fragment("shot B", PNG_64X48_B64),
    ];
    let out = compile(&request(fragments, 10_000));

    // Then the first survives and the second is dropped as its duplicate —
    // media identity is the raw bytes, never the caption text
    assert_eq!(out.decisions[0].action, ContextAction::Preserve);
    assert_eq!(out.decisions[1].action, ContextAction::Drop);
    assert_eq!(out.decisions[1].rule_id, "drop.duplicate");
    assert_eq!(out.decisions[1].risk, FidelityRisk::Low);
    // And the reason is honest: the image survives, the differing caption
    // does not — never a blanket "content survives" claim.
    assert!(
        out.decisions[1]
            .reason
            .contains("differing caption does not"),
        "reason must not overclaim survival, got: {}",
        out.decisions[1].reason
    );
}

#[test]
fn test_total_media_payload_over_the_aggregate_cap_is_rejected() {
    // Given fragments whose individual payloads pass the per-fragment cap
    // but whose SUM exceeds the aggregate request cap (64 MiB of base64)
    let one_mib_b64 = "A".repeat(1024 * 1024);
    let fragments: Vec<ContextFragment> = (0..65)
        .map(|i| media_fragment(&format!("shot {i}"), &one_mib_b64))
        .collect();
    let err = ContextCompiler::new(CompilePolicy::default())
        .compile(&request(fragments, 10_000))
        .expect_err("65 MiB of aggregate media must be rejected");

    // Then the rejection names the aggregate cap, before any decode work
    assert!(
        err.to_string().contains("total media payload"),
        "unexpected error: {err}"
    );
}

#[test]
fn test_media_fragments_with_blank_captions_and_different_bytes_are_not_deduped() {
    // Given two DISTINCT images that both happen to carry a blank caption —
    // under plain text-content dedup these would collide ("" == ""); media
    // identity must never fall back to comparing captions.
    let fragments = vec![
        media_fragment("", PNG_64X48_B64),
        media_fragment("", PNG_1024X768_B64),
    ];
    let out = compile(&request(fragments, 10_000));

    assert_eq!(out.decisions[0].action, ContextAction::Preserve);
    assert_eq!(
        out.decisions[1].action,
        ContextAction::Preserve,
        "distinct images with blank captions must never be falsely deduped"
    );
}

#[test]
fn test_media_fragment_never_scans_bytes_b64_for_text_classification_rules() {
    // Given a media fragment whose base64 payload happens to embed
    // substrings that would trigger text rules (a URL-shaped fragment, code
    // fences) if it were ever treated as content
    let frag = ContextFragment {
        media: Some(MediaRef {
            mime: "image/png".to_owned(),
            // Deliberately not valid base64 semantics-wise for a real PNG,
            // but well-formed base64 syntax (required by validation) that
            // *contains* "http" and "```"-shaped runs if naively scanned as
            // text — proving classification never reads `bytes_b64`.
            bytes_b64: "aHR0cDovL2BgYA==".to_owned(),
        }),
        ..fragment("")
    };
    let out = compile(&request(vec![frag], 10_000));

    // Then it still classifies as media.atomic, not preserve.url or
    // preserve.code_fence
    assert_eq!(out.decisions[0].rule_id, "media.atomic");
}

#[test]
fn test_media_compilation_is_fully_deterministic() {
    // Given a mixed corpus of media fragments: distinct, duplicated, and
    // budget-exceeding
    let fragments = vec![
        media_fragment("first shot", PNG_64X48_B64),
        media_fragment("", PNG_1024X768_B64),
        media_fragment("first shot dup", PNG_64X48_B64),
    ];
    let req = request(fragments, 2_000);

    // When compiling the same request twice
    let first = compile(&req);
    let second = compile(&req);

    // Then the outputs are identical byte for byte
    assert_eq!(
        serde_json::to_string(&first).expect("serialize first"),
        serde_json::to_string(&second).expect("serialize second"),
        "media compilation must be fully deterministic, exactly like text compilation"
    );
}

// --- Screenshot supersession (US-009 of EPIC-P-071, PR2) --------------------

/// A well-formed base64 payload distinct per `seed` — media dedup keys on
/// raw bytes alone, so two screenshots in the same series need DIFFERENT
/// bytes or they would collide as exact media duplicates instead of
/// exercising supersession. The seed is an explicit parameter independent
/// of any caption (see the memory-bridge BDD twin of this fixture for why);
/// the last two base64 characters are varied (still a valid unpadded quad,
/// past the sniffed PNG header) via a multiplicative fold so same-length
/// seeds never trivially collide.
fn distinct_media_b64(seed: &str) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let hash = seed
        .bytes()
        .fold(0_u64, |h, b| h.wrapping_mul(131).wrapping_add(u64::from(b)));
    let mut b64 = PNG_64X48_B64[..PNG_64X48_B64.len() - 2].to_owned();
    b64.push(ALPHABET[usize::try_from(hash % 64).unwrap_or(0)] as char);
    b64.push(ALPHABET[usize::try_from((hash / 64) % 64).unwrap_or(0)] as char);
    b64
}

/// Build a `kind: "screenshot"` media fragment naming its `metadata.target`,
/// with bytes seeded by the caption (these compiler-only tests never resolve
/// handles, so caption-independence is not load-bearing here — the
/// memory-bridge BDD suite covers that axis with explicit seeds).
fn screenshot(caption: &str, target: &str) -> ContextFragment {
    let mut meta = serde_json::Map::new();
    meta.insert(
        "target".to_owned(),
        serde_json::Value::String(target.to_owned()),
    );
    ContextFragment {
        kind: Some("screenshot".to_owned()),
        metadata: Some(meta),
        ..media_fragment(caption, &distinct_media_b64(caption))
    }
}

#[test]
fn test_three_screenshots_of_the_same_target_only_the_last_stays_inline() {
    // Given three screenshots of the same target, in order
    let fragments = vec![
        screenshot("v1", "login-page"),
        screenshot("v2", "login-page"),
        screenshot("v3", "login-page"),
    ];
    let out = compile(&request(fragments, 10_000));

    // Then only the last is preserved inline; the first two are externalized
    // as superseded, each with its own resolvable handle
    assert_eq!(out.decisions[0].action, ContextAction::Retrieve);
    assert_eq!(out.decisions[0].rule_id, "retrieve.screenshot_superseded");
    assert!(out.decisions[0].handle.is_some());
    assert!(out.decisions[0]
        .reason
        .contains("superseded by a newer screenshot"));

    assert_eq!(out.decisions[1].action, ContextAction::Retrieve);
    assert_eq!(out.decisions[1].rule_id, "retrieve.screenshot_superseded");
    assert!(out.decisions[1].handle.is_some());

    assert_eq!(out.decisions[2].action, ContextAction::Preserve);
    assert_eq!(out.decisions[2].rule_id, "media.atomic");
    assert!(out.decisions[2].handle.is_none());

    assert_eq!(out.retrieval_handles.len(), 2);
}

#[test]
fn test_screenshots_of_different_targets_are_never_superseded() {
    // Given screenshots of two DIFFERENT targets
    let fragments = vec![
        screenshot("login v1", "login-page"),
        screenshot("checkout v1", "checkout-page"),
    ];
    let out = compile(&request(fragments, 10_000));

    // Then both stay inline — no succession within either target's series
    assert_eq!(out.decisions[0].action, ContextAction::Preserve);
    assert_eq!(out.decisions[1].action, ContextAction::Preserve);
    assert!(out.retrieval_handles.is_empty());
}

#[test]
fn test_screenshots_without_a_target_are_never_superseded() {
    // Given two screenshots with no `metadata.target` at all
    let fragments = vec![
        ContextFragment {
            kind: Some("screenshot".to_owned()),
            ..media_fragment("v1", &distinct_media_b64("v1"))
        },
        ContextFragment {
            kind: Some("screenshot".to_owned()),
            ..media_fragment("v2", &distinct_media_b64("v2"))
        },
    ];
    let out = compile(&request(fragments, 10_000));

    // Then no target means no evidence of succession — both stay inline
    assert_eq!(out.decisions[0].action, ContextAction::Preserve);
    assert_eq!(out.decisions[1].action, ContextAction::Preserve);
    assert!(out.retrieval_handles.is_empty());
}

#[test]
fn test_superseded_screenshot_is_excluded_from_the_assembled_content() {
    // Given two screenshots of the same target with non-empty captions
    let fragments = vec![
        screenshot("first look", "login-page"),
        screenshot("second look", "login-page"),
    ];
    let out = compile(&request(fragments, 10_000));

    // Then the superseded caption never appears in the assembled prompt
    assert!(!out.content.contains("first look"));
}

#[test]
fn test_screenshot_supersession_rule_can_be_disabled() {
    // Given the same three-screenshot series, with the rule opted out
    let fragments = vec![
        screenshot("v1", "login-page"),
        screenshot("v2", "login-page"),
        screenshot("v3", "login-page"),
    ];
    let policy = CompilePolicy {
        disabled_rules: vec!["retrieve.screenshot_superseded".to_owned()],
        ..CompilePolicy::default()
    };
    let mut req = request(fragments, 10_000);
    req.policy = Some(policy);
    let out = ContextCompiler::new(CompilePolicy::default())
        .compile(&req)
        .expect("compile");

    // Then every screenshot stays inline — the rule is opt-outable like any
    // other named rule
    assert!(
        out.decisions
            .iter()
            .all(|d| d.action == ContextAction::Preserve),
        "disabling the rule must leave every screenshot inline, got: {:?}",
        out.decisions
    );
}