lean-ctx 3.10.0

Local context engine, CLI, MCP server, and proxy for AI agents.
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
use crate::core::context_field::{ContextItemId, ContextState};
use crate::core::context_ledger::{ContextLedger, PressureAction};
use crate::core::context_overlay::{OverlayOp, OverlayStore};

/// #843: precise, pinned reads (`diff`, `lines:N-M`, `anchored`/`anchored:N-M`)
/// must pass through every mode-override path untouched — bounce-prevention,
/// pressure-downgrade, and the graph/knowledge heuristics below must never
/// silently reinterpret one of these to e.g. `full`, which would discard the
/// exact window/anchors/delta the caller asked for. Classifies off the typed
/// `ReadMode` (single source of truth, see `tools::ctx_read::mode`) rather than
/// a hand-maintained string-prefix list, so a future precise mode has to be
/// added to `ReadMode::is_precise_pinned_read` explicitly instead of silently
/// falling through an allowlist. An unparseable mode is conservatively treated
/// as *not* pinned, matching prior behaviour for anything outside this set.
fn is_precise_pinned_mode(requested_mode: &str) -> bool {
    requested_mode
        .parse::<crate::tools::ctx_read::ReadMode>()
        .is_ok_and(|m| m.is_precise_pinned_read())
}

#[derive(Debug, Clone)]
pub struct PreDispatchResult {
    pub overridden_mode: Option<String>,
    pub reason: Option<&'static str>,
    pub pressure_downgraded: bool,
    pub budget_blocked: bool,
    pub budget_warning: Option<String>,
    /// Triage-based output filter aggressiveness: 0=passthrough, 1=moderate, 2=aggressive.
    pub triage_filter_level: u8,
}

#[derive(Debug, Clone)]
pub struct PostDispatchResult {
    pub eviction_hint: Option<String>,
    pub elicitation_hint: Option<String>,
    pub resource_changed: bool,
    /// FEP prefetch suggestion (#9): files likely needed next, from the co-access
    /// graph. A warmup hint only — never an automatic read.
    pub prefetch_hint: Option<String>,
}

/// Best-effort KnowledgeRouter advice for the completed Context Gate flow.
pub fn knowledge_advice(
    query: &str,
) -> crate::core::knowledge_router::gate_integration::KnowledgeAdvice {
    let current = crate::core::context_kernel::ContextState::new(
        Vec::new(),
        crate::core::knowledge::KnowledgeQuery::default(),
    );
    crate::core::knowledge_router::gate_integration::KnowledgeGateAdvisor::advise(query, &current)
}

pub fn pre_dispatch_read(
    path: &str,
    requested_mode: &str,
    task: Option<&str>,
    project_root: Option<&str>,
    pressure: Option<&PressureAction>,
) -> PreDispatchResult {
    pre_dispatch_read_for_agent(
        path,
        requested_mode,
        task,
        project_root,
        pressure,
        None,
        false,
    )
}

/// `fresh` is the caller's explicit escape hatch (#1588). Bounce-prevention and
/// intent-target exist to stop an agent from *drifting* into a compressed view
/// it will immediately re-read in full; neither should be able to pin a file to
/// `full` forever. A caller who passes `fresh=true` has said, in the request
/// itself, that they want this view recomputed — honour it, or those modes are
/// simply unreachable for the rest of the session.
pub fn pre_dispatch_read_for_agent(
    path: &str,
    requested_mode: &str,
    task: Option<&str>,
    project_root: Option<&str>,
    pressure: Option<&PressureAction>,
    agent_id: Option<&str>,
    fresh: bool,
) -> PreDispatchResult {
    let no_change = PreDispatchResult {
        overridden_mode: None,
        reason: None,
        pressure_downgraded: false,
        budget_blocked: false,
        budget_warning: None,
        triage_filter_level: 0,
    };

    if let Some(aid) = agent_id {
        let estimated_tokens = estimate_read_tokens(path, requested_mode);
        match crate::core::agent_budget::check_budget(aid, estimated_tokens) {
            crate::core::agent_budget::BudgetCheckResult::Exceeded { limit, consumed } => {
                return PreDispatchResult {
                    overridden_mode: None,
                    reason: Some("agent-budget-exceeded"),
                    pressure_downgraded: false,
                    budget_blocked: true,
                    budget_warning: Some(format!(
                        "Agent budget exceeded: {consumed}/{limit} tokens consumed. Reset via ctx_session or set a higher limit."
                    )),
                    triage_filter_level: 0,
                };
            }
            crate::core::agent_budget::BudgetCheckResult::Warning {
                remaining,
                percent_used,
            } => {
                let warning = format!(
                    "[BUDGET WARNING] Agent '{aid}' at {:.0}% budget ({remaining} tokens remaining)",
                    percent_used * 100.0
                );
                let mut result = no_change.clone();
                result.budget_warning = Some(warning);
                if is_precise_pinned_mode(requested_mode) {
                    return result;
                }
                let rest =
                    pre_dispatch_inner(path, requested_mode, task, project_root, pressure, fresh);
                return PreDispatchResult {
                    budget_warning: result.budget_warning,
                    ..rest
                };
            }
            crate::core::agent_budget::BudgetCheckResult::Allowed { .. } => {}
        }
    }

    pre_dispatch_inner(path, requested_mode, task, project_root, pressure, fresh)
}

/// Does `norm` (a normalized path) actually name the intent target `target`?
///
/// The old rule was `norm.ends_with(t) || norm.contains(t)`, which matched on
/// any substring: a task mentioning `src` or `read` pinned every path
/// containing those letters to `full` (#1588), including matches that land in
/// the middle of a longer component (`print` inside `printer.rs`). A target now
/// has to line up with a whole path component or the file stem, and be long
/// enough to be a name rather than noise.
fn path_matches_target(norm: &str, target: &str) -> bool {
    const MIN_TARGET_LEN: usize = 4;
    let target = target.trim().trim_matches('/');
    if target.len() < MIN_TARGET_LEN {
        return false;
    }
    // A target that is itself a path suffix (`src/server/context_gate.rs`).
    if norm == target || norm.ends_with(&format!("/{target}")) {
        return true;
    }
    // Otherwise: a whole path component, with or without its extension.
    norm.split('/').any(|component| {
        component == target
            || component
                .rsplit_once('.')
                .is_some_and(|(stem, _)| stem == target)
    })
}

fn pre_dispatch_inner(
    path: &str,
    requested_mode: &str,
    task: Option<&str>,
    project_root: Option<&str>,
    pressure: Option<&PressureAction>,
    fresh: bool,
) -> PreDispatchResult {
    let no_change = PreDispatchResult {
        overridden_mode: None,
        reason: None,
        pressure_downgraded: false,
        budget_blocked: false,
        budget_warning: None,
        triage_filter_level: 0,
    };

    if is_precise_pinned_mode(requested_mode) {
        return no_change;
    }

    if let Some(root) = project_root {
        let overlay = OverlayStore::load_project(&std::path::PathBuf::from(root));
        if let Some(result) = check_overlay_mode_override(path, requested_mode, &overlay) {
            return result;
        }
    }

    // Explicit mode=full must not be downgraded by pressure or other heuristics.
    // Only overlays (user-explicit) above can override it.
    if requested_mode == "full" {
        return no_change;
    }

    if let Some(action) = pressure {
        let no_degrade = crate::core::config::Config::load().no_degrade_effective();
        let profile = crate::core::profiles::active_profile();
        if !no_degrade
            && profile.degradation.enforce_effective()
            && let Some(downgraded) = pressure_downgrade(requested_mode, action)
        {
            return PreDispatchResult {
                overridden_mode: Some(downgraded),
                reason: Some("pressure-auto-downgrade"),
                pressure_downgraded: true,
                budget_blocked: false,
                budget_warning: None,
                triage_filter_level: 0,
            };
        }
    }

    // `fresh` is the documented way out (#1588): the caller re-requested this
    // view deliberately, so the "you keep bouncing back to full" heuristic has
    // nothing left to prevent.
    if !fresh
        && let Ok(bt) = crate::core::bounce_tracker::global().lock()
        && bt.should_force_full(path)
    {
        return PreDispatchResult {
            overridden_mode: Some("full".to_string()),
            reason: Some("bounce-prevention"),
            pressure_downgraded: false,
            budget_blocked: false,
            budget_warning: None,
            triage_filter_level: 0,
        };
    }

    if let Some(task_str) = task
        && !fresh
    {
        let intent = crate::core::intent_engine::StructuredIntent::from_query(task_str);
        let norm = crate::core::pathutil::normalize_tool_path(path);
        let is_target = intent.targets.iter().any(|t| path_matches_target(&norm, t));
        if is_target {
            return PreDispatchResult {
                overridden_mode: Some("full".to_string()),
                reason: Some("intent-target"),
                pressure_downgraded: false,
                budget_blocked: false,
                budget_warning: None,
                triage_filter_level: 0,
            };
        }
    }

    if let Some(root) = project_root
        && let Some(open) = try_load_graph(root)
    {
        let gp = &open.provider;
        let related = gp.related(path, 1);
        if let Some(task_str) = task {
            let intent = crate::core::intent_engine::StructuredIntent::from_query(task_str);
            for target in &intent.targets {
                let target_related = gp.related(target, 1);
                let norm = crate::core::pathutil::normalize_tool_path(path);
                if target_related
                    .iter()
                    .any(|r| r.contains(&norm) || norm.contains(r))
                {
                    return PreDispatchResult {
                        overridden_mode: Some("map".to_string()),
                        reason: Some("graph-direct-import"),
                        pressure_downgraded: false,
                        budget_blocked: false,
                        budget_warning: None,
                        triage_filter_level: 0,
                    };
                }
            }
        }
        if !related.is_empty() && requested_mode == "auto" {
            let reverse_deps = gp.dependents(path);
            if reverse_deps.len() > 3 {
                return PreDispatchResult {
                    overridden_mode: Some("map".to_string()),
                    reason: Some("graph-hub-file"),
                    pressure_downgraded: false,
                    budget_blocked: false,
                    budget_warning: None,
                    triage_filter_level: 0,
                };
            }
        }
    }

    if let Some(root) = project_root
        && let Some(knowledge) = crate::core::knowledge::ProjectKnowledge::load(root)
    {
        let norm = crate::core::pathutil::normalize_tool_path(path);
        let mentions = knowledge
            .facts
            .iter()
            .filter(|f| f.value.contains(&norm) || f.key.contains(&norm))
            .count();
        if mentions >= 3 {
            return PreDispatchResult {
                overridden_mode: Some("map".to_string()),
                reason: Some("knowledge-high-relevance"),
                pressure_downgraded: false,
                budget_blocked: false,
                budget_warning: None,
                triage_filter_level: 0,
            };
        }
    }

    no_change
}

fn estimate_read_tokens(path: &str, mode: &str) -> usize {
    let file_size = std::fs::metadata(path).map_or(4000, |m| m.len() as usize);
    let char_estimate = file_size;
    let full_tokens = char_estimate / 4;
    match mode {
        "signatures" => full_tokens / 5,
        "map" => full_tokens / 3,
        "aggressive" | "entropy" => full_tokens / 4,
        "diff" => full_tokens / 10,
        _ if mode.starts_with("lines:") => {
            if let Some(range) = mode.strip_prefix("lines:") {
                // #971: comma is multi-select. Splitting the whole payload on
                // '-' yields 3 parts for `620-622,1214-1218` and fell through to
                // the whole-file tenth; sum the selected spans instead.
                let mut selected = 0usize;
                for part in range.split(',') {
                    let part = part.trim();
                    selected += if let Some((s, e)) = part.split_once('-') {
                        let start = s.trim().parse::<usize>().unwrap_or(1);
                        let end = e.trim().parse::<usize>().unwrap_or(start + 100);
                        end.saturating_sub(start) + 1
                    } else {
                        1
                    };
                }
                if selected == 0 {
                    full_tokens / 10
                } else {
                    selected * 10
                }
            } else {
                full_tokens / 10
            }
        }
        _ => full_tokens,
    }
}

fn pressure_downgrade(requested_mode: &str, action: &PressureAction) -> Option<String> {
    crate::core::auto_mode_resolver::pressure_downgrade(requested_mode, action)
}

fn check_overlay_mode_override(
    path: &str,
    requested_mode: &str,
    overlay: &OverlayStore,
) -> Option<PreDispatchResult> {
    let item_id = ContextItemId::from_file(path);
    let overlays = overlay.for_item(&item_id);

    for ov in overlays.iter().rev() {
        match &ov.operation {
            OverlayOp::SetView(view) => {
                let mode_str = view.as_str();
                if mode_str != requested_mode {
                    return Some(PreDispatchResult {
                        overridden_mode: Some(mode_str.to_string()),
                        reason: Some("overlay-set-view"),
                        pressure_downgraded: false,
                        budget_blocked: false,
                        budget_warning: None,
                        triage_filter_level: 0,
                    });
                }
            }
            OverlayOp::Pin { .. } if requested_mode != "full" => {
                return Some(PreDispatchResult {
                    overridden_mode: Some("full".to_string()),
                    reason: Some("pinned"),
                    pressure_downgraded: false,
                    budget_blocked: false,
                    budget_warning: None,
                    triage_filter_level: 0,
                });
            }
            OverlayOp::Exclude { .. } if requested_mode != "signatures" => {
                return Some(PreDispatchResult {
                    overridden_mode: Some("signatures".to_string()),
                    reason: Some("excluded"),
                    pressure_downgraded: false,
                    budget_blocked: false,
                    budget_warning: None,
                    triage_filter_level: 0,
                });
            }
            _ => {}
        }
    }
    None
}

pub fn post_dispatch_record(
    path: &str,
    mode: &str,
    original_tokens: usize,
    sent_tokens: usize,
    ledger: &mut ContextLedger,
    overlay: &OverlayStore,
) -> PostDispatchResult {
    post_dispatch_record_with_task(
        path,
        mode,
        original_tokens,
        sent_tokens,
        ledger,
        overlay,
        None,
        None,
    )
}

pub fn post_dispatch_record_with_task(
    path: &str,
    mode: &str,
    original_tokens: usize,
    sent_tokens: usize,
    ledger: &mut ContextLedger,
    overlay: &OverlayStore,
    task: Option<&str>,
    project_root: Option<&str>,
) -> PostDispatchResult {
    let prev_count = ledger.entries.len();
    let prev_pressure = ledger.pressure().recommendation;

    ledger.record_with_task(path, mode, original_tokens, sent_tokens, task);

    let item_id = ContextItemId::from_file(path);
    let state = overlay.apply_to_state(&item_id, ContextState::Included);

    if state == ContextState::Excluded {
        return PostDispatchResult {
            eviction_hint: Some(format!("File '{path}' is excluded by overlay.")),
            elicitation_hint: None,
            resource_changed: true,
            prefetch_hint: None,
        };
    }

    let elicitation =
        super::elicitation::check_elicitation_needed(ledger, Some(path), Some(sent_tokens))
            .map(|s| s.format_fallback_hint());

    let pressure = ledger.pressure();

    // #6 Global-Workspace ignition: salience outliers are broadcast (pinned) into
    // the working set BEFORE reinjection, so an ignited item keeps its view while
    // the rest are downgraded under pressure. Deterministic z-score threshold.
    let ignited = ledger.ignite_high_salience();

    apply_reinjection_plan(ledger, &pressure.recommendation);

    let new_entry = ledger.entries.len() != prev_count;
    let pressure_shifted = pressure.recommendation != prev_pressure;
    let resource_changed = new_entry || pressure_shifted || !ignited.is_empty();

    if pressure.utilization > 0.9 {
        let candidates = ledger.eviction_candidates_by_phi(3);
        if !candidates.is_empty() {
            // #715: emit targets the evict resolver can actually find —
            // root-relative paths (or the full path), never display-shortened
            // forms that used to produce "Evicted 0/N".
            let names: Vec<_> = candidates
                .iter()
                .take(3)
                .map(|p| eviction_target_display(p, project_root))
                .collect();
            return PostDispatchResult {
                eviction_hint: Some(format!(
                    "Context pressure {:.0}%. Evict: ctx_ledger(action=\"evict\", targets=\"{}\")",
                    pressure.utilization * 100.0,
                    names.join(", ")
                )),
                elicitation_hint: elicitation,
                resource_changed,
                // Under pressure we evict rather than prefetch — no warmup hint.
                prefetch_hint: None,
            };
        }
    }

    // #9 FEP prefetch: with budget to spare, suggest the files most likely needed
    // next (co-access graph), so the agent can warm them before the surprise of a
    // miss. Deterministic; runs in the background post-dispatch, never in output.
    let prefetch_hint =
        project_root.and_then(|root| crate::core::fep_prefetch::prefetch_hint(root, path, ledger));

    PostDispatchResult {
        eviction_hint: None,
        elicitation_hint: elicitation,
        resource_changed,
        prefetch_hint,
    }
}

/// #715: a resolvable evict target for hint output — project-root-relative
/// when the candidate lives under the root, otherwise the full canonical
/// path. Both forms round-trip through `ContextLedger::resolve_entry`.
fn eviction_target_display(path: &str, project_root: Option<&str>) -> String {
    if let Some(root) = project_root.filter(|r| !r.is_empty()) {
        let root_prefix = format!("{}/", root.trim_end_matches(['/', '\\']).replace('\\', "/"));
        if let Some(rel) = path.strip_prefix(&root_prefix)
            && !rel.is_empty()
        {
            return rel.to_string();
        }
    }
    path.to_string()
}

fn apply_reinjection_plan(ledger: &mut ContextLedger, action: &PressureAction) {
    if *action != PressureAction::ForceCompression && *action != PressureAction::EvictLeastRelevant
    {
        return;
    }
    for entry in &mut ledger.entries {
        // #6: ignited / user-pinned items stay broadcast — never downgraded.
        if entry.state == Some(ContextState::Pinned) {
            continue;
        }
        if entry.mode == "full" {
            entry.mode = "map".to_string();
        }
    }
}

fn try_load_graph(project_root: &str) -> Option<crate::core::graph_provider::OpenGraphProvider> {
    crate::core::graph_provider::open_best_effort(project_root)
}

/// Determines the output-filtering aggressiveness from a task profile.
///
/// Fail-safe by construction (community reports on 3.9.19, "triage always
/// level 2"): the original ladder inverted fail-safety — the empty-query
/// fallback profile landed on the MOST aggressive level, and per-tool-call
/// profiles almost always report a low context need (a single tool call
/// classifies as SingleFile, base 250). A rules-derived profile can now
/// select at most level 1; uncertainty degrades toward passthrough, never
/// toward harder filtering.
pub fn triage_filter_level(profile: &crate::core::triage::profile::TaskProfileLocal) -> u8 {
    use crate::core::triage::confidence::ACTIONABLE_FLOOR_MILLI;
    // An unset context need means "unknown", never "needs no context".
    if profile.confidence_milli < ACTIONABLE_FLOOR_MILLI || profile.context_need_milli == 0 {
        return 0;
    }
    // Level 2 removes declarations and leaves output that parses but no longer
    // means what it says (#1484). Nothing in a rules-derived profile is precise
    // enough to justify that: `confidence_milli` measures how sure the intent
    // classification is, not how much information loss the output tolerates.
    // The level stays reachable through `apply_triage_filter` for callers that
    // ask for it — where it is additionally markdown-only, so source code and
    // logs never lose non-comment lines — and should return here again only
    // once a model backend can supply that prediction.
    u8::from(profile.context_need_milli < 600)
}

/// Filters output according to the task profile and selected triage level.
pub fn apply_triage_filter(
    output: &str,
    profile: &crate::core::triage::profile::TaskProfileLocal,
    level: u8,
) -> (String, usize) {
    if level == 0 || output.chars().count() < 500 {
        return (output.to_string(), 0);
    }

    // Never filter structured JSON output — the line-based heuristics destroy
    // key-value pairs while keeping only braces, producing invalid JSON.
    let trimmed = output.trim_start();
    if (trimmed.starts_with('{') || trimmed.starts_with('['))
        && serde_json::from_str::<serde_json::Value>(trimmed).is_ok()
    {
        return (output.to_string(), 0);
    }

    let lines: Vec<&str> = output.lines().collect();

    // Also bypass when JSON is embedded after a short header (e.g. "ctx_handoff show\n path: …\n{…}")
    if let Some(json_start) = lines.iter().position(|l| {
        let t = l.trim_start();
        t.starts_with('{') || t.starts_with('[')
    }) {
        let json_portion = lines[json_start..].join("\n");
        if serde_json::from_str::<serde_json::Value>(&json_portion).is_ok() {
            return (output.to_string(), 0);
        }
    }
    // Build a set of kept lines for O(1) lookup.
    let keep: std::collections::HashSet<usize> = match level {
        1 => lines
            .iter()
            .enumerate()
            .filter(|(_, line)| !is_boilerplate_line(line.trim_start()))
            .map(|(i, _)| i)
            .collect(),
        2 => {
            let keywords = extract_task_keywords(&profile.task_class, &profile.intent);
            if crate::core::triage::markdown::looks_like_markdown(&lines) {
                crate::core::triage::markdown::keep_indices(&lines, &keywords)
            } else {
                // Community report (3.9.19, "abridged into something that
                // still looks right"): the structural+keyword keep-set is
                // provably unsafe for source code — plain `let` bindings
                // vanished from a Rust fn while the survivors still parsed
                // (21 of 36 lines dropped, output looked complete, bindings
                // became undeclared). Line-level lossy triage is therefore
                // markdown-only; every other content shape gets at most the
                // level-1 boilerplate strip.
                lines
                    .iter()
                    .enumerate()
                    .filter(|(_, line)| !is_boilerplate_line(line.trim_start()))
                    .map(|(i, _)| i)
                    .collect()
            }
        }
        _ => return (output.to_string(), 0),
    };

    // #1484: assemble output with inline elision markers so omissions are visible.
    let removed = lines.len().saturating_sub(keep.len());
    if removed == 0 {
        return (output.to_string(), 0);
    }
    // #1493: total deletion (100% of lines removed) is never a useful
    // compression outcome — the marker plus retry costs more than passing
    // through the original content. Return unfiltered when nothing survives.
    if keep.is_empty() {
        return (output.to_string(), 0);
    }
    // Heading-only markdown is the same failure mode: ATX titles survive the
    // markdown keep-set so `keep` is non-empty, but every body paragraph is
    // gone. Pass through instead of returning a TOC.
    if crate::core::triage::markdown::is_heading_only_collapse(&lines, &keep) {
        return (output.to_string(), 0);
    }
    let mut result = String::with_capacity(output.len());
    let mut consecutive_omitted: usize = 0;
    for (i, line) in lines.iter().enumerate() {
        if keep.contains(&i) {
            if consecutive_omitted > 0 {
                result.push_str(&format!(
                    "  [...{consecutive_omitted} lines omitted by triage...]\n"
                ));
                consecutive_omitted = 0;
            }
            result.push_str(line);
            result.push('\n');
        } else {
            consecutive_omitted += 1;
        }
    }
    if consecutive_omitted > 0 {
        result.push_str(&format!(
            "  [...{consecutive_omitted} lines omitted by triage...]\n"
        ));
    }
    result.push_str(&format!(
        "[lean-ctx: {removed} lines filtered by triage (level {level}) — rerun with raw=true for the unfiltered output]"
    ));
    (result, removed)
}

fn extract_task_keywords(task_class: &str, intent: &str) -> Vec<String> {
    let mut keywords = task_class
        .split(|character: char| !character.is_alphanumeric())
        .chain(intent.split(|character: char| !character.is_alphanumeric()))
        .filter(|keyword| !keyword.is_empty())
        .map(str::to_lowercase)
        .collect::<Vec<_>>();
    keywords.sort_unstable();
    keywords.dedup();
    keywords
}

fn is_boilerplate_line(line: &str) -> bool {
    line.starts_with("//")
        && !line.contains("TODO")
        && !line.contains("FIXME")
        && !line.contains("SAFETY")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::triage::profile::TaskProfileLocal;

    #[test]
    fn eviction_target_display_emits_resolvable_targets() {
        // #715: root-relative when under the root, full path otherwise —
        // never a display-shortened form the resolver cannot find.
        assert_eq!(
            eviction_target_display("/w/proj/src/a.rs", Some("/w/proj")),
            "src/a.rs"
        );
        assert_eq!(
            eviction_target_display("/other/b.rs", Some("/w/proj")),
            "/other/b.rs"
        );
        assert_eq!(eviction_target_display("/x/c.rs", None), "/x/c.rs");
    }

    #[test]
    fn pre_dispatch_passthrough_for_full() {
        let result = pre_dispatch_read("src/main.rs", "full", None, None, None);
        assert!(result.overridden_mode.is_none());
    }

    #[test]
    fn pre_dispatch_passthrough_for_diff() {
        let result = pre_dispatch_read("src/main.rs", "diff", None, None, None);
        assert!(result.overridden_mode.is_none());
    }

    #[test]
    fn pre_dispatch_passthrough_for_anchored_window() {
        // #843: a windowed anchored:N-M read must keep its hash anchors —
        // bounce-prevention, pressure-downgrade, etc. must not clobber it to
        // "full" and silently drop the window.
        {
            let mut bt = crate::core::bounce_tracker::global()
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            bt.set_seq(101);
            bt.record_read("anchored-bouncy.yml", "map", 30, 400);
            bt.set_seq(102);
            bt.record_read("anchored-bouncy.yml", "full", 400, 400);
            bt.set_seq(103);
            bt.record_read("a2.yml", "map", 30, 400);
            bt.set_seq(104);
            bt.record_read("a2.yml", "full", 400, 400);
            bt.set_seq(105);
            bt.record_read("a3.yml", "map", 30, 400);
            bt.set_seq(106);
            bt.record_read("a3.yml", "full", 400, 400);
        }
        let result = pre_dispatch_read("anchored-new.yml", "anchored:10-40", None, None, None);
        assert!(
            result.overridden_mode.is_none(),
            "anchored:N-M must not be overridden by bounce-prevention"
        );
        let bare = pre_dispatch_read("anchored-new.yml", "anchored", None, None, None);
        assert!(
            bare.overridden_mode.is_none(),
            "bare anchored mode must not be overridden by bounce-prevention"
        );
    }

    #[test]
    fn pre_dispatch_passthrough_for_lines_multi_select() {
        // #971: `lines:A-B,C-D` is a precise pinned window exactly like
        // `lines:A-B`, but it parsed as Malformed, so `is_precise_pinned_mode`
        // reported "not pinned" and bounce-prevention rewrote an 8-line request
        // into a full-file read. Exercises the edit-forced branch, which is what
        // the field report actually hit (a ctx_patch anchored edit immediately
        // before the read).
        {
            let mut bt = crate::core::bounce_tracker::global()
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            bt.set_seq(201);
            bt.record_edit("multi-select-971.rs");
            bt.set_seq(202);
        }

        // Precondition: the tracker really is armed for this path, so the
        // assertions below cannot pass vacuously.
        let forced = pre_dispatch_read("multi-select-971.rs", "map", None, None, None);
        assert_eq!(
            forced.overridden_mode.as_deref(),
            Some("full"),
            "precondition: a recent edit must force a non-pinned mode to full"
        );

        let multi = pre_dispatch_read(
            "multi-select-971.rs",
            "lines:620-622,1214-1218",
            None,
            None,
            None,
        );
        assert!(
            multi.overridden_mode.is_none(),
            "lines:A-B,C-D must not be overridden by bounce-prevention (#971)"
        );

        // Control: the single-range form was already protected.
        let single = pre_dispatch_read("multi-select-971.rs", "lines:620-622", None, None, None);
        assert!(
            single.overridden_mode.is_none(),
            "lines:A-B must not be overridden by bounce-prevention"
        );
    }

    #[test]
    fn fresh_escapes_bounce_prevention() {
        // #1588: after an edit the gate pins the file to `full`. Without an
        // escape hatch, signatures/map/reference stay unreachable for the rest
        // of the session — `fresh=true` is that hatch.
        {
            let mut bt = crate::core::bounce_tracker::global()
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            bt.set_seq(301);
            bt.record_edit("fresh-escape-1586.rs");
            bt.set_seq(302);
        }

        let pinned = pre_dispatch_read("fresh-escape-1586.rs", "signatures", None, None, None);
        assert_eq!(
            pinned.overridden_mode.as_deref(),
            Some("full"),
            "precondition: the tracker must actually be armed for this path"
        );

        let escaped = pre_dispatch_read_for_agent(
            "fresh-escape-1586.rs",
            "signatures",
            None,
            None,
            None,
            None,
            true,
        );
        assert!(
            escaped.overridden_mode.is_none(),
            "fresh=true must keep the requested mode reachable"
        );
    }

    #[test]
    fn intent_target_matches_whole_components_only() {
        // #1588: substring matching pinned unrelated files to `full`.
        assert!(path_matches_target(
            "/repo/src/server/context_gate.rs",
            "context_gate"
        ));
        assert!(path_matches_target(
            "/repo/src/server/context_gate.rs",
            "context_gate.rs"
        ));
        assert!(path_matches_target(
            "/repo/src/server/context_gate.rs",
            "src/server/context_gate.rs"
        ));

        assert!(
            !path_matches_target("/repo/src/printer/link_gate.rs", "print"),
            "a target must not match the middle of a longer component"
        );
        assert!(
            !path_matches_target("/repo/src/server/context_gate.rs", "src"),
            "targets below the minimum length are noise, not names"
        );
        assert!(!path_matches_target(
            "/repo/src/server/context_gate.rs",
            "gate"
        ));
    }

    #[test]
    fn fresh_escapes_intent_target() {
        let result = pre_dispatch_read_for_agent(
            "/repo/src/server/context_gate.rs",
            "reference",
            Some("fix context_gate overrides"),
            None,
            None,
            None,
            true,
        );
        assert!(
            result.overridden_mode.is_none(),
            "fresh=true must also escape the intent-target override"
        );
    }

    #[test]
    fn pre_dispatch_no_override_without_signals() {
        let result = pre_dispatch_read("src/unknown.rs", "auto", None, None, None);
        assert!(result.overridden_mode.is_none());
    }

    #[test]
    fn pre_dispatch_bounce_prevention_forces_full() {
        {
            let mut bt = crate::core::bounce_tracker::global()
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            bt.set_seq(1);
            bt.record_read("src/bouncy.yml", "map", 30, 400);
            bt.set_seq(2);
            bt.record_read("src/bouncy.yml", "full", 400, 400);
            bt.set_seq(3);
            bt.record_read("a2.yml", "map", 30, 400);
            bt.set_seq(4);
            bt.record_read("a2.yml", "full", 400, 400);
            bt.set_seq(5);
            bt.record_read("a3.yml", "map", 30, 400);
            bt.set_seq(6);
            bt.record_read("a3.yml", "full", 400, 400);
        }
        let result = pre_dispatch_read("new.yml", "auto", None, None, None);
        assert_eq!(result.overridden_mode, Some("full".to_string()));
        assert_eq!(result.reason, Some("bounce-prevention"));
    }

    #[test]
    fn pressure_does_not_downgrade_explicit_full() {
        let result = pre_dispatch_read(
            "c.rs",
            "full",
            None,
            None,
            Some(&PressureAction::ForceCompression),
        );
        assert!(
            result.overridden_mode.is_none(),
            "explicit mode=full must never be downgraded by pressure"
        );
        assert!(!result.pressure_downgraded);
    }

    #[test]
    fn pressure_does_not_downgrade_when_enforce_off() {
        // Default profile has degradation.enforce = false, so pressure
        // should NOT downgrade any mode.
        let result = pre_dispatch_read(
            "c.rs",
            "map",
            None,
            None,
            Some(&PressureAction::EvictLeastRelevant),
        );
        assert!(
            result.overridden_mode.is_none(),
            "pressure must not downgrade when degradation.enforce is off"
        );
        assert!(!result.pressure_downgraded);
    }

    #[test]
    fn no_pressure_downgrade_when_low() {
        let result = pre_dispatch_read("c.rs", "full", None, None, Some(&PressureAction::NoAction));
        assert!(result.overridden_mode.is_none());
        assert!(!result.pressure_downgraded);
    }

    #[test]
    fn suggest_compression_does_not_downgrade_when_enforce_off() {
        // Default profile has degradation.enforce = false
        let result = pre_dispatch_read(
            "c.rs",
            "auto",
            None,
            None,
            Some(&PressureAction::SuggestCompression),
        );
        assert!(
            result.overridden_mode.is_none(),
            "suggest_compression must not downgrade when enforce is off"
        );
        assert!(!result.pressure_downgraded);
    }

    #[test]
    fn suggest_compression_does_not_touch_explicit_full() {
        let result = pre_dispatch_read(
            "c.rs",
            "full",
            None,
            None,
            Some(&PressureAction::SuggestCompression),
        );
        assert!(result.overridden_mode.is_none());
        assert!(!result.pressure_downgraded);
    }

    #[test]
    fn post_dispatch_reinjection_downgrades_entries() {
        let mut ledger = ContextLedger::with_window_size(1000);
        ledger.record("a.rs", "full", 400, 400);
        ledger.record("b.rs", "full", 400, 400);
        let overlay = OverlayStore::new();
        let result = post_dispatch_record("c.rs", "full", 300, 300, &mut ledger, &overlay);
        assert!(result.resource_changed);
        let a_entry = ledger.entries.iter().find(|e| e.path == "a.rs").unwrap();
        assert_eq!(a_entry.mode, "map");
    }

    #[test]
    fn ignited_item_resists_reinjection_downgrade() {
        // #6: a high-salience outlier ignites (pins) and keeps its full view,
        // while the rest are downgraded to map by pressure reinjection.
        let mut ledger = ContextLedger::with_window_size(1000);
        for i in 0..5 {
            ledger.record(&format!("bg{i}.rs"), "full", 250, 250);
        }
        ledger.record("hot.rs", "full", 250, 250);
        // Set the salience distribution explicitly (record recomputes Phi, so we
        // overwrite afterwards) to make ignition deterministic in the test.
        for e in &mut ledger.entries {
            e.phi = Some(if e.path == "hot.rs" { 0.97 } else { 0.1 });
        }
        let ignited = ledger.ignite_high_salience();
        assert_eq!(ignited, vec!["hot.rs".to_string()], "outlier should ignite");

        apply_reinjection_plan(&mut ledger, &PressureAction::ForceCompression);
        let hot = ledger.entries.iter().find(|e| e.path == "hot.rs").unwrap();
        assert_eq!(hot.mode, "full", "ignited item keeps its full view");
        let bg = ledger.entries.iter().find(|e| e.path == "bg0.rs").unwrap();
        assert_eq!(bg.mode, "map", "non-ignited items are downgraded");
    }

    #[test]
    fn overlay_pin_forces_full_mode() {
        let dir = tempfile::tempdir().expect("tmp dir");
        let root = dir.path();
        let mut store = OverlayStore::new();
        let target = ContextItemId::from_file("src/important.rs");
        store.add(crate::core::context_overlay::ContextOverlay::new(
            target,
            OverlayOp::Pin { verbatim: false },
            crate::core::context_overlay::OverlayScope::Project,
            String::new(),
            crate::core::context_overlay::OverlayAuthor::User,
        ));
        store.save_project(root).unwrap();

        let result = pre_dispatch_read(
            "src/important.rs",
            "auto",
            None,
            Some(root.to_str().unwrap()),
            None,
        );
        assert_eq!(result.overridden_mode, Some("full".to_string()));
        assert_eq!(result.reason, Some("pinned"));
    }

    #[test]
    fn overlay_exclude_forces_signatures_mode() {
        let dir = tempfile::tempdir().expect("tmp dir");
        let root = dir.path();
        let mut store = OverlayStore::new();
        let target = ContextItemId::from_file("src/noisy.rs");
        store.add(crate::core::context_overlay::ContextOverlay::new(
            target,
            OverlayOp::Exclude {
                reason: "noise".to_string(),
            },
            crate::core::context_overlay::OverlayScope::Project,
            String::new(),
            crate::core::context_overlay::OverlayAuthor::User,
        ));
        store.save_project(root).unwrap();

        let result = pre_dispatch_read(
            "src/noisy.rs",
            "auto",
            None,
            Some(root.to_str().unwrap()),
            None,
        );
        assert_eq!(result.overridden_mode, Some("signatures".to_string()));
        assert_eq!(result.reason, Some("excluded"));
    }

    // --- pressure_downgrade unit tests (pure function) ---

    #[test]
    fn pressure_downgrade_suggest_auto_to_map() {
        let result = pressure_downgrade("auto", &PressureAction::SuggestCompression);
        assert_eq!(result, Some("map".to_string()));
    }

    #[test]
    fn pressure_downgrade_suggest_full_to_map() {
        let result = pressure_downgrade("full", &PressureAction::SuggestCompression);
        assert_eq!(result, Some("map".to_string()));
    }

    #[test]
    fn pressure_downgrade_suggest_does_not_touch_signatures() {
        let result = pressure_downgrade("signatures", &PressureAction::SuggestCompression);
        assert!(result.is_none());
    }

    #[test]
    fn pressure_downgrade_suggest_does_not_touch_diff() {
        let result = pressure_downgrade("diff", &PressureAction::SuggestCompression);
        assert!(result.is_none());
    }

    #[test]
    fn pressure_downgrade_force_full_to_map() {
        let result = pressure_downgrade("full", &PressureAction::ForceCompression);
        assert_eq!(result, Some("map".to_string()));
    }

    #[test]
    fn pressure_downgrade_force_auto_to_signatures() {
        let result = pressure_downgrade("auto", &PressureAction::ForceCompression);
        assert_eq!(result, Some("signatures".to_string()));
    }

    #[test]
    fn pressure_downgrade_force_map_to_signatures() {
        let result = pressure_downgrade("map", &PressureAction::ForceCompression);
        assert_eq!(result, Some("signatures".to_string()));
    }

    #[test]
    fn pressure_downgrade_force_does_not_touch_signatures() {
        let result = pressure_downgrade("signatures", &PressureAction::ForceCompression);
        assert!(result.is_none());
    }

    #[test]
    fn pressure_downgrade_force_does_not_touch_lines() {
        let result = pressure_downgrade("lines:1-50", &PressureAction::ForceCompression);
        assert!(result.is_none());
    }

    #[test]
    fn pressure_downgrade_evict_full_to_map() {
        let result = pressure_downgrade("full", &PressureAction::EvictLeastRelevant);
        assert_eq!(result, Some("map".to_string()));
    }

    #[test]
    fn pressure_downgrade_evict_auto_to_signatures() {
        let result = pressure_downgrade("auto", &PressureAction::EvictLeastRelevant);
        assert_eq!(result, Some("signatures".to_string()));
    }

    #[test]
    fn pressure_downgrade_evict_map_to_signatures() {
        let result = pressure_downgrade("map", &PressureAction::EvictLeastRelevant);
        assert_eq!(result, Some("signatures".to_string()));
    }

    #[test]
    fn pressure_downgrade_noaction_returns_none() {
        let result = pressure_downgrade("full", &PressureAction::NoAction);
        assert!(result.is_none());
    }

    #[test]
    fn pressure_downgrade_noaction_auto_returns_none() {
        let result = pressure_downgrade("auto", &PressureAction::NoAction);
        assert!(result.is_none());
    }

    // --- pre_dispatch_inner: no_degrade integration ---
    // When LCTX_NO_DEGRADE is NOT set (test default), pressure downgrade is active.

    #[test]
    fn pre_dispatch_does_not_downgrade_full_under_force() {
        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
            return;
        }
        // Explicit mode=full is protected: pressure cannot downgrade it
        let result = pre_dispatch_read(
            "nd_test.rs",
            "full",
            None,
            None,
            Some(&PressureAction::ForceCompression),
        );
        assert!(result.overridden_mode.is_none());
        assert!(!result.pressure_downgraded);
    }

    #[test]
    fn pre_dispatch_does_not_downgrade_auto_when_enforce_off() {
        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
            return;
        }
        // Default profile has degradation.enforce = false, so pressure
        // should not downgrade even non-full modes
        let result = pre_dispatch_read(
            "nd_test2.rs",
            "auto",
            None,
            None,
            Some(&PressureAction::EvictLeastRelevant),
        );
        assert!(result.overridden_mode.is_none());
        assert!(!result.pressure_downgraded);
    }

    // --- estimate_read_tokens unit tests ---

    #[test]
    fn estimate_tokens_diff_mode_is_small() {
        let tokens = estimate_read_tokens("nonexistent.rs", "diff");
        assert!(tokens < 500, "diff mode should estimate low: got {tokens}");
    }

    #[test]
    fn estimate_tokens_signatures_smaller_than_full() {
        let sig = estimate_read_tokens("nonexistent.rs", "signatures");
        let full = estimate_read_tokens("nonexistent.rs", "full");
        assert!(sig < full, "signatures={sig} should be < full={full}");
    }

    #[test]
    fn estimate_tokens_lines_range() {
        let tokens = estimate_read_tokens("nonexistent.rs", "lines:1-10");
        assert!(tokens <= 200, "lines:1-10 should be small: got {tokens}");
    }

    #[test]
    fn overlay_set_view_forces_specified_mode() {
        let dir = tempfile::tempdir().expect("tmp dir");
        let root = dir.path();
        let mut store = OverlayStore::new();
        let target = ContextItemId::from_file("src/big.rs");
        store.add(crate::core::context_overlay::ContextOverlay::new(
            target,
            OverlayOp::SetView(crate::core::context_field::ViewKind::Map),
            crate::core::context_overlay::OverlayScope::Project,
            String::new(),
            crate::core::context_overlay::OverlayAuthor::User,
        ));
        store.save_project(root).unwrap();

        let result = pre_dispatch_read(
            "src/big.rs",
            "auto",
            None,
            Some(root.to_str().unwrap()),
            None,
        );
        assert_eq!(result.overridden_mode, Some("map".to_string()));
        assert_eq!(result.reason, Some("overlay-set-view"));
    }
    use crate::core::triage::profile::TaskScopeLocal;

    fn test_profile(confidence: u16, context_need: u16) -> TaskProfileLocal {
        TaskProfileLocal {
            task_class: "bug_fix".into(),
            intent: "fix context gate filtering".into(),
            complexity: "low".into(),
            scope: TaskScopeLocal::SingleFile,
            context_need_milli: context_need,
            reasoning_need_milli: 0,
            risk_signal_milli: 0,
            confidence_milli: confidence,
        }
    }

    #[test]
    fn triage_filter_level_selects_expected_level() {
        for (confidence, context_need, expected) in [
            (200, 200, 0),
            // context_need == 0 means "unknown", never "needs no context" —
            // the fallback profile must pass through untouched.
            (300, 0, 0),
            (500, 0, 0),
            (500, 200, 1),
            (500, 450, 1),
            (500, 700, 0),
            // A rules-derived profile never selects the lossy level 2, no
            // matter how confident the intent classification is.
            (700, 200, 1),
            (700, 450, 1),
            (700, 700, 0),
            (1000, 100, 1),
        ] {
            assert_eq!(
                triage_filter_level(&test_profile(confidence, context_need)),
                expected,
                "confidence={confidence} context_need={context_need}"
            );
        }
    }

    #[test]
    fn no_model_installed_means_passthrough() {
        use crate::core::triage::{TaskAnalysisInput, TaskAnalyzer, rules::RuleTriageBackend};

        let profile = RuleTriageBackend
            .analyze(&TaskAnalysisInput::default())
            .unwrap()
            .profile;
        assert_eq!(triage_filter_level(&profile), 0);
    }

    #[test]
    fn apply_triage_filter_level_zero_is_passthrough() {
        let profile = test_profile(500, 200);
        let output = "// boilerplate\n".repeat(40);
        assert_eq!(apply_triage_filter(&output, &profile, 0), (output, 0));
    }

    #[test]
    fn apply_triage_filter_short_output_is_passthrough() {
        let profile = test_profile(500, 200);
        let output = "fn main() {\n    println!(\"hi\");\n}";
        assert_eq!(apply_triage_filter(output, &profile, 2), (output.into(), 0));
    }

    #[test]
    fn apply_triage_filter_level_one_preserves_actionable_comments() {
        let profile = test_profile(500, 450);
        let output = "// boilerplate comment\n".repeat(30)
            + "// TODO: keep this\n// FIXME: keep this\n// SAFETY: keep this\nfn keep_me() {}\n";
        let (filtered, removed) = apply_triage_filter(&output, &profile, 1);
        assert!(!filtered.contains("// boilerplate comment"));
        assert!(filtered.contains("// TODO: keep this"));
        assert!(filtered.contains("// FIXME: keep this"));
        assert!(filtered.contains("// SAFETY: keep this"));
        assert!(
            filtered
                .contains("[lean-ctx: 30 lines filtered by triage (level 1) — rerun with raw=true")
        );
        assert_eq!(removed, 30);
    }

    /// Community regression (3.9.19 "abridged into something that still looks
    /// right"): level 2 on NON-markdown content must never delete a
    /// non-comment line — plain `let` bindings used to vanish from source
    /// files while the survivors still parsed.
    #[test]
    fn apply_triage_filter_level_two_never_drops_code_lines() {
        let profile = test_profile(700, 200);
        let output = "// boilerplate noise\n".repeat(20)
            + "pub fn read_identity() -> Identity {\n"
            + "    let serial = read_serial();\n"
            + "    let model = read_model();\n"
            + "    Identity { serial, model }\n"
            + "}\n";
        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
        // Every code line survives — especially the plain `let` bindings that
        // carry neither braces, keywords, nor task keywords.
        assert!(filtered.contains("let serial = read_serial();"));
        assert!(filtered.contains("let model = read_model();"));
        assert!(filtered.contains("Identity { serial, model }"));
        // Only the boilerplate comments were stripped, and the footer names
        // the escape hatch.
        assert_eq!(removed, 20);
        assert!(filtered.contains("rerun with raw=true"));
    }

    #[test]
    fn apply_triage_filter_level_two_keeps_keywords_and_structure() {
        let profile = test_profile(500, 200);
        let output = "// unrelated noise about widgets\n".repeat(20)
            + "fix the context gate\n"
            + "pub fn unrelated() {}\n"
            + "#[derive(Debug)]\n"
            + "mod inner {}\n";
        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
        assert!(filtered.contains("fix the context gate"));
        assert!(filtered.contains("pub fn unrelated() {}"));
        assert!(filtered.contains("#[derive(Debug)]"));
        assert!(filtered.contains("mod inner {}"));
        assert!(filtered.contains("[lean-ctx:"));
        assert_eq!(removed, 20);
    }

    #[test]
    fn benchmark_apply_triage_filter() {
        use std::time::Instant;

        let profile = test_profile(500, 200);
        // Use a mix of keyword-matching and non-matching lines so triage
        // actually filters (100% deletion is now a passthrough per #1493).
        let output = "// unrelated noise about widgets\n".repeat(1_999) + "fix the context gate\n";

        let started = Instant::now();
        for _ in 0..1_000 {
            let (_, removed) = apply_triage_filter(&output, &profile, 2);
            assert_eq!(removed, 1_999);
        }
        let average = started.elapsed() / 1_000;
        println!("benchmark_apply_triage_filter: {average:?} per call");
    }

    #[test]
    fn gh1493_total_deletion_returns_original_output() {
        let profile = test_profile(500, 200);
        // 30 lines of plain file names — no keyword match, would be 100% deleted
        let output = (1..=30)
            .map(|i| format!("plugin/device_{i:03}.go"))
            .collect::<Vec<_>>()
            .join("\n");
        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
        assert_eq!(
            removed, 0,
            "100% deletion must be prevented — output should pass through"
        );
        assert_eq!(filtered, output);
    }

    #[test]
    fn extract_task_keywords_normalizes_and_deduplicates() {
        assert_eq!(
            extract_task_keywords("bug_fix", "Fix context-gate"),
            ["bug", "context", "fix", "gate"]
        );
    }

    #[test]
    fn markdown_level_two_keeps_section_leads_not_just_headings() {
        let profile = test_profile(500, 200);
        let filler = "Later filler that restates the same loop in racing language. ".repeat(8);
        let extra = "Ignore this extra dashboard discussion. ".repeat(8);
        let output = [
            "# LeanCTX: The Context SDK for AI Agents",
            "",
            "## The context-performance loop",
            "Connect, measure, tune, prove, deploy, repeat.",
            "",
            filler.as_str(),
            "",
            "## The Receipt is the trust product",
            "A Receipt is evidence, not a decorative log.",
            "",
            extra.as_str(),
            "",
            "## Guardrails",
            "Local runtime, SDK, CLI, and Receipt stay useful offline.",
            "",
            extra.as_str(),
        ]
        .join("\n");
        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
        assert!(
            filtered.contains("Connect, measure, tune, prove"),
            "section lead must survive: {filtered}"
        );
        assert!(
            filtered.contains("A Receipt is evidence"),
            "receipt lead must survive: {filtered}"
        );
        assert!(
            !filtered.contains("racing language"),
            "later filler should drop: {filtered}"
        );
        assert!(removed > 0);
    }
}