lean-ctx 3.11.4

LeanCTX Engine: the open-source runtime for the Context Gateway for AI Systems. CLI, MCP server, and supported proxy integrations.
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
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
#[allow(clippy::wildcard_imports)]
use super::super::*;
use super::{finalize_call_result, roots_list_failure_is_permanent};

/// Community regression (3.9.19): every documented lossless escape hatch was
/// ignored — triage ran after the compression pipeline, so per-call
/// parameters never reached it. These pins guarantee the bypass contract
/// stays wired at the dispatch chokepoint.
mod rules_self_heal_status_tests {
    use super::super::outcome::append_rules_self_heal_status;

    #[test]
    fn failed_rule_write_must_not_claim_auto_updated() {
        let failed = crate::rules_inject::InjectResult {
            errors: vec!["Cursor: simulated write failure".to_string()],
            ..Default::default()
        };

        let result = append_rules_self_heal_status("tool output".to_string(), Some(&failed));

        assert!(
            !result.contains("[RULES AUTO-UPDATED]"),
            "a failed rules write must never be reported as successfully refreshed, got: {result}"
        );
    }

    #[test]
    fn successful_rule_write_claims_auto_updated() {
        let updated = crate::rules_inject::InjectResult {
            updated: vec!["Cursor".to_string()],
            ..Default::default()
        };

        let result = append_rules_self_heal_status("tool output".to_string(), Some(&updated));

        assert!(
            result.contains("[RULES AUTO-UPDATED]"),
            "a successful rules rewrite must retain the existing success notice, got: {result}"
        );
    }

    #[test]
    fn already_current_rules_do_not_claim_auto_updated() {
        let already = crate::rules_inject::InjectResult {
            already: vec!["Cursor".to_string()],
            ..Default::default()
        };

        let result = append_rules_self_heal_status("tool output".to_string(), Some(&already));

        assert!(
            !result.contains("[RULES AUTO-UPDATED]"),
            "AlreadyPresent is not a write and must not be described as one, got: {result}"
        );
    }

    #[test]
    fn missing_heal_result_does_not_claim_auto_updated() {
        let result = append_rules_self_heal_status("tool output".to_string(), None);

        assert!(
            !result.contains("[RULES AUTO-UPDATED]"),
            "missing home or a failed blocking task must not be reported as a successful rewrite, got: {result}"
        );
    }

    #[test]
    fn partial_rule_write_failure_must_not_claim_auto_updated() {
        let heal_result = crate::rules_inject::InjectResult {
            updated: vec!["Cursor".to_string()],
            errors: vec!["OpenCode: simulated write failure".to_string()],
            ..Default::default()
        };

        let output =
            append_rules_self_heal_status("original result".to_string(), Some(&heal_result));

        assert_eq!(output, "original result");
        assert!(!output.contains("[RULES AUTO-UPDATED]"));
    }
}
mod triage_bypass_tests {
    use super::super::pipeline::triage_bypass_requested;

    fn args(json: &serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        json.as_object().expect("test args are an object").clone()
    }

    #[test]
    fn ctx_read_is_always_exempt() {
        // ctx_read delivers file content agents edit against — and its cache
        // marks content as fully delivered BEFORE the pipeline runs, so any
        // post-hoc filtering silently corrupts the dedup contract ("full
        // content already in this conversation" after a stripped delivery).
        assert!(triage_bypass_requested("ctx_read", None));
        assert!(triage_bypass_requested(
            "ctx_read",
            Some(&args(&serde_json::json!({"path": "src/identity.rs"})))
        ));
    }

    #[test]
    fn documented_lossless_escape_hatches_bypass_triage() {
        for a in [
            serde_json::json!({"raw": true}),
            serde_json::json!({"mode": "raw"}),
            serde_json::json!({"mode": "full"}),
            serde_json::json!({"mode": "full-compact"}),
            serde_json::json!({"mode": "lines:32-33"}),
            serde_json::json!({"mode": "anchored:1-10"}),
            serde_json::json!({"mode": "diff"}),
            serde_json::json!({"aggressiveness": 0.0}),
            serde_json::json!({"fresh": true}),
        ] {
            assert!(
                triage_bypass_requested("ctx_shell", Some(&args(&a))),
                "escape hatch must bypass triage: {a}"
            );
        }
    }

    #[test]
    fn plain_calls_remain_subject_to_the_level_gate() {
        assert!(!triage_bypass_requested(
            "ctx_shell",
            Some(&args(&serde_json::json!({"command": "git status"})))
        ));
        assert!(!triage_bypass_requested("ctx_search", None));
    }
}

mod shell_outcome_tests {
    use super::*;
    // GH #2005; lives in `call_tool/tests/shell_outcome_tests/`.
    #[cfg(not(windows))]
    mod expand_unpolled;
    #[cfg(not(windows))]
    use crate::server::call_tool::dispatch_and_post_process;
    use crate::server::tool_trait::{McpTool, ShellOutcome, ToolContext};

    #[cfg(not(windows))]
    struct ScopedEnvVar {
        key: &'static str,
        previous: Option<std::ffi::OsString>,
    }

    #[cfg(not(windows))]
    impl ScopedEnvVar {
        fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
            let previous = std::env::var_os(key);
            crate::test_env::set_var(key, value);
            Self { key, previous }
        }
    }

    #[cfg(not(windows))]
    impl Drop for ScopedEnvVar {
        fn drop(&mut self) {
            if let Some(previous) = &self.previous {
                crate::test_env::set_var(self.key, previous);
            } else {
                crate::test_env::remove_var(self.key);
            }
        }
    }

    #[cfg(not(windows))]
    struct ScopedPolicy {
        _override: crate::core::policy::runtime::TestPolicyOverride,
    }

    #[cfg(not(windows))]
    impl ScopedPolicy {
        fn redacting(label: &str, pattern: &str) -> Self {
            let mut redaction = std::collections::BTreeMap::new();
            redaction.insert(label.to_string(), pattern.to_string());
            Self {
                _override: crate::core::policy::runtime::TestPolicyOverride::set(Some(
                    crate::core::policy::ResolvedPolicy {
                        name: "mes1609-test-policy".into(),
                        version: "1.0.0".into(),
                        description: "MES-1609 archive chokepoint regression".into(),
                        chain: vec![],
                        default_read_mode: None,
                        allow_tools: None,
                        deny_tools: vec![],
                        max_context_tokens: None,
                        audit_retention_days: None,
                        redaction,
                        filters: crate::core::policy::FilterRules {
                            pii: Some("redact".into()),
                            ..crate::core::policy::FilterRules::default()
                        },
                        egress: crate::core::policy::EgressRules::default(),
                        routing: crate::core::policy::RoutingPolicyRules::default(),
                        budgets: crate::core::policy::BudgetRules::default(),
                    },
                )),
            }
        }
    }

    #[cfg(not(windows))]
    struct BackgroundJobGuard {
        job_id: String,
    }

    #[cfg(not(windows))]
    impl BackgroundJobGuard {
        fn new(job_id: String) -> Self {
            Self { job_id }
        }
    }

    #[cfg(not(windows))]
    impl Drop for BackgroundJobGuard {
        fn drop(&mut self) {
            let _ = crate::server::background_shell::cancel(&self.job_id);
            for _ in 0..120 {
                if !matches!(
                    crate::server::background_shell::status(&self.job_id),
                    Some(crate::server::background_shell::JobState::Running { .. })
                ) {
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(25));
            }
            crate::server::background_shell::remove_for_test(&self.job_id);
        }
    }

    /// Wait until a background job has completed, and say why when it has not.
    ///
    /// The callers used to poll for a bare 6–10 s and then assert
    /// `matches!(status, Some(Completed))`. On a loaded ubuntu runner three
    /// trivial `printf | yes | head` jobs missed that window one after the
    /// other (PR #1995), and the assertion could not tell a slow job from one
    /// that was cancelled or pruned away. The ceiling only costs time when the
    /// job really is stuck; the panic names the state that was observed.
    #[cfg(not(windows))]
    fn wait_for_completed(job_id: &str) {
        use crate::server::background_shell::JobState;
        const CEILING: std::time::Duration = std::time::Duration::from_mins(1);
        let deadline = std::time::Instant::now() + CEILING;
        loop {
            let state = crate::server::background_shell::status(job_id);
            match &state {
                Some(JobState::Completed { .. }) => return,
                Some(JobState::Cancelled { output }) => {
                    panic!("job {job_id} was cancelled instead of completing: {output:?}")
                }
                _ if std::time::Instant::now() >= deadline => {
                    let observed = match state {
                        None => "gone from the job table (removed or pruned)".to_string(),
                        Some(JobState::Running { output }) => {
                            let tail: String = output.chars().rev().take(200).collect();
                            let tail: String = tail.chars().rev().collect();
                            format!(
                                "still running, {} bytes captured, tail {tail:?}",
                                output.len()
                            )
                        }
                        Some(other) => format!("{other:?}"),
                    };
                    panic!("job {job_id} did not complete within {CEILING:?}: {observed}");
                }
                _ => std::thread::sleep(std::time::Duration::from_millis(25)),
            }
        }
    }

    fn text_of(result: &CallToolResult) -> String {
        result
            .content
            .first()
            .and_then(|c| c.as_text())
            .map(|t| t.text.clone())
            .unwrap_or_default()
    }

    #[cfg(not(windows))]
    fn launched_job_guard(result: &CallToolResult) -> BackgroundJobGuard {
        let structured_id = result
            .structured_content
            .as_ref()
            .and_then(|value| value["jobId"].as_str());
        let text = text_of(result);
        let text_id = text
            .strip_prefix('[')
            .and_then(|value| value.split_once(':'))
            .and_then(|(_, value)| value.split_whitespace().next());
        BackgroundJobGuard::new(
            structured_id
                .or(text_id)
                .expect("background launch must expose a job id")
                .to_string(),
        )
    }

    /// Drive a command through the auto-detach path *deterministically*.
    ///
    /// The 10 ms foreground window used to be held open by the caller's own
    /// `sleep 0.1`, which assumes the child is spawned, scheduled and still
    /// running 10 ms later. On a loaded macOS runner that assumption broke and
    /// the helper panicked with "the reproduction must exercise the
    /// auto-detached path" — a flake in the harness, not a defect in the code
    /// under test. The child now blocks on a barrier file until the test
    /// releases it, exactly like `auto_detached_pipeline_result` below, so the
    /// detach is guaranteed no matter how the runner schedules us.
    #[cfg(not(windows))]
    fn auto_detached_result(command: &str) -> CallToolResult {
        let release_dir = tempfile::tempdir().expect("create auto-detach barrier directory");
        let release_path = release_dir.path().join("release");
        let mut extra_env = std::collections::HashMap::new();
        extra_env.insert(
            "LCTX_TEST_RELEASE_PATH".to_string(),
            release_path.to_string_lossy().into_owned(),
        );
        let guarded_command =
            format!("while [ ! -e \"$LCTX_TEST_RELEASE_PATH\" ]; do sleep 0.01; done; {command}");
        let detached = crate::server::background_shell::run_foreground_or_detach(
            guarded_command,
            ".".to_string(),
            extra_env,
            Some(10_000),
            std::time::Duration::from_millis(10),
            None,
            None,
        );
        let job_id = match detached {
            crate::server::background_shell::ForegroundResult::Detached { job_id } => job_id,
            // Diagnostic on purpose: if this ever fires on CI we need to see
            // *why* the child never reached the soft cap. A failed spawn or a
            // missing `sleep` shows up here as an exit code and a shell error
            // rather than as an unexplained timing story.
            crate::server::background_shell::ForegroundResult::Finished { output, exit_code } => {
                panic!(
                    "the reproduction must exercise the auto-detached path; the child \
                     finished inside the soft cap instead (exit {exit_code}): {output}"
                )
            }
        };
        let _job = BackgroundJobGuard::new(job_id.clone());
        std::fs::write(&release_path, b"release").expect("release auto-detached child");

        let mut terminal = false;
        for _ in 0..240 {
            if matches!(
                crate::server::background_shell::status(&job_id),
                Some(
                    crate::server::background_shell::JobState::Completed { .. }
                        | crate::server::background_shell::JobState::Cancelled { .. }
                )
            ) {
                terminal = true;
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
        assert!(
            terminal,
            "auto-detached child did not reach a terminal state"
        );

        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("status"));
        args.insert("job_id".to_string(), serde_json::json!(job_id));
        let output = crate::tools::registered::ctx_shell::CtxShellTool
            .handle(&args, &ToolContext::default())
            .expect("status must return a tool result");
        finalize_call_result(&output.text, output.shell_outcome)
    }

    #[cfg(not(windows))]
    async fn auto_detached_pipeline_result(command: &str) -> (CallToolResult, BackgroundJobGuard) {
        let release_dir = tempfile::tempdir().expect("create auto-detach barrier directory");
        let release_path = release_dir.path().join("release");
        let mut extra_env = std::collections::HashMap::new();
        extra_env.insert(
            "LCTX_TEST_RELEASE_PATH".to_string(),
            release_path.to_string_lossy().into_owned(),
        );
        let guarded_command =
            format!("while [ ! -e \"$LCTX_TEST_RELEASE_PATH\" ]; do sleep 0.01; done; {command}");
        let detached = crate::server::background_shell::run_foreground_or_detach(
            guarded_command,
            ".".to_string(),
            extra_env,
            Some(30_000),
            std::time::Duration::from_millis(10),
            None,
            None,
        );
        let job_id = match detached {
            crate::server::background_shell::ForegroundResult::Detached { job_id } => job_id,
            // Diagnostic on purpose: if this ever fires on CI we need to see
            // *why* the child never reached the soft cap. A failed spawn or a
            // missing `sleep` shows up here as an exit code and a shell error
            // rather than as an unexplained timing story.
            crate::server::background_shell::ForegroundResult::Finished { output, exit_code } => {
                panic!(
                    "the reproduction must exercise the auto-detached path; the child \
                     finished inside the soft cap instead (exit {exit_code}): {output}"
                )
            }
        };
        let job = BackgroundJobGuard::new(job_id.clone());
        std::fs::write(release_path, b"release").expect("release auto-detached child");
        wait_for_completed(&job_id);
        (
            pipeline_background_status(&job_id, false, false, false).await,
            job,
        )
    }

    #[cfg(not(windows))]
    fn structured_of(result: &CallToolResult) -> &serde_json::Value {
        result
            .structured_content
            .as_ref()
            .expect("background status must expose structuredContent")
    }

    #[cfg(not(windows))]
    fn auto_detached_running_result() -> CallToolResult {
        let detached = crate::server::background_shell::run_foreground_or_detach(
            "sleep 2 # MES1609_RUNNING_STATUS".to_string(),
            ".".to_string(),
            std::collections::HashMap::default(),
            Some(10_000),
            std::time::Duration::from_millis(10),
            None,
            None,
        );
        let job_id = match detached {
            crate::server::background_shell::ForegroundResult::Detached { job_id } => job_id,
            // Diagnostic on purpose: if this ever fires on CI we need to see
            // *why* the child never reached the soft cap. A failed spawn or a
            // missing `sleep` shows up here as an exit code and a shell error
            // rather than as an unexplained timing story.
            crate::server::background_shell::ForegroundResult::Finished { output, exit_code } => {
                panic!(
                    "the reproduction must exercise the auto-detached path; the child \
                     finished inside the soft cap instead (exit {exit_code}): {output}"
                )
            }
        };
        let _job = BackgroundJobGuard::new(job_id.clone());

        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("status"));
        args.insert("job_id".to_string(), serde_json::json!(job_id));
        let output = crate::tools::registered::ctx_shell::CtxShellTool
            .handle(&args, &ToolContext::default())
            .expect("status must return a tool result");
        finalize_call_result(&output.text, output.shell_outcome)
    }

    #[cfg(not(windows))]
    fn shell_context() -> ToolContext {
        // #1778: a compile-time constant, not the process cwd. These tests only
        // need *some* real directory, but `std::env::current_dir()` is
        // process-global and other tests mutate it via `set_current_dir`, so
        // reading it here raced with them under `cargo test`'s parallelism.
        let cwd = env!("CARGO_MANIFEST_DIR").to_string();
        let mut session = crate::core::session::SessionState::new();
        session.project_root = Some(cwd.clone());
        session.shell_cwd = Some(cwd.clone());
        ToolContext {
            project_root: cwd,
            session: Some(std::sync::Arc::new(tokio::sync::RwLock::new(session))),
            ..ToolContext::default()
        }
    }

    #[cfg(not(windows))]
    fn completed_background_job(command: &str) -> (String, BackgroundJobGuard) {
        let job_id = crate::server::background_shell::start(
            command.to_string(),
            ".".to_string(),
            std::collections::HashMap::default(),
            Some(30_000),
        );
        let job = BackgroundJobGuard::new(job_id.clone());
        wait_for_completed(&job_id);
        (job_id, job)
    }

    #[cfg(not(windows))]
    async fn pipeline_background_status(
        job_id: &str,
        minimal: bool,
        raw: bool,
        inline: bool,
    ) -> CallToolResult {
        // #1778: compile-time constant, not the process-global cwd (see
        // `shell_context` above).
        let root = env!("CARGO_MANIFEST_DIR").to_string();
        let server = crate::tools::LeanCtxServer::new_with_project_root(Some(&root));
        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("status"));
        args.insert("job_id".to_string(), serde_json::json!(job_id));
        if raw {
            args.insert("raw".to_string(), serde_json::json!(true));
        }
        if inline {
            args.insert("inline".to_string(), serde_json::json!(true));
        }
        dispatch_and_post_process(
            &server,
            "ctx_shell",
            Some(&args),
            minimal,
            crate::core::config::Config::load_arc(),
            false,
            None,
            None,
            format!("mes1609_pipeline_{job_id}"),
            None,
        )
        .await
        .expect("background status pipeline must succeed")
    }

    fn call_shell(
        args: &serde_json::Map<String, serde_json::Value>,
        ctx: &ToolContext,
    ) -> CallToolResult {
        let output = crate::tools::registered::ctx_shell::CtxShellTool
            .handle(args, ctx)
            .expect("ctx_shell must return a tool result");
        finalize_call_result(&output.text, output.shell_outcome)
    }

    #[test]
    fn success_exit_is_not_an_error() {
        let r = finalize_call_result("ok", Some(ShellOutcome::Exit(0)));
        assert_ne!(r.is_error, Some(true), "exit 0 must not set isError");
        assert!(
            r.structured_content.is_none(),
            "happy path stays token-neutral: no structuredContent on exit 0"
        );
        assert_eq!(text_of(&r), "ok");
    }

    #[test]
    fn nonzero_exit_with_output_is_not_error() {
        // #1090: exit 1 with command output (before [exit:] footer) is NOT
        // a tool error — grep/diff/test exit 1 with results is normal.
        let r = finalize_call_result("boom\n[exit:1]", Some(ShellOutcome::Exit(1)));
        assert_ne!(
            r.is_error,
            Some(true),
            "exit 1 with output must NOT set isError (#1090)"
        );
        // #1127: and it must carry no structuredContent either — clients that
        // prefer it would render `{"exitCode":1}` and drop the output.
        assert!(
            r.structured_content.is_none(),
            "benign exit 1 must not shadow its output with structuredContent (#1127)"
        );
        assert_eq!(text_of(&r), "boom\n[exit:1]", "output text is preserved");
    }

    #[test]
    fn stderr_only_failure_keeps_its_text() {
        // #1127: `ls /nonexistent` writes only to stderr and exits 1. The text
        // block is the sole carrier of the diagnostic, so it must survive.
        let text = "ls: /nonexistent-path-xyz: No such file or directory\n[exit:1]";
        let r = finalize_call_result(text, Some(ShellOutcome::Exit(1)));
        assert_ne!(r.is_error, Some(true));
        assert!(r.structured_content.is_none());
        assert_eq!(text_of(&r), text);
    }

    #[test]
    fn timeout_with_partial_output_keeps_its_text() {
        // #1086/#1127: same shape for exit 124 — partial output is a success
        // result, so structuredContent must not displace it.
        let text = "line one\nERROR: command timed out after 5000ms";
        let r = finalize_call_result(text, Some(ShellOutcome::Exit(124)));
        assert_ne!(r.is_error, Some(true));
        assert!(r.structured_content.is_none());
        assert_eq!(text_of(&r), text);
    }

    #[test]
    fn exit_1_without_output_is_error() {
        // Exit 1 with only the [exit:] footer (no command output) IS an error.
        let r = finalize_call_result("[exit:1]", Some(ShellOutcome::Exit(1)));
        assert_eq!(
            r.is_error,
            Some(true),
            "exit 1 with no command output must set isError"
        );
    }

    /// MES-1609: once a foreground command auto-detaches, its terminal
    /// failure is a job verdict, not grep-like output that may use exit 1 as
    /// data. The MCP result must therefore keep both state and exit code.
    #[test]
    #[cfg(not(windows))]
    fn auto_detached_exit_1_is_a_structured_failed_job() {
        let result = auto_detached_result("sleep 0.1; printf TAP_FAILURE; exit 1");

        assert_eq!(result.is_error, Some(true));
        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("failed"));
        assert_eq!(structured["exitCode"], serde_json::json!(1));
        assert!(structured["jobId"].as_str().is_some());
        assert!(
            structured["summary"]
                .as_str()
                .is_some_and(|s| s.contains("TAP_FAILURE"))
        );
        assert!(text_of(&result).contains("TAP_FAILURE"));
    }

    #[test]
    #[cfg(not(windows))]
    fn auto_detached_exit_7_is_a_structured_failed_job() {
        let result = auto_detached_result("sleep 0.1; exit 7");

        assert_eq!(result.is_error, Some(true));
        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("failed"));
        assert_eq!(structured["exitCode"], serde_json::json!(7));
    }

    #[test]
    #[cfg(not(windows))]
    fn auto_detached_running_job_has_no_exit_code() {
        let result = auto_detached_running_result();

        assert_ne!(result.is_error, Some(true));
        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("running"));
        assert!(structured["jobId"].as_str().is_some());
        assert!(structured.get("exitCode").is_none());
    }

    #[test]
    #[cfg(not(windows))]
    fn auto_detached_cancel_returns_cancelled_exit_130_without_error() {
        let detached = crate::server::background_shell::run_foreground_or_detach(
            "sleep 2 # MES1609_CANCEL_STATUS".to_string(),
            ".".to_string(),
            std::collections::HashMap::default(),
            Some(10_000),
            std::time::Duration::from_millis(10),
            None,
            None,
        );
        let job_id = match detached {
            crate::server::background_shell::ForegroundResult::Detached { job_id } => job_id,
            // Diagnostic on purpose: if this ever fires on CI we need to see
            // *why* the child never reached the soft cap. A failed spawn or a
            // missing `sleep` shows up here as an exit code and a shell error
            // rather than as an unexplained timing story.
            crate::server::background_shell::ForegroundResult::Finished { output, exit_code } => {
                panic!(
                    "the reproduction must exercise the auto-detached path; the child \
                     finished inside the soft cap instead (exit {exit_code}): {output}"
                )
            }
        };
        let _job = BackgroundJobGuard::new(job_id.clone());

        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("cancel"));
        args.insert("job_id".to_string(), serde_json::json!(job_id));
        let output = crate::tools::registered::ctx_shell::CtxShellTool
            .handle(&args, &ToolContext::default())
            .expect("cancel must return a tool result");
        let cancel_result = finalize_call_result(&output.text, output.shell_outcome);

        assert_ne!(cancel_result.is_error, Some(true));
        let mut cancelled = false;
        for _ in 0..80 {
            if matches!(
                crate::server::background_shell::status(&job_id),
                Some(crate::server::background_shell::JobState::Cancelled { .. })
            ) {
                cancelled = true;
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
        assert!(cancelled, "cancelled job did not reach a terminal state");

        args.insert("background_action".to_string(), serde_json::json!("status"));
        let output = crate::tools::registered::ctx_shell::CtxShellTool
            .handle(&args, &ToolContext::default())
            .expect("status must return a tool result");
        let result = finalize_call_result(&output.text, output.shell_outcome);

        assert_ne!(result.is_error, Some(true));
        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("cancelled"));
        assert_eq!(structured["exitCode"], serde_json::json!(130));
    }

    #[test]
    fn missing_cancel_is_a_success_ack_without_a_fabricated_terminal_state() {
        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("cancel"));
        args.insert(
            "job_id".to_string(),
            serde_json::json!("shell_mes1609_missing_cancel"),
        );

        let result = call_shell(&args, &ToolContext::default());

        assert_ne!(result.is_error, Some(true));
        assert!(
            result.structured_content.is_none(),
            "an unknown terminal must not be fabricated: {:?}",
            result.structured_content
        );
        assert!(text_of(&result).contains("already finished or cancelled"));
    }

    #[test]
    fn missing_status_is_a_lookup_error_without_a_fabricated_lifecycle_state() {
        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("status"));
        args.insert(
            "job_id".to_string(),
            serde_json::json!("shell_mes1609_missing_status"),
        );

        let result = call_shell(&args, &ToolContext::default());

        assert_eq!(result.is_error, Some(true));
        let structured = result
            .structured_content
            .as_ref()
            .expect("missing status must expose a structured lookup error");
        assert_eq!(
            structured["jobId"],
            serde_json::json!("shell_mes1609_missing_status")
        );
        assert_eq!(
            structured["errorCode"],
            serde_json::json!("background_job_not_found_or_expired")
        );
        assert!(structured["reason"].as_str().is_some());
        assert!(structured.get("state").is_none());
        assert!(structured.get("exitCode").is_none());
        assert!(text_of(&result).contains("not found or expired"));
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn explicit_background_launch_ack_is_structured_running() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "4096");
        let mut args = serde_json::Map::new();
        args.insert(
            "command".to_string(),
            serde_json::json!("sleep 0.1; printf MES1727_EXPLICIT_OUTPUT"),
        );
        args.insert("run_in_background".to_string(), serde_json::json!(true));

        let result = call_shell(&args, &shell_context());

        let job = launched_job_guard(&result);
        assert_ne!(result.is_error, Some(true));
        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("running"));
        assert!(structured["jobId"].as_str().is_some());
        assert!(structured.get("exitCode").is_none());

        wait_for_completed(&job.job_id);
        let terminal = pipeline_background_status(&job.job_id, false, false, false).await;
        let archive_id = structured_of(&terminal)["archiveId"]
            .as_str()
            .expect("short explicit background output must be archived");
        assert_ne!(archive_id, job.job_id);
        let expanded = crate::tools::ctx_expand::handle(&serde_json::json!({"id": &job.job_id}));
        assert!(expanded.contains(&format!("Archive {archive_id}")));
        assert!(expanded.contains("MES1727_EXPLICIT_OUTPUT"));

        let repeated = pipeline_background_status(&job.job_id, false, false, false).await;
        assert_eq!(
            structured_of(&repeated)["archiveId"],
            serde_json::json!(archive_id)
        );
    }

    // #1980: with `[cache] shell_cache_enabled = true` (since removed), a
    // repeated state-observing command replayed its first output after the
    // file it reads had changed. Every call must observe the workspace as is.
    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn repeated_state_observing_command_sees_the_current_file() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let config = crate::core::config::Config::path().expect("isolated config path");
        std::fs::create_dir_all(config.parent().expect("config dir")).unwrap();
        std::fs::write(&config, "[cache]\nshell_cache_enabled = true\n").unwrap();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("probe.txt");
        let mut args = serde_json::Map::new();
        args.insert(
            "command".to_string(),
            serde_json::json!(format!("wc -c {}", file.display())),
        );
        let byte_count = |content: &str| {
            std::fs::write(&file, content).unwrap();
            let result = call_shell(&args, &shell_context());
            text_of(&result)
                .split_whitespace()
                .next()
                .map(str::to_owned)
        };

        assert_eq!(byte_count("a").as_deref(), Some("1"));
        assert_eq!(byte_count("abcdef").as_deref(), Some("6"));
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn soft_cap_auto_detach_ack_is_structured_running() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _soft_cap = ScopedEnvVar::set("LEAN_CTX_SHELL_FG_CAP_MS", "10");
        let mut args = serde_json::Map::new();
        args.insert(
            "command".to_string(),
            serde_json::json!("sleep 2 # MES1609_SOFT_CAP_LAUNCH"),
        );

        let result = call_shell(&args, &shell_context());

        let _job = launched_job_guard(&result);
        assert_ne!(result.is_error, Some(true));
        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("running"));
        assert!(structured["jobId"].as_str().is_some());
        assert!(structured.get("exitCode").is_none());
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn running_background_status_is_not_archived() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let job_id = crate::server::background_shell::start(
            "sleep 2".to_string(),
            ".".to_string(),
            std::collections::HashMap::default(),
            Some(10_000),
        );
        let _job = BackgroundJobGuard::new(job_id.clone());

        let result = pipeline_background_status(&job_id, false, false, false).await;

        assert_eq!(
            structured_of(&result)["state"],
            serde_json::json!("running")
        );
        assert!(structured_of(&result).get("archiveId").is_none());
        assert!(crate::core::archive::list_entries(None).is_empty());
    }

    /// MES-1609: a successful auto-detached child remains queryable after
    /// the OS process exits and exposes an explicit terminal code 0.
    #[test]
    #[cfg(not(windows))]
    fn auto_detached_exit_0_remains_queryable_as_completed() {
        let result = auto_detached_result("sleep 0.1; printf LONG_OK");

        assert_ne!(result.is_error, Some(true));
        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("completed"));
        assert_eq!(structured["exitCode"], serde_json::json!(0));
        assert!(structured["jobId"].as_str().is_some());
        assert!(
            structured["summary"]
                .as_str()
                .is_some_and(|s| s.contains("LONG_OK"))
        );
        assert!(text_of(&result).contains("LONG_OK"));
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn auto_detached_short_output_is_recoverable_by_job_id() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "4096");
        let (result, job) = auto_detached_pipeline_result("printf MES1727_AUTO_OUTPUT").await;

        let structured = structured_of(&result);
        let archive_id = structured["archiveId"]
            .as_str()
            .expect("short auto-detached output must be archived");
        assert_ne!(archive_id, job.job_id);
        let expanded = crate::tools::ctx_expand::handle(&serde_json::json!({"id": &job.job_id}));
        assert!(expanded.contains(&format!("Archive {archive_id}")));
        assert!(expanded.contains("MES1727_AUTO_OUTPUT"));
    }

    /// MES-1609: terminal output too large for an inline response is archived
    /// before generic filtering can erase both the verdict and retrieval id.
    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn auto_detached_large_output_keeps_summary_and_archive_id_inline() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let (result, _job) = auto_detached_pipeline_result("sleep 0.1; seq 1 50000").await;

        assert_ne!(result.is_error, Some(true));
        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("completed"));
        assert_eq!(structured["exitCode"], serde_json::json!(0));
        let archive_id = structured["archiveId"]
            .as_str()
            .expect("large terminal output must expose its archive id");
        assert!(
            structured["summary"]
                .as_str()
                .is_some_and(|s| s.contains("50000 lines"))
        );
        let text = text_of(&result);
        assert!(text.contains(&format!("ctx_expand(id=\"{archive_id}\")")));
        assert!(text.len() < 20_000, "large output was returned inline");
        let archived = crate::core::archive::retrieve(archive_id)
            .expect("archive id must resolve to the terminal output");
        assert!(archived.starts_with("1\n2\n"));
        assert!(archived.ends_with("49999\n50000\n"));
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn auto_detached_private_key_block_is_fully_redacted_before_archive() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let begin_marker = ["-----BEGIN ", "PRIVATE", " KEY-----"].concat();
        let end_marker = ["-----END ", "PRIVATE", " KEY-----"].concat();
        let command = format!(
            "sleep 0.1; printf '%s\\n' '{begin_marker}'; \
             yes MES1609_FAKE_KEY_BODY_0123456789 | head -n 2000; \
             printf '%s\\n' '{end_marker}'; \
             yes MES1609_SAFE_OUTPUT | head -n 2000"
        );
        let (result, _job) = auto_detached_pipeline_result(&command).await;

        let archive_id = structured_of(&result)["archiveId"]
            .as_str()
            .expect("large redacted output must be archived");
        let archived = crate::core::archive::retrieve(archive_id)
            .expect("archive id must resolve to redacted output");
        assert!(!archived.contains("BEGIN PRIVATE KEY"));
        assert!(!archived.contains("END PRIVATE KEY"));
        assert!(!archived.contains("MES1609_FAKE_KEY_BODY_0123456789"));
        assert!(archived.contains("[REDACTED:Private key block]"));
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn oversized_background_archive_reports_truncation_and_exact_sizes() {
        const ARCHIVE_LIMIT: usize = crate::core::archive::MAX_ARCHIVE_SIZE;
        const CAPTURED: usize = ARCHIVE_LIMIT + 4096;
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _shell_cap = ScopedEnvVar::set("LCTX_MAX_SHELL_BYTES", (CAPTURED + 1024).to_string());
        let (result, _job) = auto_detached_pipeline_result(&format!(
            "sleep 0.1; head -c {CAPTURED} /dev/zero | tr '\\0' X"
        ))
        .await;

        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("completed"));
        assert_eq!(structured["exitCode"], serde_json::json!(0));
        assert_eq!(structured["archiveTruncated"], serde_json::json!(true));
        assert_eq!(structured["capturedChars"], serde_json::json!(CAPTURED));
        assert_eq!(
            structured["archivedChars"],
            serde_json::json!(ARCHIVE_LIMIT)
        );
        let archive_id = structured["archiveId"]
            .as_str()
            .expect("oversized output must expose archiveId");
        let archived = crate::core::archive::retrieve(archive_id)
            .expect("truncated archive must remain retrievable");
        assert_eq!(archived.len(), ARCHIVE_LIMIT);
        assert!(text_of(&result).contains("archive truncated"));
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn background_status_pipeline_keeps_single_archive_and_structured_metadata() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let _references = ScopedEnvVar::set("LEAN_CTX_REFERENCE_RESULTS", "1");
        let job_id = crate::server::background_shell::start(
            "sleep 0.1; printf MES1609_PIPELINE; head -c 50000 /dev/zero | tr '\\000' P"
                .to_string(),
            ".".to_string(),
            std::collections::HashMap::default(),
            Some(10_000),
        );
        let _job = BackgroundJobGuard::new(job_id.clone());
        wait_for_completed(&job_id);

        // #1778: compile-time constant, not the process-global cwd (see
        // `shell_context` above).
        let root = env!("CARGO_MANIFEST_DIR").to_string();
        let server = crate::tools::LeanCtxServer::new_with_project_root(Some(&root));
        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("status"));
        args.insert("job_id".to_string(), serde_json::json!(job_id));
        let result = dispatch_and_post_process(
            &server,
            "ctx_shell",
            Some(&args),
            false,
            crate::core::config::Config::load_arc(),
            false,
            None,
            None,
            "mes1609_pipeline".to_string(),
            None,
        )
        .await
        .expect("background status pipeline must succeed");

        let structured = structured_of(&result);
        assert_eq!(structured["state"], serde_json::json!("completed"));
        assert_eq!(structured["exitCode"], serde_json::json!(0));
        let archive_id = structured["archiveId"]
            .as_str()
            .expect("pipeline must retain archiveId");
        assert_eq!(crate::core::archive::list_entries(None).len(), 1);
        assert_eq!(
            text_of(&result)
                .matches(&format!("ctx_expand(id=\"{archive_id}\")"))
                .count(),
            1
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn background_status_triage_filters_display_after_preserving_complete_archive() {
        const KEEP: &str = "MES1609_TRIAGE_KEEP";
        const DROP: &str = "MES1609_TRIAGE_DROP";
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _archive_threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let _firewall_threshold = ScopedEnvVar::set("LEAN_CTX_EPHEMERAL_MIN_TOKENS", "100000");
        let (job_id, _job) = completed_background_job(&format!(
            "printf 'coding coding_fix {KEEP}\\n'; yes '// unrelated {DROP}' | head -n 80"
        ));

        // #1778: compile-time constant, not the process-global cwd (see
        // `shell_context` above).
        let root = env!("CARGO_MANIFEST_DIR").to_string();
        let server = crate::tools::LeanCtxServer::new_with_project_root(Some(&root));
        let session_id = server.session.read().await.id.clone();
        let context = crate::core::decision_loop_runtime::DecisionLoopRuntime::get_or_init()
            .on_tool_start(
                "ctx_shell",
                Some("fix a coding bug in one file"),
                &session_id,
                "mes1609-triage-test",
            );
        let profile = crate::core::decision_loop_runtime::DecisionLoopRuntime::get_or_init()
            .profile_for_session(&session_id)
            .expect("task profile must be remembered for the pipeline session");
        assert!(crate::server::context_gate::triage_filter_level(&profile) > 0);

        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("status"));
        args.insert("job_id".to_string(), serde_json::json!(job_id));
        // Output filtering is opt-in since decision_loop.max_filter_level
        // landed (default 0 = off); this test exercises the filtered-display
        // path, so it enables the level explicitly on its own config.
        let config = {
            let mut config = crate::core::config::Config::load_arc().as_ref().clone();
            config.decision_loop.max_filter_level = 2;
            std::sync::Arc::new(config)
        };
        let result = dispatch_and_post_process(
            &server,
            "ctx_shell",
            Some(&args),
            false,
            config,
            false,
            None,
            None,
            "mes1609_triage_pipeline".to_string(),
            Some(context),
        )
        .await
        .expect("background status pipeline must succeed");

        let structured = structured_of(&result);
        let archive_id = structured["archiveId"]
            .as_str()
            .expect("normal background status must retain its complete archive");
        let archived = crate::core::archive::retrieve(archive_id)
            .expect("structured archiveId must remain retrievable");
        assert!(archived.contains(KEEP));
        assert!(archived.contains(DROP));
        let displayed = text_of(&result);
        assert!(displayed.contains(KEEP));
        assert!(!displayed.contains(DROP));
        assert!(!displayed.contains("ctx_expand"));
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn unbound_background_recovery_is_withheld_after_policy_and_input_filters() {
        const POLICY_PATTERN: &str = "MES1609_POLICY_PII_7F3A9C2E";
        const TEST_CARD: &str = "4111111111111111";
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let _policy = ScopedPolicy::redacting("mes1609_policy", POLICY_PATTERN);
        let (job_id, _job) = completed_background_job(&format!(
            "printf '%s\\n%s\\n' '{POLICY_PATTERN}' '{TEST_CARD}'; \
             yes MES1609_POLICY_SAFE | head -n 3000"
        ));

        let result = pipeline_background_status(&job_id, false, false, false).await;

        let structured = structured_of(&result);
        assert!(structured.get("archiveId").is_none());
        assert!(structured.get("archiveTruncated").is_none());
        assert!(structured.get("archivedChars").is_none());
        assert!(structured["capturedChars"].as_u64().unwrap() > 0);
        assert!(
            structured["summary"]
                .as_str()
                .unwrap()
                .contains("archive unavailable")
        );
        assert!(crate::core::archive::list_entries(None).is_empty());
        let displayed = text_of(&result);
        assert!(!displayed.contains(POLICY_PATTERN));
        assert!(!displayed.contains(TEST_CARD));
        assert!(displayed.contains("[REDACTED:mes1609_policy]"));
        assert!(displayed.contains("[REDACTED:card]"));
        assert!(
            crate::core::audit_trail::load_recent(10)
                .iter()
                .any(|entry| {
                    entry.tool == "ctx_shell"
                        && entry.role == "mes1609-test-policy"
                        && matches!(
                            entry.event_type,
                            crate::core::audit_trail::AuditEventType::SecretDetected
                        )
                })
        );
        assert!(
            result.meta.is_some(),
            "finalize metadata must still be present"
        );
    }

    #[test]
    #[cfg(not(windows))]
    fn scoped_policy_overrides_serialize_parallel_mutation() {
        // The deliberately active global overrides below must not leak into
        // other tests that hold isolated data/config state but use live
        // policy. Each override now holds `test_env_lock` itself (lock order
        // env → override), so this thread must not hold it: the override
        // threads below would wait on it forever.
        let (first_ready_tx, first_ready_rx) = std::sync::mpsc::channel();
        let (release_first_tx, release_first_rx) = std::sync::mpsc::channel();
        let first = std::thread::spawn(move || {
            let _policy = ScopedPolicy::redacting("mes1609_first", "MES1609_FIRST");
            first_ready_tx.send(()).expect("signal first override");
            release_first_rx.recv().expect("release first override");
        });
        // Liveness waits, not timing assertions: an override first takes
        // `test_env_lock`, which other tests may hold for a while on a busy
        // many-core runner.
        let acquire = std::time::Duration::from_mins(2);
        first_ready_rx
            .recv_timeout(acquire)
            .expect("first override must become active");

        let (second_started_tx, second_started_rx) = std::sync::mpsc::channel();
        let (second_acquired_tx, second_acquired_rx) = std::sync::mpsc::channel();
        let (release_second_tx, release_second_rx) = std::sync::mpsc::channel();
        let second = std::thread::spawn(move || {
            second_started_tx.send(()).expect("signal second thread");
            let _policy = ScopedPolicy::redacting("mes1609_second", "MES1609_SECOND");
            second_acquired_tx.send(()).expect("signal second override");
            release_second_rx.recv().expect("release second override");
        });
        second_started_rx
            .recv_timeout(std::time::Duration::from_secs(1))
            .expect("second thread must start");
        let overlapped = second_acquired_rx
            .recv_timeout(std::time::Duration::from_millis(500))
            .is_ok();

        release_first_tx.send(()).expect("release first thread");
        first.join().expect("first policy thread");
        if !overlapped {
            second_acquired_rx
                .recv_timeout(acquire)
                .expect("second override must acquire after first drops");
        }
        release_second_tx.send(()).expect("release second thread");
        second.join().expect("second policy thread");

        assert!(!overlapped, "policy test overrides must not overlap");
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn raw_background_status_keeps_secured_output_inline_without_digest() {
        const RAW_SIZE: usize = 50_000;
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let _turn_limit = ScopedEnvVar::set("LEAN_CTX_TURN_FRESH_LIMIT", "0");
        let (job_id, _job) = completed_background_job(&format!(
            "printf MES1609_RAW_HEAD; head -c {RAW_SIZE} /dev/zero | tr '\\000' R; printf MES1609_RAW_TAIL"
        ));

        let result = pipeline_background_status(&job_id, false, true, false).await;

        let text = text_of(&result);
        assert!(text.len() >= RAW_SIZE);
        assert!(text.contains("MES1609_RAW_HEAD"));
        assert!(text.contains("MES1609_RAW_TAIL"));
        assert!(!text.contains("ctx_expand"));
        assert!(!text.contains("[Archived:"));
        assert!(structured_of(&result)["archiveId"].as_str().is_some());
        assert_eq!(crate::core::archive::list_entries(None).len(), 1);
    }

    // #1540: the `minimal_overhead` CONFIG key (default true) must not disable
    // the archive/firewall safety net — a large background delivery still
    // becomes a lossless digest with drilldown.
    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn config_minimal_still_archives_and_firewalls_background_status() {
        const MINIMAL_SIZE: usize = 50_000;
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let (job_id, _job) = completed_background_job(&format!(
            "printf MES1609_MINIMAL_HEAD; head -c {MINIMAL_SIZE} /dev/zero | tr '\\000' M; printf MES1609_MINIMAL_TAIL"
        ));

        let result = pipeline_background_status(&job_id, true, false, false).await;

        assert_eq!(crate::core::archive::list_entries(None).len(), 1);
        let text = text_of(&result);
        assert!(text.contains("ctx_expand"), "digest must offer drilldown");
        assert!(
            text.len() < MINIMAL_SIZE,
            "delivery must be the digest, not the body"
        );
    }

    // #1540: only the LEAN_CTX_MINIMAL env escape hatch (the documented
    // do-not-touch-anything switch since the 3.9.19 incident) skips the
    // archive/firewall entirely.
    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn env_minimal_escape_hatch_skips_archive_and_digest() {
        const MINIMAL_SIZE: usize = 50_000;
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let _hatch = ScopedEnvVar::set("LEAN_CTX_MINIMAL", "1");
        let (job_id, _job) = completed_background_job(&format!(
            "printf MES1609_HATCH_HEAD; head -c {MINIMAL_SIZE} /dev/zero | tr '\\000' M; printf MES1609_HATCH_TAIL"
        ));

        let result = pipeline_background_status(&job_id, true, false, false).await;

        let structured = structured_of(&result);
        assert!(structured.get("archiveId").is_none());
        assert_eq!(crate::core::archive::list_entries(None).len(), 0);
        let text = text_of(&result);
        assert!(!text.contains("ctx_expand"));
        assert!(!text.contains("[Archived:"));
    }

    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn inline_background_status_under_limit_stays_inline_without_digest() {
        const INLINE_SIZE: usize = 5_000;
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let _turn_limit = ScopedEnvVar::set("LEAN_CTX_TURN_FRESH_LIMIT", "0");
        let (job_id, _job) = completed_background_job(&format!(
            "printf MES1609_INLINE_HEAD; head -c {INLINE_SIZE} /dev/zero | tr '\\000' I; printf MES1609_INLINE_TAIL"
        ));

        let result = pipeline_background_status(&job_id, false, false, true).await;

        let text = text_of(&result);
        assert!(text.len() >= INLINE_SIZE);
        assert!(text.contains("MES1609_INLINE_HEAD"));
        assert!(text.contains("MES1609_INLINE_TAIL"));
        assert!(!text.contains("ctx_expand"));
        assert!(!text.contains("[Archived:"));
        assert!(structured_of(&result)["archiveId"].as_str().is_some());
        assert_eq!(crate::core::archive::list_entries(None).len(), 1);
    }

    // #1541: inline=true is honored up to the context-window cap; above it the
    // delivery becomes a lossless digest with drilldown instead of flooding
    // the caller's context. Explicit raw stays verbatim at any size.
    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn inline_background_status_above_verbatim_cap_is_digested() {
        const CAP_SIZE: usize = 20_000;
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let _cap = ScopedEnvVar::set("LEAN_CTX_VERBATIM_MAX_TOKENS", "1000");
        let _turn_limit = ScopedEnvVar::set("LEAN_CTX_TURN_FRESH_LIMIT", "0");
        let (job_id, _job) = completed_background_job(&format!(
            "printf MES1609_CAP_HEAD; head -c {CAP_SIZE} /dev/zero | tr '\\000' C; printf MES1609_CAP_TAIL"
        ));

        let result = pipeline_background_status(&job_id, false, false, true).await;

        let text = text_of(&result);
        assert!(
            text.len() < CAP_SIZE,
            "above the cap the delivery is a digest, got {} bytes",
            text.len()
        );
        assert!(text.contains("ctx_expand"), "digest must offer drilldown");
        assert_eq!(crate::core::archive::list_entries(None).len(), 1);
    }

    #[test]
    #[cfg(not(windows))]
    fn background_status_handler_does_not_write_archives_before_pipeline() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let _archive = ScopedEnvVar::set("LEAN_CTX_ARCHIVE", "1");
        let _threshold = ScopedEnvVar::set("LEAN_CTX_ARCHIVE_THRESHOLD", "1");
        let (job_id, _job) = completed_background_job(
            "printf MES1609_HANDLER_ONLY; head -c 50000 /dev/zero | tr '\\000' H",
        );
        let mut args = serde_json::Map::new();
        args.insert("background_action".to_string(), serde_json::json!("status"));
        args.insert("job_id".to_string(), serde_json::json!(job_id));

        let output = crate::tools::registered::ctx_shell::CtxShellTool
            .handle(&args, &ToolContext::default())
            .expect("status handler must succeed without pipeline I/O");

        assert_eq!(crate::core::archive::list_entries(None).len(), 0);
        assert!(
            output
                .shell_outcome
                .and_then(|outcome| outcome.structured())
                .is_some_and(|structured| structured.get("archiveId").is_none())
        );
    }

    #[test]
    fn exit_2_is_always_error() {
        let r = finalize_call_result("error output", Some(ShellOutcome::Exit(2)));
        assert_eq!(
            r.is_error,
            Some(true),
            "exit >= 2 must always set isError (#389)"
        );
        assert_eq!(
            r.structured_content,
            Some(serde_json::json!({ "exitCode": 2 })),
            "guards must be able to read exitCode without text parsing"
        );
    }

    #[test]
    fn negative_exit_codes_are_reported() {
        // Signal terminations are mapped to negative/128+n codes by execute();
        // whatever the value, non-zero must surface as an error.
        let r = finalize_call_result("killed", Some(ShellOutcome::Exit(-1)));
        assert_eq!(r.is_error, Some(true));
        assert_eq!(
            r.structured_content,
            Some(serde_json::json!({ "exitCode": -1 }))
        );
    }

    #[test]
    fn blocked_command_sets_is_error_and_blocked_marker() {
        let r = finalize_call_result("[BLOCKED] nope", Some(ShellOutcome::Blocked));
        assert_eq!(
            r.is_error,
            Some(true),
            "blocked commands never ran — that is a failure"
        );
        assert_eq!(
            r.structured_content,
            Some(serde_json::json!({ "blocked": true }))
        );
    }

    #[test]
    fn non_shell_tools_are_unaffected() {
        let r = finalize_call_result("file contents", None);
        assert_ne!(r.is_error, Some(true));
        assert!(r.structured_content.is_none());
    }

    /// A real registered file-output tool must pass through the model-bound
    /// policy redaction before its MCP result is returned.
    #[tokio::test(flavor = "multi_thread")]
    #[cfg(not(windows))]
    async fn registered_file_output_is_policy_redacted_before_mcp_reply() {
        let _data_dir = crate::core::data_dir::isolated_data_dir();
        let root = tempfile::tempdir().unwrap();
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        // Letters, not digits: a digit run can pass the Luhn check, and the
        // gateway's card detector would then redact it before the policy rule
        // sees the whole marker.
        let nonce_text = nonce
            .to_string()
            .chars()
            .map(|digit| {
                let value = digit.to_digit(10).unwrap_or(0);
                char::from_digit(value + 10, 36).unwrap_or('x').to_string()
            })
            .collect::<Vec<_>>()
            .join("-");
        let secret = format!("cobalt badger egress marker {nonce_text} private note");
        std::fs::write(root.path().join("probe.txt"), &secret).unwrap();
        let _policy = ScopedPolicy::redacting("cq06_runtime_probe", &regex::escape(&secret));

        let server = crate::tools::LeanCtxServer::new_with_project_root(Some(
            root.path().to_str().expect("temporary root is UTF-8"),
        ));
        *server.presence_agent_id.write().await = Some("cq06-egress-test".to_owned());
        let args = serde_json::Map::from_iter([
            ("path".to_owned(), serde_json::json!("probe.txt")),
            ("mode".to_owned(), serde_json::json!("full")),
        ]);
        let request = rmcp::model::CallToolRequestParams::new("ctx_read").with_arguments(args);

        let result = server
            .call_tool_guarded(request)
            .await
            .expect("registered ctx_read call must succeed");
        let visible = result
            .content
            .iter()
            .filter_map(|block| block.as_text())
            .map(|block| block.text.as_str())
            .collect::<Vec<_>>()
            .join("\n");

        assert!(
            !visible.contains(&secret),
            "model-visible MCP result leaked runtime secret: {visible}"
        );
        assert!(
            visible.contains("[REDACTED:cq06_runtime_probe]"),
            "policy redaction marker missing from model-visible result: {visible}"
        );
    }

    /// Security invariant across the registry and dispatch files: every
    /// registered McpTool is invoked only by the one generic dispatcher that
    /// the MCP handler sends through dispatch_and_post_process. The sole
    /// exemption is this cfg(test)-only file, whose direct calls test handlers
    /// in isolation and never create model-visible MCP replies.
    #[test]
    fn registered_tool_dispatch_has_one_outbound_pipeline_entry() {
        // Test-only fixtures that call a handler directly. `task_lineage_tests`
        // wraps ctx_read in a rendezvous tool that is itself dispatched through
        // the one production entry, so it adds no second outbound path.
        const TEST_ONLY_EXEMPTIONS: &[&str] = &[
            "call_tool/tests.rs",
            "call_tool/guarded/task_lineage_tests.rs",
        ];

        let server_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/server");
        for exemption in TEST_ONLY_EXEMPTIONS {
            let path = server_dir.join(exemption);
            assert!(path.is_file(), "stale egress exemption: {exemption}");
            let source = std::fs::read_to_string(path).expect("read test-only exemption");
            assert!(
                source.contains(".handle("),
                "stale egress exemption no longer contains isolated direct handler tests: {exemption}"
            );
        }

        let mut direct_handler_calls = Vec::new();
        for entry in walkdir::WalkDir::new(&server_dir)
            .into_iter()
            .filter_map(Result::ok)
            .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "rs"))
        {
            let relative = entry
                .path()
                .strip_prefix(&server_dir)
                .expect("entry is under server source")
                .to_string_lossy()
                // Windows yields `call_tool\tests.rs`; compare in one separator.
                .replace('\\', "/");
            if TEST_ONLY_EXEMPTIONS.contains(&relative.as_str()) {
                continue;
            }
            let source = std::fs::read_to_string(entry.path()).expect("read server source");
            for (line, text) in source.lines().enumerate() {
                if text.contains(".handle(") {
                    direct_handler_calls.push((relative.clone(), line + 1, text.trim().to_owned()));
                }
            }
        }

        assert_eq!(
            direct_handler_calls.len(),
            1,
            "registered McpTool handlers must have one production invocation site: {direct_handler_calls:?}"
        );
        assert_eq!(direct_handler_calls[0].0, "dispatch/mod.rs");
        assert!(direct_handler_calls[0].2.contains("tool.handle("));

        let server_handler = include_str!("../server_handler.rs");
        let guarded = include_str!("guarded.rs");
        let pipeline = include_str!("pipeline.rs");
        let dispatch = include_str!("../dispatch/mod.rs");
        let resources = include_str!("../resources.rs");
        let file_resource = include_str!("../file_resource.rs");
        let prompts = include_str!("../prompts.rs");
        let cli_call = include_str!("../../cli/call_cmd.rs");
        let cli_agent_tools = include_str!("../../cli/agent_tools_cmd.rs");
        let embed_engine = include_str!("../../../crates/lean-ctx-embed/src/engine.rs");
        assert!(server_handler.contains("self.call_tool_guarded(request)"));
        // The guarded lifecycle driver runs the one pipeline in its two
        // stages: dispatch, then reversible post-processing.
        assert!(guarded.contains("super::pipeline::dispatch_primitive("));
        assert!(guarded.contains("super::pipeline::reversible_post_process("));
        // Dispatch runs under source-authority capture; content decisions go
        // through the shared policy guard (redaction or withholding) and the
        // sensitivity floor.
        assert!(
            pipeline
                .contains("authority::capture(server.dispatch_tool(name, args, minimal)).await")
        );
        assert!(pipeline.contains("policy_guard::protect_result(name, &result_text)"));
        assert!(pipeline.contains("sensitivity::enforce_text"));
        assert!(dispatch.contains("_ => self.dispatch_inner(name, args, minimal).await"));
        assert!(dispatch.contains("r.get_arc(name)"));
        assert!(resources.contains("policy_guard::redact_model_text"));
        assert!(file_resource.contains("resources::text_resource(&content, uri)"));
        assert!(prompts.contains("policy_guard::redact_model_text"));
        assert!(cli_call.contains("policy_guard::redact_model_text(&output.text)"));
        assert!(cli_agent_tools.contains("policy_guard::redact_model_text(&output.text)"));
        assert!(embed_engine.contains("policy_guard::redact_model_text(&out.text)"));

        let registry = crate::server::registry::build_registry();
        let names = registry.names();
        assert!(!names.is_empty(), "registry must include registered tools");
        for name in names {
            let tool = registry.get(name).expect("every registered name resolves");
            assert_eq!(tool.name(), name);
        }
    }
}

#[cfg(test)]
mod roots_retry_tests {
    use super::roots_list_failure_is_permanent;

    /// Cursor's pattern (#699): roots capability declared, `roots/list`
    /// answered with `-32601` — retrying is pointless and must stop.
    #[test]
    fn method_not_found_is_permanent() {
        let err = rmcp::ServiceError::McpError(rmcp::model::ErrorData::new(
            rmcp::model::ErrorCode::METHOD_NOT_FOUND,
            "Method not found",
            None,
        ));
        assert!(roots_list_failure_is_permanent(&err));
    }

    /// The VS Code multi-window pattern (GH #694): the second window's client
    /// is still starting up, `roots/list` times out or the transport hiccups —
    /// these must stay retryable so root detection recovers.
    #[test]
    fn timeouts_and_other_mcp_errors_are_transient() {
        let timeout = rmcp::ServiceError::Timeout {
            timeout: std::time::Duration::from_secs(5),
        };
        assert!(!roots_list_failure_is_permanent(&timeout));

        let internal = rmcp::ServiceError::McpError(rmcp::model::ErrorData::new(
            rmcp::model::ErrorCode::INTERNAL_ERROR,
            "boom",
            None,
        ));
        assert!(!roots_list_failure_is_permanent(&internal));
    }
}

#[cfg(test)]
mod response_cache_tests {
    use super::super::guarded::{cache_call_result, cached_call_result, response_cache_key};
    use crate::core::ocla::response_cache::{CachedResponse, ResponseCache};
    use rmcp::model::{CallToolResult, ContentBlock};
    use serde_json::{Map, json};
    use std::time::{Duration, Instant};

    fn arguments() -> Map<String, serde_json::Value> {
        Map::from_iter([("path".to_owned(), json!("src/lib.rs"))])
    }

    fn text_of(result: &CallToolResult) -> &str {
        result.content[0]
            .as_text()
            .expect("cached result must be text")
            .text
            .as_str()
    }

    #[test]
    fn only_deterministic_tools_receive_cache_keys() {
        for tool in ["ctx_search", "ctx_tree", "ctx_glob"] {
            assert!(response_cache_key(tool, Some(&arguments()), "/project").is_some());
        }
        for tool in ["ctx_shell", "ctx_session", "ctx_knowledge", "ctx_call"] {
            assert!(response_cache_key(tool, Some(&arguments()), "/project").is_none());
        }
    }

    #[test]
    fn cache_keys_include_arguments_and_project_scope() {
        // The key binds the active policy; pin "no policy" so a concurrent
        // test's override cannot change the key between the calls.
        let _env = crate::core::data_dir::test_env_lock();
        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let base = response_cache_key("ctx_search", Some(&arguments()), "/project").unwrap();
        let other_root = response_cache_key("ctx_search", Some(&arguments()), "/other").unwrap();
        let other_args = Map::from_iter([("path".to_owned(), json!("src/main.rs"))]);
        let other_path = response_cache_key("ctx_search", Some(&other_args), "/project").unwrap();

        assert_ne!(base, other_root);
        assert_ne!(base, other_path);
        assert_eq!(
            base,
            response_cache_key("ctx_search", Some(&arguments()), "/project").unwrap()
        );
    }

    #[test]
    fn successful_text_response_round_trips_through_cache() {
        let cache = ResponseCache::new(8, Duration::from_mins(1));
        let key = response_cache_key("ctx_search", Some(&arguments()), "/project").unwrap();
        let mut result = CallToolResult::success(vec![ContentBlock::text("search result")]);
        result.structured_content = Some(json!({"matches": 1}));

        cache_call_result(&cache, key.clone(), &result);

        let cached = cached_call_result(&cache, &key).expect("response should be cached");
        assert_eq!(text_of(&cached), "search result");
        assert_eq!(cached.structured_content, Some(json!({"matches": 1})));
        assert_ne!(cached.is_error, Some(true));
    }

    #[test]
    fn expired_response_is_not_returned() {
        let cache = ResponseCache::new(8, Duration::from_secs(1));
        let key = response_cache_key("ctx_tree", Some(&arguments()), "/project").unwrap();
        cache.put(
            key.clone(),
            CachedResponse {
                body: b"stale".to_vec(),
                status: 200,
                tokens: 1,
                created_at: Instant::now().checked_sub(Duration::from_secs(2)).unwrap(),
                ttl: Duration::from_secs(1),
            },
        );

        assert!(cached_call_result(&cache, &key).is_none());
    }
}