trusty-memory 0.22.0

MCP server (stdio + HTTP/SSE) for trusty-memory
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
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
//! Integration tests for `commands::prompt_context`.
//!
//! Why: Separated from `mod.rs` to keep the production module under the
//! 500-SLOC cap while retaining full test coverage.
//! What: exercises `build_injection_body`, filter helpers, format helpers,
//! and the full HTTP-daemon path (gated on `axum-server`).
//! Test: this file is the test suite.

use super::*;
// Why (issue #226): `serde_json::json!` is only used by the daemon-based
//      tests, which are themselves gated behind `axum-server`. Mirror the
//      gate here so `--no-default-features` builds stay warning-free.
#[cfg(feature = "axum-server")]
use serde_json::json;

/// Why (issue #134): the recall query needs the actual prompt text the
/// user typed; the stdin payload carries it under `"prompt"`.
/// What: parses three shapes — full JSON with `prompt`, JSON without,
/// and raw text — and asserts each returns the expected string.
/// Test: itself.
#[test]
fn parse_user_prompt_prefers_prompt_field() {
    let json_with_prompt = serde_json::json!({
        "prompt": "what is rust?",
        "cwd": "/tmp/example",
    })
    .to_string();
    assert_eq!(parse_user_prompt(&json_with_prompt), "what is rust?");

    let json_without_prompt = serde_json::json!({"cwd": "/tmp/example"}).to_string();
    assert_eq!(parse_user_prompt(&json_without_prompt), json_without_prompt);

    assert_eq!(parse_user_prompt("plain text query"), "plain text query");
    assert_eq!(parse_user_prompt(""), "");
}

/// Why (issue #139): the deny-tag filter is the load-bearing piece of
/// the recall-quality fix; unit-test the boundary conditions in
/// isolation so a refactor cannot silently regress them.
/// What: case-insensitive matching, empty deny list = passthrough,
/// drawers with no tags = kept (no excluded tag can match).
/// Test: itself.
#[test]
fn filter_drawers_by_deny_tags_handles_edge_cases() {
    use filter::{filter_drawers_by_deny_tags, RecalledDrawer};
    let make = |tags: &[&str]| RecalledDrawer {
        content: "irrelevant".into(),
        tags: tags.iter().map(|s| s.to_string()).collect(),
        layer: Some(2),
        score: Some(0.9),
    };

    // Empty deny list → passthrough.
    let drawers = vec![make(&["claude-session"]), make(&["rust"])];
    let out = filter_drawers_by_deny_tags(drawers.clone(), &[]);
    assert_eq!(out.len(), 2, "empty deny list must pass everything");

    // Case-insensitive match (deny "claude-session" vs tag "Claude-Session").
    let drawers = vec![make(&["Claude-Session"]), make(&["rust"])];
    let out = filter_drawers_by_deny_tags(drawers, &["claude-session".to_string()]);
    assert_eq!(out.len(), 1);
    assert!(out[0].tags.iter().any(|t| t == "rust"));

    // Drawer with no tags is always kept.
    let drawers = vec![make(&[]), make(&["user-prompt"])];
    let out = filter_drawers_by_deny_tags(drawers, &["user-prompt".to_string()]);
    assert_eq!(out.len(), 1, "tagless drawers must survive the filter");
    assert!(out[0].tags.is_empty());

    // Multiple deny entries — any match excludes.
    let drawers = vec![
        make(&["claude-session"]),
        make(&["user-prompt"]),
        make(&["signal"]),
    ];
    let out = filter_drawers_by_deny_tags(
        drawers,
        &["claude-session".to_string(), "user-prompt".to_string()],
    );
    assert_eq!(out.len(), 1);
    assert_eq!(out[0].tags, vec!["signal".to_string()]);
}

/// Why (issue #134): KG triples should only surface when one of their
/// endpoints actually appears in the user's prompt; otherwise the
/// injection just dumps random graph noise.
/// What: build a small set of triples; query a prompt that mentions
/// only one subject; assert exactly the matching triple comes back.
/// Test: itself.
#[test]
fn select_relevant_triples_filters_by_prompt_overlap() {
    use filter::{select_relevant_triples, RawTriple};
    let triples = vec![
        RawTriple {
            subject: "tga".into(),
            predicate: "is_alias_for".into(),
            object: "trusty-git-analytics".into(),
        },
        RawTriple {
            subject: "python".into(),
            predicate: "is-a".into(),
            object: "language".into(),
        },
        RawTriple {
            subject: "rust".into(),
            predicate: "is-a".into(),
            object: "language".into(),
        },
    ];
    let chosen = select_relevant_triples(&triples, "tell me about rust integration", 5);
    assert_eq!(chosen.len(), 1, "only the rust triple should match");
    assert_eq!(chosen[0].subject, "rust");

    // Empty / no-overlap prompt → no triples.
    let none = select_relevant_triples(&triples, "weather forecast next week", 5);
    assert!(none.is_empty());
}

/// Why: the injection has a hard 4 KB byte ceiling so a runaway palace
/// can't drown the model's prompt; truncation must end with `…` and
/// stay valid UTF-8.
/// What: synthesises drawers whose previews exceed the cap, calls
/// `compose_injection`, asserts the result is `<= INJECTION_BYTE_CAP`
/// and ends with `…`.
/// Test: itself.
#[test]
fn compose_injection_truncates_at_cap() {
    use filter::{RawTriple, RecalledDrawer};
    use format::compose_injection;
    // Stuff a giant global-facts block to push the composition past the
    // 4 KB byte cap. Drawer previews are already capped at
    // DRAWER_PREVIEW_CHARS so the cap-trigger has to come from the
    // global section.
    // #5037 raised INJECTION_BYTE_CAP from 4 KB to 8 KB; size the fixture off
    // the constant so the next raise cannot silently stop exercising truncation.
    let lines = INJECTION_BYTE_CAP / "- fact line\n".len() + 64;
    let big_global = "## Big block\n".to_string() + &"- fact line\n".repeat(lines);
    let drawers: Vec<RecalledDrawer> = (0..5)
        .map(|i| RecalledDrawer {
            content: format!("drawer {i} content"),
            tags: vec!["tag1".into()],
            layer: Some(2),
            score: Some(0.9),
        })
        .collect();
    let triples: Vec<RawTriple> = (0..5)
        .map(|i| RawTriple {
            subject: format!("subject{i}"),
            predicate: "p".into(),
            object: "object".into(),
        })
        .collect();
    let out = compose_injection(Some(&big_global), &drawers, 0, &triples, Some("alpha"));
    assert!(
        out.len() <= INJECTION_BYTE_CAP,
        "expected len <= cap; got {}",
        out.len()
    );
    // Truncation marker survives.
    assert!(
        out.ends_with('…'),
        "expected `…` truncation marker; got tail: {}",
        &out[out.len().saturating_sub(20)..]
    );
}

/// Why: an empty composition (no global facts, no drawers, no triples)
/// must return an empty string so the caller can substitute the
/// legacy placeholder. Section headers should never appear without
/// content beneath them.
/// What: call `compose_injection` with empty inputs and assert the
/// result is empty.
/// Test: itself.
#[test]
fn compose_injection_empty_inputs_yields_empty() {
    use format::compose_injection;
    let out = compose_injection(None, &[], 0, &[], Some("alpha"));
    assert!(out.is_empty(), "got: {out:?}");
}

/// Why (issue #5037): the truncation budget was raised from 4 KB to 8 KB
/// alongside the relevance floor. Pin the new ceiling explicitly so a future
/// edit cannot quietly shrink it back and blame the floor for lost content.
/// What: asserts the constant and that `compose_injection` respects it.
/// Test: itself.
#[test]
fn injection_byte_cap_is_eight_kib() {
    assert_eq!(INJECTION_BYTE_CAP, 8 * 1024);
    assert_eq!(DEFAULT_TOP_K, 12, "requirement 2: max size raised from 5");
}

/// Why (issue #5037, requirement 1 + the primary probe): "what is the capital
/// of France" returned five drawers all scoring exactly `0.15` — the
/// `L1_NO_SIMILARITY_PENALTY` floor — and the reader could not tell them from a
/// genuine `0.56` hit. That set must now be empty.
/// What: five 0.15-scored drawers through the relevance filter at the shipped
/// default; asserts nothing survives and all five are counted as withheld.
/// Test: itself.
#[test]
fn relevance_floor_drops_all_noise_drawers() {
    use filter::{filter_drawers_by_relevance_floor, RecalledDrawer};
    let noise: Vec<RecalledDrawer> = (0..5)
        .map(|i| RecalledDrawer {
            content: format!("off-topic session drawer {i}"),
            tags: vec!["signal".into()],
            layer: Some(1),
            // The exact value `rescore_l1_by_similarity` assigns an essential
            // drawer the HNSW search never returned.
            score: Some(0.15),
        })
        .collect();
    let out = filter_drawers_by_relevance_floor(noise, DEFAULT_RELEVANCE_FLOOR);
    assert!(
        out.kept.is_empty(),
        "0.15 L1-penalty drawers must not reach the injection; got {:?}",
        out.kept.len()
    );
    assert_eq!(out.withheld, 5, "all five must be counted for the notice");
}

/// Why (issue #5037): a floor that also cut real matches would trade one defect
/// for a worse one. `0.56` is the measured median of the self-retrieval signal
/// population against the live palace.
/// What: one genuine hit among four noise drawers; asserts only the hit
/// survives, in order, with the rest counted.
/// Test: itself.
#[test]
fn relevance_floor_keeps_high_scoring_drawer() {
    use filter::{filter_drawers_by_relevance_floor, RecalledDrawer};
    let make = |content: &str, score: f32| RecalledDrawer {
        content: content.into(),
        tags: Vec::new(),
        layer: Some(2),
        score: Some(score),
    };
    let mixed = vec![
        make("genuine on-topic hit about rust integration", 0.56),
        make("noise a", 0.15),
        make("noise b", 0.15),
        make("noise c", 0.2446),
        make("noise d", 0.3439),
    ];
    let out = filter_drawers_by_relevance_floor(mixed, DEFAULT_RELEVANCE_FLOOR);
    assert_eq!(out.kept.len(), 1, "the genuine hit must survive");
    assert!(out.kept[0].content.contains("genuine on-topic hit"));
    assert_eq!(out.withheld, 4);
}

/// Why (issue #5037): a drawer whose `score` the daemon did not send is
/// unjudgeable. Dropping it would let a wire-format change silently empty every
/// injection — the fail-open inversion this fix exists to prevent.
/// What: a drawer with `score: None` through the filter at the default floor.
/// Test: itself.
#[test]
fn relevance_floor_keeps_drawer_without_score() {
    use filter::{filter_drawers_by_relevance_floor, RecalledDrawer};
    let drawers = vec![RecalledDrawer {
        content: "daemon predates the score field".into(),
        tags: Vec::new(),
        layer: Some(2),
        score: None,
    }];
    let out = filter_drawers_by_relevance_floor(drawers, DEFAULT_RELEVANCE_FLOOR);
    assert_eq!(out.kept.len(), 1, "unknown score must not mean dropped");
    assert_eq!(out.withheld, 0);
}

/// Why (issue #5037, requirement 4): a partial drop must tell the reader more
/// exists, so "the model saw everything relevant" is never assumed wrongly.
/// What: composes with two kept drawers and three withheld; asserts the count
/// and the `memory_recall` pointer both render.
/// Test: itself.
#[test]
fn compose_injection_announces_withheld_drawers() {
    use filter::RecalledDrawer;
    use format::compose_injection;
    let drawers: Vec<RecalledDrawer> = (0..2)
        .map(|i| RecalledDrawer {
            content: format!("kept drawer {i}"),
            tags: Vec::new(),
            layer: Some(2),
            score: Some(0.7),
        })
        .collect();
    let out = compose_injection(None, &drawers, 3, &[], Some("alpha"));
    assert!(out.contains("kept drawer 0"), "kept content must render");
    assert!(
        out.contains("3 further memories withheld"),
        "the withheld count must be visible; got:\n{out}"
    );
    assert!(
        out.contains("memory_recall"),
        "the notice must point at how to see past the floor; got:\n{out}"
    );
}

/// Why (issue #5037, requirement 4 — the case the ruling calls out): returning
/// zero drawers where five noisy ones used to appear is correct, but only if it
/// is visible. Silence must be distinguishable from nothing-existed.
/// What: composes with zero kept and five withheld, then with zero of both.
/// Asserts the first announces itself and the second stays silent — an empty
/// palace has nothing to announce.
/// Test: itself.
#[test]
fn compose_injection_announces_total_silence() {
    use format::compose_injection;
    let silenced = compose_injection(None, &[], 5, &[], Some("alpha"));
    assert!(
        !silenced.is_empty(),
        "an all-withheld recall must not render as an empty injection"
    );
    assert!(
        silenced.contains("cleared the relevance floor") && silenced.contains('5'),
        "total silence must be announced with its count; got:\n{silenced}"
    );
    assert!(
        silenced.contains("Nothing is missing from the palace"),
        "the notice must distinguish withheld from absent; got:\n{silenced}"
    );

    let nothing_existed = compose_injection(None, &[], 0, &[], Some("alpha"));
    assert!(
        nothing_existed.is_empty(),
        "zero candidates is not a withheld recall; got:\n{nothing_existed}"
    );
}

/// Why (issue #5037): the floor is required to be *configurable*, including
/// settable to zero to restore pre-fix behaviour. The clamp is the only thing
/// standing between an operator typo and a disabled or total-blackout gate.
/// What: exercises `clamp_floor` across unset, valid, zero, out-of-range,
/// unparseable, and NaN inputs.
/// Test: itself.
#[test]
fn configured_relevance_floor_clamps_to_bounds() {
    assert_eq!(clamp_floor(None), DEFAULT_RELEVANCE_FLOOR);
    assert_eq!(clamp_floor(Some("0.5")), 0.5);
    assert_eq!(clamp_floor(Some(" 0.42 ")), 0.42);
    assert_eq!(clamp_floor(Some("0")), 0.0, "zero must disable the gate");
    assert_eq!(clamp_floor(Some("-3")), 0.0);
    assert_eq!(clamp_floor(Some("9")), 1.0);
    assert_eq!(clamp_floor(Some("banana")), DEFAULT_RELEVANCE_FLOOR);
    assert_eq!(clamp_floor(Some("NaN")), DEFAULT_RELEVANCE_FLOOR);
}

/// Why (issue #5037, requirement 2): the K ceiling moved with the default, and
/// a ceiling below the default would silently cap every operator override.
/// What: exercises `clamp_top_k` across unset, valid, zero, over-ceiling, and
/// unparseable inputs.
/// Test: itself.
#[test]
fn configured_top_k_clamps_to_bounds() {
    assert_eq!(clamp_top_k(None), DEFAULT_TOP_K);
    assert_eq!(clamp_top_k(Some("7")), 7);
    assert_eq!(clamp_top_k(Some("0")), DEFAULT_TOP_K);
    assert_eq!(clamp_top_k(Some("999")), MAX_TOP_K);
    assert_eq!(clamp_top_k(Some("nope")), DEFAULT_TOP_K);
}

/// Why (issue #5037, requirement 3): the recall query must be the whole user
/// input. `hook_prompt_excerpt` exists a few lines away in the same module and
/// truncates for telemetry — wiring it into the query by mistake would fragment
/// every recall silently. Pin that `parse_user_prompt` hands back the prompt
/// entire.
/// What: a 12,000-character prompt through `parse_user_prompt`; asserts the
/// result is byte-identical, and that the telemetry excerpt is not.
/// Test: itself.
#[test]
fn recall_query_is_the_whole_prompt() {
    let long: String = "explain the retrieval floor and why it matters. "
        .repeat(400)
        .trim_end()
        .to_string();
    assert!(long.len() > 12_000, "fixture must exceed any plausible cap");
    let payload = serde_json::json!({ "prompt": long, "cwd": "/tmp" }).to_string();

    let parsed = parse_user_prompt(&payload);
    assert_eq!(parsed, long, "the recall query must not be truncated");

    // The telemetry excerpt IS truncated — that asymmetry is the point.
    assert!(
        crate::hook_prompt_excerpt(&parsed).len() < parsed.len(),
        "excerpt helper must stay distinct from the query path"
    );
}

/// Why (issue #125): when Claude Code invokes the UserPromptSubmit hook,
/// the stdin JSON carries a `cwd` field that reflects the user's actual
/// working directory at prompt time. The hook process cwd may be where
/// the hook was registered (typically a fixed install root), not where
/// the user actually is. The log palace must follow the stdin `cwd`.
/// What: build a stdin JSON payload pointing at a tempdir, derive the
/// expected slug for that tempdir via the *_at variant, and assert
/// `resolve_palace_for_log` returns the same slug — even though the
/// process cwd is unchanged and would resolve to a different slug.
/// Test: itself.
#[test]
fn resolve_palace_for_log_prefers_stdin_cwd() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let project = tmp.path().join("stdin-driven-project");
    std::fs::create_dir_all(&project).expect("create project dir");
    let payload = serde_json::json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project.to_string_lossy(),
        "prompt": "hello"
    })
    .to_string();

    let expected =
        crate::messaging::cwd_palace_slug_at(&project).expect("derive slug from stdin cwd");
    let got = resolve_palace_for_log(&payload);
    assert_eq!(
        got, expected,
        "stdin `cwd` must override the process cwd for the log palace slug"
    );
    assert!(
        got.contains("stdin-driven-project"),
        "expected slug derived from stdin path, got {got:?}"
    );
}

/// Why (issue #125): when stdin is empty or non-JSON, the helper must
/// fall through to the process-cwd resolution path so manual `trusty-
/// memory prompt-context` invocations from a TTY still get a useful
/// palace identifier.
/// What: pass an empty string and a non-JSON string; assert the result
/// is *not* the legacy `"<unknown>"` sentinel (the process cwd here is a
/// real git repo, so cwd_palace_slug succeeds).
/// Test: itself.
#[test]
fn resolve_palace_for_log_falls_back_to_process_cwd() {
    let from_empty = resolve_palace_for_log("");
    let from_garbage = resolve_palace_for_log("not json at all");
    assert_eq!(from_empty, from_garbage);
    assert_ne!(from_empty, "<unknown>");
}

/// Why: the hook is wired into every Claude Code prompt the user types;
/// failing it would block the prompt. The contract is that a missing
/// daemon-address lockfile (the canonical "daemon not running" signal)
/// must produce `Ok(())` with no stdout, not an error.
/// What: redirects `trusty_common::resolve_data_dir` at a fresh tempdir
/// via `TRUSTY_DATA_DIR_OVERRIDE` so `read_daemon_addr("trusty-memory")`
/// observes a missing lockfile, then runs the handler and asserts it
/// returns `Ok(())`. Calls `handle_prompt_context_with_payload` directly
/// (issue #2079) with a fixed empty payload instead of
/// `handle_prompt_context()` so the test never spawns a real blocking
/// stdin read that could outlive the test's `Runtime` teardown.
#[tokio::test]
async fn prompt_context_returns_ok_without_daemon() {
    let _guard = crate::commands::env_test_lock().lock().await;
    let tmp = tempfile::tempdir().expect("tempdir");
    // SAFETY: tests serialise on `TRUSTY_DATA_DIR_OVERRIDE` by convention
    // across the trusty-* workspace (see trusty-common's lib.rs notes).
    // This test only mutates the env var inside its own scope.
    unsafe {
        std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, tmp.path());
    }
    let res = handle_prompt_context_with_payload(String::new()).await;
    unsafe {
        std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
    }
    assert!(
        res.is_ok(),
        "missing daemon lockfile must degrade to Ok(()), got {res:?}"
    );
}

/// Why (issue #134): the hook's whole value-prop is surfacing relevant
/// drawers from the palace; previously it only returned the workspace-
/// level hot facts. Confirm that with a live daemon, a populated palace,
/// and a prompt that mentions a known keyword, the rendered injection
/// contains real drawer content — not the legacy `EMPTY_PLACEHOLDER`.
/// What: spin up a real HTTP daemon under a tempdir-pinned data root,
/// create a palace whose slug matches a project tempdir basename,
/// populate it with three keyworded drawers via the MCP dispatch
/// (which loads the real embedder), then call `build_injection_body`
/// with a stdin payload carrying `cwd = <project tempdir>` and
/// `prompt = "how does rust integration work?"`. Assert the body
/// contains the rust drawer's content and the relevant-memories
/// section header.
/// Test: itself.
/// Note (issue #226): gated on `axum-server` because it spins up the
/// real HTTP daemon via `run_http_on`.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn prompt_context_recalls_palace_drawers() {
    let _guard = crate::commands::env_test_lock().lock().await;
    let (state, _data_dir_tmp, _project_dir_tmp, project_dir, slug, addr_handle) =
        spin_up_test_daemon_with_palace("prompt-ctx-recall-pop").await;

    // Populate the palace with three diverged drawers via MCP dispatch.
    // Using the MCP path here exercises the real embedder + KG hook.
    for (text, tags) in [
        (
            "Rust integration uses tokio for async tasks and serde for JSON",
            vec!["rust", "tokio"],
        ),
        (
            "Python bindings ship via PyO3 with custom ABI shims",
            vec!["python", "pyo3"],
        ),
        (
            "Knowledge graph stores triples in redb with valid_from intervals",
            vec!["kg", "redb"],
        ),
    ] {
        let tags_json: Vec<serde_json::Value> = tags.iter().map(|t| json!(t)).collect();
        let _ = crate::tools::dispatch_tool(
            &state,
            "memory_remember",
            json!({
                "palace": slug,
                "text": text,
                "room": "General",
                "tags": tags_json,
            }),
        )
        .await
        .expect("memory_remember");
    }

    // Build the stdin payload Claude Code would send: a JSON object with
    // `cwd` (the project dir) and `prompt` (mentioning "rust").
    let payload = json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project_dir.to_string_lossy(),
        "prompt": "how does rust integration work?"
    })
    .to_string();

    let start = std::time::Instant::now();
    let body = build_injection_body(&payload).await;
    let elapsed_ms = start.elapsed().as_millis();
    eprintln!("prompt_context_recalls_palace_drawers latency: {elapsed_ms}ms");

    assert_ne!(
        body, EMPTY_PLACEHOLDER,
        "populated palace must return real content, not the placeholder"
    );
    // The injection must mention the rust drawer's content (proves
    // recall actually targeted the resolved palace and surfaced
    // prompt-relevant memories).
    assert!(
        body.to_lowercase().contains("rust") && body.to_lowercase().contains("integration"),
        "expected rust integration drawer in injection; got:\n{body}"
    );
    // Section header should be present (proves the multi-section
    // composition is wired through).
    assert!(
        body.contains("Relevant memories") || body.contains("memories from palace"),
        "expected a `Relevant memories` section; got:\n{body}"
    );

    // Performance guardrail (issue #134 target: <200 ms p95). On
    // CI/dev machines this comfortably stays under the budget.
    assert!(
        elapsed_ms < 5_000,
        "prompt-context too slow ({elapsed_ms}ms) — investigate"
    );

    addr_handle.shutdown().await;
}

/// Why (issue #5037, end to end): the unit tests above pin the floor over
/// synthetic scores. This one proves the whole chain — real embedder, real HTTP
/// recall, real `score` on the wire, real filter — turns an off-topic prompt
/// into zero injected drawers plus a visible withheld notice, which is the
/// behaviour the probe found missing ("what is the capital of France" returned
/// five drawers at 0.15, rendered as if they matched).
/// What: populates a palace with three Rust/Python/KG drawers, then submits a
/// prompt about none of them. Asserts no drawer content reaches the injection,
/// and that the block says results were withheld rather than going silent.
/// Test: itself.
/// Note (issue #226): gated on `axum-server`; spins up the HTTP daemon.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn prompt_context_off_topic_prompt_withholds_and_says_so() {
    let _guard = crate::commands::env_test_lock().lock().await;
    unsafe {
        std::env::remove_var(ENV_MIN_SCORE);
        std::env::remove_var(ENV_RECALL_DENY_TAGS);
    }
    let (state, _data_dir_tmp, _project_dir_tmp, project_dir, slug, addr_handle) =
        spin_up_test_daemon_with_palace("prompt-ctx-floor-e2e").await;

    for (text, tags) in [
        (
            "Rust integration uses tokio for async tasks and serde for JSON encoding",
            vec!["rust", "tokio"],
        ),
        (
            "Python bindings ship via PyO3 with custom ABI shims for the runtime",
            vec!["python", "pyo3"],
        ),
        (
            "Knowledge graph stores triples in redb with valid_from intervals per edge",
            vec!["kg", "redb"],
        ),
    ] {
        let tags_json: Vec<serde_json::Value> = tags.iter().map(|t| json!(t)).collect();
        let _ = crate::tools::dispatch_tool(
            &state,
            "memory_remember",
            json!({
                "palace": slug,
                "text": text,
                "room": "General",
                "tags": tags_json,
            }),
        )
        .await
        .expect("memory_remember");
    }

    // The probe query from #5037 — nothing in this palace answers it.
    let payload = json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project_dir.to_string_lossy(),
        "prompt": "what is the capital of France"
    })
    .to_string();
    let body = build_injection_body(&payload).await;

    for leaked in ["tokio", "PyO3", "valid_from"] {
        assert!(
            !body.contains(leaked),
            "off-topic prompt must not inject `{leaked}`; got:\n{body}"
        );
    }
    assert!(
        body.contains("relevance floor"),
        "a withheld recall must announce itself, not go silent; got:\n{body}"
    );

    addr_handle.shutdown().await;
}

/// Why (issue #134, negative case): when the resolved palace has no
/// drawers AND no global hot facts have been asserted, the hook must
/// still emit a safe placeholder so downstream consumers see byte-
/// identical behaviour to the pre-fix daemon. Don't regress the empty
/// case while fixing the populated one.
/// What: spin up the same daemon shape but skip the drawer-population
/// step; assert the body equals [`EMPTY_PLACEHOLDER`].
/// Test: itself.
/// Note (issue #226): gated on `axum-server`; spawns the HTTP daemon.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn prompt_context_empty_palace_falls_back_to_global() {
    let _guard = crate::commands::env_test_lock().lock().await;
    let (_state, _data_dir_tmp, _project_dir_tmp, project_dir, _slug, addr_handle) =
        spin_up_test_daemon_with_palace("prompt-ctx-recall-empty").await;

    let payload = json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project_dir.to_string_lossy(),
        "prompt": "no drawers exist here"
    })
    .to_string();
    let body = build_injection_body(&payload).await;
    assert_eq!(
        body, EMPTY_PLACEHOLDER,
        "empty palace + empty prompt-facts must fall back to the placeholder"
    );

    addr_handle.shutdown().await;
}

/// Test fixture: spin up a real HTTP daemon under a tempdir-pinned
/// data root, create a palace with the given slug under a project
/// tempdir whose basename matches the slug, and return everything
/// the test needs to interact with the daemon.
///
/// Why: the prompt-context hook talks HTTP to a live daemon; unit
/// tests with the router alone can't exercise the `read_daemon_addr`
/// → HTTP round trip. This helper wires it all together in one place.
/// What: creates two tempdirs (one for the data root, one for the
/// project cwd whose basename equals `palace_slug`), pins
/// `TRUSTY_DATA_DIR_OVERRIDE`, builds the `AppState`, creates the
/// palace, spawns the HTTP server on `127.0.0.1:0`, and waits for
/// the daemon addr file to land. Returns `(state, data_dir_tmp,
/// project_dir_tmp, project_dir_path, palace_slug, addr_handle)`.
/// Test: indirectly via `prompt_context_recalls_palace_drawers` and
/// `prompt_context_empty_palace_falls_back_to_global`.
/// Note (issue #226): gated on `axum-server` because `run_http_on` is
/// only available when the HTTP-serving surface is compiled in.
#[cfg(feature = "axum-server")]
async fn spin_up_test_daemon_with_palace(
    palace_slug: &str,
) -> (
    crate::AppState,
    tempfile::TempDir,
    tempfile::TempDir,
    std::path::PathBuf,
    String,
    DaemonHandle,
) {
    // Seed the process-wide `retrieval::shared_embedder()` OnceCell with
    // `MockEmbedder`: every caller of this helper writes fixture drawers via
    // `memory_remember`, which embeds. The cell is first-writer-wins for the
    // whole process, so under `cargo test` a sibling test's seed satisfied
    // these; under per-test process isolation (`cargo nextest run`) each gets a
    // virgin cell and reaches for the real ONNX model (HTTP 429 in CI) — same
    // defect class as #4413. The call is idempotent, so order does not matter.
    trusty_common::memory_core::retrieval::seed_shared_embedder_with_mock();
    let data_tmp = tempfile::tempdir().expect("data tempdir");
    let project_tmp = tempfile::tempdir().expect("project tempdir");
    // Build a project directory whose basename equals the palace slug.
    // This is what `cwd_palace_slug_at` will derive from the stdin `cwd`.
    let project_dir = project_tmp.path().join(palace_slug);
    std::fs::create_dir_all(&project_dir).expect("project dir");

    // SAFETY: env_test_lock serialises this section.
    unsafe {
        std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, data_tmp.path());
        std::env::remove_var(crate::prompt_log::ENV_ENABLED);
        std::env::remove_var(crate::prompt_log::ENV_DIR);
        std::env::remove_var(crate::prompt_log::ENV_HASH_PROMPTS);
        // Issue #88: bypass palace-slug enforcement so test palaces with
        // arbitrary names can be created without a matching project root.
        std::env::set_var("TRUSTY_SKIP_PALACE_ENFORCEMENT", "1");
    }

    // Issue #1217: the default palace ID is now derived from project identity
    // (git owner/repo, else parent/dir slug), so a bare tempdir whose basename
    // equals `palace_slug` no longer resolves to that slug (a non-git dir
    // derives `<parent>-<leaf>`). Write a committed pin file in `project_dir`
    // so the hook's `cwd_palace_slug_at` resolves deterministically to the
    // palace this fixture created. This is fully hermetic (per-tempdir, no env
    // or global state to leak into sibling tests) and exercises the #1217
    // pin-file-primacy anchor that keeps existing palaces from being orphaned.
    crate::project_root::write_project_pin(
        &project_dir,
        &crate::project_root::ProjectPin {
            schema_version: crate::project_root::PIN_SCHEMA_VERSION,
            palace: palace_slug.to_string(),
            note: None,
        },
    )
    .expect("write project pin for fixture");

    let data_root =
        trusty_common::resolve_data_dir("trusty-memory").expect("resolve data dir under override");
    let state = crate::AppState::new(data_root.clone());
    // Flip to Ready so the issue #911 warming preflight does not reject
    // the `memory_remember` calls that seed fixture data below.
    state.set_ready();

    // Create the palace via MCP dispatch so the on-disk metadata
    // matches what a real client would have produced. The `TRUSTY_MEMORY_PALACE`
    // override pinned above makes `cwd_palace_slug_at` (and thus the hook)
    // resolve to exactly this slug (issue #1217).
    let _ = crate::tools::dispatch_tool(&state, "palace_create", json!({"name": palace_slug}))
        .await
        .expect("palace_create");

    // Bind a random local port and start the HTTP server. `run_http_on`
    // writes the addr file as part of startup; we poll for it briefly
    // so the subsequent `read_daemon_addr` call succeeds.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind 127.0.0.1:0");
    let addr = listener.local_addr().expect("local_addr");
    let state_for_server = state.clone();
    let handle = tokio::spawn(async move {
        let _ = crate::run_http_on(state_for_server, listener).await;
    });

    // Poll for the addr file (run_http_on writes it after binding).
    // Generous deadline so a contended CI machine doesn't flake — the
    // disk_size_ticker spawned inside `run_http_on` does some setup
    // work before the addr write lands. Bumped from 250 to 500
    // attempts (5 s → 10 s) under issue #139: the recall-quality fix
    // doubled the number of fixtures spinning a daemon (5 tests now
    // share this helper), so a heavily loaded host needs more headroom
    // before the first `http_addr` write lands.
    let addr_file = data_root.join("http_addr");
    let mut attempts = 0;
    while !addr_file.exists() && attempts < 500 {
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        attempts += 1;
    }
    assert!(
        addr_file.exists(),
        "daemon never wrote http_addr at {} (attempts={attempts})",
        addr_file.display()
    );

    (
        state,
        data_tmp,
        project_tmp,
        project_dir,
        palace_slug.to_string(),
        DaemonHandle {
            addr,
            join: Some(handle),
        },
    )
}

/// Test-only handle to a spawned daemon — aborts the server task on
/// drop or explicit `shutdown` so the tempdir cleanup doesn't race
/// with in-flight requests.
/// Note (issue #226): gated on `axum-server` because the only callers
/// are HTTP-daemon-dependent tests.
#[cfg(feature = "axum-server")]
struct DaemonHandle {
    #[allow(dead_code)]
    addr: std::net::SocketAddr,
    join: Option<tokio::task::JoinHandle<()>>,
}

#[cfg(feature = "axum-server")]
impl DaemonHandle {
    async fn shutdown(mut self) {
        if let Some(h) = self.join.take() {
            h.abort();
            let _ = h.await;
        }
        // Release the pinned data dir override for sibling tests.
        // SAFETY: protected by env_test_lock in the caller.
        unsafe {
            std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
        }
    }
}

/// Why (issue #139): live evidence from the user's `trusty-tools`
/// session showed the prompt-context hook injecting raw past user
/// prompts (drawers tagged `claude-session` / `user-prompt` from an
/// upstream auto-capture hook) on every UserPromptSubmit, dominating
/// real palace knowledge. Filtering by deny-listed tags is the
/// cheapest in-tree fix. Verify the default deny list drops both
/// auto-capture tags AND keeps a signal drawer untouched.
/// What: populate a palace with three drawers — one tagged
/// `claude-session`, one tagged `user-prompt`, one tagged with only
/// signal tags. The prompt mentions a keyword shared by all three so
/// recall returns all three. Assert the injection contains only the
/// signal drawer's content and neither of the deny-listed drawers'
/// content surfaces.
/// Test: itself.
/// Note (issue #226): gated on `axum-server`; spins up the HTTP daemon.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn prompt_context_recall_filters_deny_tags() {
    let _guard = crate::commands::env_test_lock().lock().await;
    // Defensive: scrub the env override in case a sibling test set it
    // and panicked before its cleanup ran. Both vars are pinned to a
    // known state for this test.
    unsafe {
        std::env::remove_var(ENV_RECALL_DENY_TAGS);
    }
    let (state, _data_dir_tmp, _project_dir_tmp, project_dir, slug, addr_handle) =
        spin_up_test_daemon_with_palace("prompt-ctx-deny-tags").await;

    // Three drawers, all mentioning "rust" so recall returns all three.
    // The first two carry the default deny tags and must be filtered;
    // their content is sized above the signal-filter threshold so the
    // remember path accepts them (the deny filter operates on tags,
    // not content length, so the body must be realistic).
    // The third has only signal tags and must survive.
    for (text, tags) in [
        (
            "user: how do I use rust async tokio runtime and serde derive macros in this project to glue an http handler to a kafka producer",
            vec!["claude-session", "user-prompt", "rust"],
        ),
        (
            "user: yes please go ahead and refactor the rust async producer module, this captured prompt fragment should never be surfaced",
            vec!["user-prompt", "rust"],
        ),
        (
            "Rust integration uses tokio for async tasks and serde for JSON",
            vec!["rust", "tokio"],
        ),
    ] {
        let tags_json: Vec<serde_json::Value> = tags.iter().map(|t| json!(t)).collect();
        let _ = crate::tools::dispatch_tool(
            &state,
            "memory_remember",
            json!({
                "palace": slug,
                "text": text,
                "room": "General",
                "tags": tags_json,
            }),
        )
        .await
        .expect("memory_remember");
    }

    let payload = json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project_dir.to_string_lossy(),
        "prompt": "how does rust integration work?"
    })
    .to_string();
    let body = build_injection_body(&payload).await;

    assert!(
        body.contains("tokio") && body.contains("serde"),
        "signal drawer must survive deny filter; got:\n{body}"
    );
    assert!(
        !body.contains("kafka producer"),
        "claude-session-tagged drawer must be filtered out; got:\n{body}"
    );
    assert!(
        !body.contains("captured prompt fragment"),
        "user-prompt-tagged drawer must be filtered out; got:\n{body}"
    );

    addr_handle.shutdown().await;
}

/// Why (issue #139): operators need to widen the deny list at runtime
/// without rebuilding the binary — e.g. when a palace accumulates a
/// project-specific synthetic tag. The env override
/// [`ENV_RECALL_DENY_TAGS`] supplies the comma-separated list.
/// What: set the env override to a custom tag, populate a palace
/// where the only recallable drawer carries that custom tag plus a
/// keyword shared with the prompt, assert the drawer is filtered out
/// and the body falls back to the global / empty placeholder path
/// (no `Relevant memories` section).
/// Test: itself.
/// Note (issue #226): gated on `axum-server`; spins up the HTTP daemon.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn prompt_context_recall_env_override_extends_deny_list() {
    let _guard = crate::commands::env_test_lock().lock().await;
    // SAFETY: env_test_lock serialises this section.
    unsafe {
        std::env::set_var(ENV_RECALL_DENY_TAGS, "noise-tag");
    }
    let (state, _data_dir_tmp, _project_dir_tmp, project_dir, slug, addr_handle) =
        spin_up_test_daemon_with_palace("prompt-ctx-env-deny").await;

    let _ = crate::tools::dispatch_tool(
        &state,
        "memory_remember",
        json!({
            "palace": slug,
            "text": "Rust integration uses tokio and serde for the async layer",
            "room": "General",
            "tags": ["noise-tag", "rust"],
        }),
    )
    .await
    .expect("memory_remember");

    let payload = json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project_dir.to_string_lossy(),
        "prompt": "how does rust integration work?"
    })
    .to_string();
    let body = build_injection_body(&payload).await;

    // The single drawer is filtered, so the body should NOT carry its
    // content. The empty-palace fallback (or the global facts path)
    // takes over.
    assert!(
        !body.contains("tokio and serde"),
        "noise-tag drawer must be filtered when env override targets it; got:\n{body}"
    );

    // Clean up the env override so it does not leak to sibling tests.
    // SAFETY: env_test_lock still held until DaemonHandle::shutdown.
    unsafe {
        std::env::remove_var(ENV_RECALL_DENY_TAGS);
    }
    addr_handle.shutdown().await;
}

/// Why (issue #139, regression): a palace consisting entirely of
/// deny-listed drawers must NOT crash the hook and must NOT inject a
/// `Relevant memories` section. The empty-palace fallback path (the
/// existing global hot-facts route from #136) must kick in instead.
/// What: populate a palace where every drawer carries a deny tag,
/// run the hook, assert the body is either the legacy placeholder OR
/// global-facts-only — crucially, it must not contain any of the
/// drawer content nor a `Relevant memories` section header.
/// Test: itself.
/// Note (issue #226): gated on `axum-server`; spins up the HTTP daemon.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn prompt_context_recall_all_filtered_falls_back_to_global() {
    let _guard = crate::commands::env_test_lock().lock().await;
    unsafe {
        std::env::remove_var(ENV_RECALL_DENY_TAGS);
    }
    let (state, _data_dir_tmp, _project_dir_tmp, project_dir, slug, addr_handle) =
        spin_up_test_daemon_with_palace("prompt-ctx-all-filtered").await;

    // Every drawer is deny-listed. Bodies are sized above the signal
    // filter threshold so memory_remember accepts them — the deny-tag
    // filter operates downstream on tags, not content length.
    for (text, tags) in [
        (
            "user: status update on the rust async rewrite, the kafka consumer should not surface in any prompt-context injection",
            vec!["claude-session", "user-prompt", "rust"],
        ),
        (
            "user: yes please continue with the rust refactor on the producer side, this prompt fragment must be filtered out of recall",
            vec!["claude-session", "rust"],
        ),
    ] {
        let tags_json: Vec<serde_json::Value> = tags.iter().map(|t| json!(t)).collect();
        let _ = crate::tools::dispatch_tool(
            &state,
            "memory_remember",
            json!({
                "palace": slug,
                "text": text,
                "room": "General",
                "tags": tags_json,
            }),
        )
        .await
        .expect("memory_remember");
    }

    let payload = json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project_dir.to_string_lossy(),
        "prompt": "tell me about rust"
    })
    .to_string();
    let body = build_injection_body(&payload).await;

    // No drawer content leaks through and no `Relevant memories`
    // section is rendered — either the global hot-facts section or
    // the empty-placeholder fallback wins.
    assert!(
        !body.contains("kafka consumer") && !body.contains("producer side"),
        "filtered drawer content must not leak; got:\n{body}"
    );
    assert!(
        !body.contains("Relevant memories"),
        "no `Relevant memories` section should render when every drawer is filtered; got:\n{body}"
    );

    addr_handle.shutdown().await;
}

/// Why (issue #105): even when the daemon is down, the hook must still
/// log an attempt entry so operators can see "prompt-context fired N
/// times but the daemon was unreachable" in the JSONL stream.
/// What: pin a tempdir as the data directory, run the handler with no
/// daemon, and assert exactly one log file landed under `<tmp>/logs/`
/// with a single JSONL line whose `injection_kind` is the prompt-context
/// kind. Calls `handle_prompt_context_with_payload` directly (issue
/// #2079) with a fixed empty payload so this test never spawns a real
/// blocking stdin read.
/// Test: itself.
#[tokio::test]
async fn prompt_context_logs_attempt_without_daemon() {
    let _guard = crate::commands::env_test_lock().lock().await;
    let tmp = tempfile::tempdir().expect("tempdir");
    unsafe {
        std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, tmp.path());
        std::env::remove_var(crate::prompt_log::ENV_ENABLED);
        std::env::remove_var(crate::prompt_log::ENV_DIR);
        std::env::remove_var(crate::prompt_log::ENV_HASH_PROMPTS);
    }
    let res = handle_prompt_context_with_payload(String::new()).await;
    let logs_dir = trusty_common::resolve_data_dir("trusty-memory")
        .expect("resolve data dir")
        .join("logs");
    unsafe {
        std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
    }
    assert!(res.is_ok());
    let files: Vec<_> = std::fs::read_dir(&logs_dir)
        .expect("logs dir should be created")
        .flatten()
        .map(|e| e.path())
        .filter(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.starts_with("enriched-prompts."))
        })
        .collect();
    assert_eq!(
        files.len(),
        1,
        "expected one enriched-prompts log file, got {files:?}"
    );
    let content = std::fs::read_to_string(&files[0]).expect("read log");
    let line = content.lines().next().expect("at least one line");
    let parsed: crate::prompt_log::PromptLogEntry =
        serde_json::from_str(line).expect("parse JSONL");
    assert_eq!(parsed.hook_type, "UserPromptSubmit");
    assert_eq!(parsed.injection_kind, "prompt-context-facts");
}

/// Why (issue #2043): [`bounded_blocking`] is the mechanism that keeps the
/// stdin read from ever hanging the hook. A real `std::io::Stdin` can't be
/// swapped in-process, so this test drives the exact same
/// `spawn_blocking` + `timeout` mechanism with a synthetic closure that
/// sleeps past the deadline, proving the caller gets control back on time
/// with a `None` (fail-open) result rather than waiting for the closure.
/// What: races a closure that sleeps 400 ms against a 100 ms deadline;
/// asserts `None` is returned and wall time stays close to the deadline,
/// not the closure's sleep duration. The 400 ms sleep (rather than
/// something longer) is deliberate: `tokio::test`'s per-test `Runtime`
/// still waits for this abandoned blocking thread to finish during its
/// own teardown (blocking-pool threads cannot be cancelled — this is the
/// same reason `main.rs` calls `std::process::exit` after the
/// `prompt-context` dispatch instead of returning normally), so the test
/// itself pays that thread's full sleep as wall-clock tax regardless of
/// the assertion below. Kept short to bound that tax.
/// Test: itself.
#[tokio::test]
async fn bounded_blocking_times_out_on_slow_closure() {
    let start = std::time::Instant::now();
    let result: Option<String> = bounded_blocking(
        || {
            std::thread::sleep(std::time::Duration::from_millis(400));
            "too-late".to_string()
        },
        std::time::Duration::from_millis(100),
    )
    .await;
    let elapsed = start.elapsed();
    assert_eq!(result, None, "slow closure must fail open to None");
    assert!(
        elapsed < std::time::Duration::from_millis(300),
        "bounded_blocking did not return promptly: elapsed={elapsed:?}"
    );
}

/// Why (issue #2043): the deadline mechanism must not clip a value that
/// finishes comfortably within budget — only genuinely slow closures
/// should fail open.
/// What: races an instantly-returning closure against a 300 ms deadline;
/// asserts the real value comes back.
/// Test: itself.
#[tokio::test]
async fn bounded_blocking_returns_value_when_fast_enough() {
    let result =
        bounded_blocking(|| "fast".to_string(), std::time::Duration::from_millis(300)).await;
    assert_eq!(result, Some("fast".to_string()));
}

/// Why (issue #2043): proves the end-to-end fix — before this issue, a
/// daemon that accepted a connection but never answered could block
/// `handle_prompt_context` for as long as the daemon took (bounded only by
/// Claude Code's own ~15 s hook ceiling, which is exactly the hang this
/// issue reports). This test stands up a real HTTP listener that accepts
/// every request and sleeps 5 s before responding — far longer than
/// [`BODY_DEADLINE`] + [`EMIT_DEADLINE`] — and asserts the hook still
/// returns `Ok(())` well inside its own deadline budget.
/// What: writes the slow listener's address as the discovered daemon addr
/// (via `write_daemon_addr`, matching what a real running daemon would
/// have written), runs `handle_prompt_context_with_payload` (issue #2079 —
/// direct call with a fixed empty payload so this test never spawns a
/// real blocking stdin read), and asserts both the `Ok(())` contract and
/// a bounded wall-clock time.
/// Test: itself.
/// Note (issue #226): gated on `axum-server` — it needs a real `axum`
/// listener to simulate the slow daemon.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn handle_prompt_context_fails_open_on_slow_daemon() {
    let _guard = crate::commands::env_test_lock().lock().await;
    let tmp = tempfile::tempdir().expect("tempdir");
    unsafe {
        std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, tmp.path());
        std::env::remove_var(crate::prompt_log::ENV_ENABLED);
        std::env::remove_var(crate::prompt_log::ENV_DIR);
        std::env::remove_var(crate::prompt_log::ENV_HASH_PROMPTS);
    }

    async fn slow_handler() -> &'static str {
        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
        "slow"
    }
    let app = axum::Router::new().fallback(axum::routing::any(slow_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind 127.0.0.1:0");
    let addr = listener.local_addr().expect("local_addr");
    let server = tokio::spawn(async move {
        let _ = axum::serve(listener, app).await;
    });
    trusty_common::write_daemon_addr("trusty-memory", &addr.to_string())
        .expect("write fake daemon addr");

    let start = std::time::Instant::now();
    let res = handle_prompt_context_with_payload(String::new()).await;
    let elapsed = start.elapsed();

    server.abort();
    unsafe {
        std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
    }

    assert!(
        res.is_ok(),
        "must fail open even with a stalled daemon, got {res:?}"
    );
    let budget = BODY_DEADLINE + EMIT_DEADLINE + std::time::Duration::from_millis(750);
    assert!(
        elapsed < budget,
        "handle_prompt_context took {elapsed:?}, expected under budget {budget:?} \
         (a stalled daemon must never make the hook wait out its own timeout)"
    );
}

/// Why (issue #5038, symptom 1): `memory_remember` stamps every drawer with the
/// reserved `creator:*` namespace — `creator:cwd` alone is a ~90-character
/// absolute path — and the injection rendered all of it. Over 17,176 real
/// firings those tags are 33.4% of every tag byte injected. They tell a model
/// nothing about what the drawer says.
/// What: a drawer carrying provenance tags among topical ones through
/// `render_tags`; asserts no `creator:` survives and the topical tags do.
/// Test: itself.
#[test]
fn injection_drops_provenance_tags() {
    use format::render_tags;
    let tags: Vec<String> = [
        "rust",
        "creator:client=trusty-memory-mcp",
        "tokio",
        "creator:version=0.21.2",
        "creator:source=mcp",
        "creator:cwd=/Users/masa/trusty-mpm-projects/bobmatnyc/trusty-tools/.base",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    let rendered = render_tags(&tags).expect("topical tags must still render");
    assert!(
        !rendered.contains("creator:"),
        "provenance must not reach the injection; got: {rendered}"
    );
    assert!(
        rendered.contains("`rust`") && rendered.contains("`tokio`"),
        "topical tags must survive; got: {rendered}"
    );

    // A drawer whose only tags are provenance renders no suffix at all — 2.8%
    // of drawers in the corpus were exactly this shape.
    let only_provenance: Vec<String> = tags
        .iter()
        .filter(|t| t.starts_with("creator:"))
        .cloned()
        .collect();
    assert_eq!(
        render_tags(&only_provenance),
        None,
        "an all-provenance tag list must render nothing, not an empty suffix"
    );
}

/// Why (issue #5038, symptom 2): tag lists rendered in full, uncapped — the
/// median drawer carried 17 tags and the `_(tags: …)_` suffix was 53.0% of
/// every byte the hook injected, outweighing the content preview it labels on
/// 82.3% of drawers.
/// What: a 12-tag drawer through `render_tags`; asserts exactly
/// `MAX_RENDERED_TAGS` render, the surplus is announced rather than dropped
/// silently, and the whole suffix stays under the content budget the cap was
/// chosen against.
/// Test: itself.
#[test]
fn injection_caps_rendered_tag_count() {
    use format::{render_tags, MAX_RENDERED_TAGS};
    // Realistic tag lengths, not `topic-N`. These are the shapes the live
    // palace actually stores — the 7-character fixture this test used to carry
    // could not have caught the byte-budget hole the #5038 review found.
    let tags: Vec<String> = [
        "slate-prioritization-in-flight",
        "trusty-search-reinstall-in-flight",
        "standing-instruction",
        "session-2eb72dca",
        "resume-target",
        "issue-2833",
        "bob-decision",
        "trusty-mpm",
        "status",
        "kg",
        "redb",
        "python",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    let rendered = render_tags(&tags).expect("tags must render");
    let shown = rendered.matches('`').count() / 2;
    assert!(
        shown <= MAX_RENDERED_TAGS,
        "at most MAX_RENDERED_TAGS tags may render; got {shown}: {rendered}"
    );
    assert!(
        rendered.contains(&format!("+{} more", tags.len() - shown)),
        "held-back tags must be announced, not dropped silently; got: {rendered}"
    );
    assert!(
        !rendered.contains("python"),
        "the tail of the tag list must not render; got: {rendered}"
    );
}

/// Why (#5038 review): `MAX_RENDERED_TAGS` is argued from "a label must never
/// outweigh the payload it labels" but enforces a *count*, and a count cannot
/// bound bytes — four 55-character tags blow a 220-character budget while
/// satisfying the cap. The old test used 7-character `topic-N` fixtures, so its
/// length assertion could never fail no matter how wrong the cap was.
/// What: four tags of 55 characters each — well inside the count cap, well past
/// the char budget. Asserts the rendered suffix stays within
/// `MAX_RENDERED_TAG_CHARS`, that fewer than the count cap render as a result,
/// and that the ones dropped for length are still announced.
/// Test: itself.
#[test]
fn injection_caps_rendered_tag_bytes() {
    use format::{render_tags, MAX_RENDERED_TAGS, MAX_RENDERED_TAG_CHARS};
    const TAG_CHARS: usize = 55;
    let long: Vec<String> = (0..4)
        .map(|i| {
            let stem = format!("workstream-{i}-");
            format!("{stem}{}", "x".repeat(TAG_CHARS - stem.chars().count()))
        })
        .collect();
    assert_eq!(
        long[0].chars().count(),
        TAG_CHARS,
        "fixture must be 55 chars"
    );
    let rendered = render_tags(&long).expect("tags must render");
    assert!(
        rendered.chars().count() <= MAX_RENDERED_TAG_CHARS,
        "the tag label must stay inside its {MAX_RENDERED_TAG_CHARS}-char budget; \
         got {} chars: {rendered}",
        rendered.chars().count()
    );
    let shown = rendered.matches('`').count() / 2;
    assert!(
        shown < MAX_RENDERED_TAGS,
        "with 55-char tags the byte budget must bind before the count cap; \
         got {shown} tags: {rendered}"
    );
    assert!(
        rendered.contains(&format!("+{} more", long.len() - shown)),
        "tags held back for length must be announced too; got: {rendered}"
    );

    // The deliberate exception: one tag longer than the whole budget still
    // renders, because `_(tags: +1 more)_` communicates strictly less.
    let huge = vec![format!("w-{}", "y".repeat(400))];
    let rendered = render_tags(&huge).expect("a single oversized tag still renders");
    assert!(
        rendered.contains(&huge[0]),
        "the lone tag must survive whole"
    );
}

/// Why (issue #5038, end to end): the unit tests above pin `render_tags` in
/// isolation. This one proves the whole chain — real MCP write path stamping
/// `creator:*`, real HTTP recall, real composition — never puts provenance or
/// an uncapped tag list into what Claude Code actually receives.
/// What: seeds a palace through `memory_remember` (which attaches the
/// attribution namespace exactly as production does) with drawers carrying more
/// topical tags than the cap, recalls with a matching prompt, and asserts the
/// rendered injection carries no `creator:` and no bullet over the cap.
/// Test: itself.
/// Note (issue #226): gated on `axum-server`; spins up the HTTP daemon.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn prompt_context_injection_has_no_provenance_tags() {
    use format::MAX_RENDERED_TAGS;
    let _guard = crate::commands::env_test_lock().lock().await;
    unsafe {
        std::env::remove_var(ENV_MIN_SCORE);
        std::env::remove_var(ENV_RECALL_DENY_TAGS);
    }
    let (state, _data_dir_tmp, _project_dir_tmp, project_dir, slug, addr_handle) =
        spin_up_test_daemon_with_palace("prompt-ctx-tag-render").await;

    for (text, tags) in [
        (
            "Rust integration uses tokio for async tasks and serde for JSON encoding",
            vec![
                "rust", "tokio", "serde", "async", "json", "encoding", "runtime", "crate",
            ],
        ),
        (
            "Rust error handling prefers thiserror in libraries and anyhow in binaries",
            vec![
                "rust",
                "thiserror",
                "anyhow",
                "errors",
                "libraries",
                "binaries",
                "convention",
            ],
        ),
    ] {
        let tags_json: Vec<serde_json::Value> = tags.iter().map(|t| json!(t)).collect();
        let _ = crate::tools::dispatch_tool(
            &state,
            "memory_remember",
            json!({
                "palace": slug,
                "text": text,
                "room": "General",
                "tags": tags_json,
            }),
        )
        .await
        .expect("memory_remember");
    }

    let payload = json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project_dir.to_string_lossy(),
        "prompt": "how does rust integration work with tokio and serde?"
    })
    .to_string();
    let body = build_injection_body(&payload).await;

    assert_ne!(
        body, EMPTY_PLACEHOLDER,
        "fixture must actually recall something for this test to mean anything"
    );
    assert!(
        body.contains("_(tags:"),
        "fixture must render a tag suffix for this test to mean anything; got:\n{body}"
    );
    assert!(
        !body.contains("creator:"),
        "no provenance tag may reach the injection; got:\n{body}"
    );
    for bullet in body.lines().filter(|l| l.contains("_(tags:")) {
        let shown = bullet
            .split("_(tags:")
            .nth(1)
            .map(|suffix| suffix.matches('`').count() / 2)
            .unwrap_or(0);
        assert!(
            shown <= MAX_RENDERED_TAGS,
            "bullet renders {shown} tags, over the cap of {MAX_RENDERED_TAGS}: {bullet}"
        );
    }

    addr_handle.shutdown().await;
}

/// Why (issue #4972, end to end): the unit tests in `query` pin the shaping in
/// isolation. This one proves the metric survives the whole hook — an
/// over-window `<task-notification>` prompt must reach `/recall` reshaped and
/// leave a record of it on the enriched-prompt log line, which is the same
/// corpus the 52%-over-window rate was measured from. Before this change the
/// embedder cut the query at token 512 and nothing anywhere recorded it.
/// What: fires the hook with a 22 KB envelope-wrapped prompt, then parses the
/// JSONL log and asserts `recall_query` reports an over-budget original, a
/// within-budget send, a stripped envelope, and a non-zero dropped-unit count.
/// Test: itself.
/// Note (issue #226): gated on `axum-server`; spins up the HTTP daemon.
#[cfg(feature = "axum-server")]
#[tokio::test]
async fn prompt_context_logs_recall_query_shape() {
    let _guard = crate::commands::env_test_lock().lock().await;
    unsafe {
        std::env::remove_var(ENV_MIN_SCORE);
        std::env::remove_var(super::query::ENV_QUERY_TOKEN_BUDGET);
    }
    let (state, _data_dir_tmp, _project_dir_tmp, project_dir, slug, addr_handle) =
        spin_up_test_daemon_with_palace("prompt-ctx-query-shape").await;
    let _ = crate::tools::dispatch_tool(
        &state,
        "memory_remember",
        json!({
            "palace": slug,
            "text": "Rust integration uses tokio for async tasks and serde for JSON encoding",
            "room": "General",
            "tags": [json!("rust")],
        }),
    )
    .await
    .expect("memory_remember");

    // The exact shape 65.3% of logged hook prompts arrive in: a machine
    // envelope whose head is task ids and absolute paths, wrapping a long
    // agent report.
    let long_result = "The retrieval relevance floor interacts with the top_k cap.\n".repeat(400);
    let prompt = format!(
        "<task-notification>\n\
         <task-id>a23c46a0439fa7881</task-id>\n\
         <tool-use-id>toolu_01PvoC76SpHX65DVbJi7sPes</tool-use-id>\n\
         <output-file>/private/tmp/claude-502/-Users-masa-projects/tasks/a23.output</output-file>\n\
         <status>completed</status>\n\
         <summary>Agent \"rust integration\" finished</summary>\n\
         <result>{long_result}</result>\n\
         </task-notification>"
    );
    assert!(prompt.len() > 20_000, "fixture must be far past the window");

    let payload = json!({
        "hook_event_name": "UserPromptSubmit",
        "cwd": project_dir.to_string_lossy(),
        "prompt": prompt,
    })
    .to_string();
    let _ = build_injection_body(&payload).await;

    let logs_dir = trusty_common::resolve_data_dir("trusty-memory")
        .expect("resolve data dir")
        .join("logs");
    let log_file = std::fs::read_dir(&logs_dir)
        .expect("logs dir")
        .flatten()
        .map(|e| e.path())
        .find(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.starts_with("enriched-prompts."))
        })
        .expect("an enriched-prompts log file");
    let content = std::fs::read_to_string(&log_file).expect("read log");
    let entry: crate::prompt_log::PromptLogEntry = content
        .lines()
        .filter_map(|l| serde_json::from_str::<crate::prompt_log::PromptLogEntry>(l).ok())
        .next_back()
        .expect("at least one parseable log line");

    let shape = entry
        .recall_query
        .expect("an over-window query must leave a shape record, not truncate silently");
    assert!(
        shape.original_tokens > shape.budget_tokens,
        "fixture must exceed the budget; got {shape:?}"
    );
    assert!(
        shape.sent_tokens <= shape.budget_tokens,
        "the query sent to the embedder must fit its window; got {shape:?}"
    );
    assert!(
        shape.envelope_stripped,
        "the task-notification envelope must be stripped; got {shape:?}"
    );
    assert!(
        shape.units_dropped > 0 && shape.reshaped(),
        "the reduction must be recorded, not silent; got {shape:?}"
    );

    addr_handle.shutdown().await;
}