Skip to main content

lean_ctx/server/
context_gate.rs

1use crate::core::context_field::{ContextItemId, ContextState};
2use crate::core::context_ledger::{ContextLedger, PressureAction};
3use crate::core::context_overlay::{OverlayOp, OverlayStore};
4
5/// #1570 P4: protected path arguments bypass every lossy output filter.
6pub(super) fn protected_path_requested(
7    args: Option<&serde_json::Map<String, serde_json::Value>>,
8) -> bool {
9    let Some(args) = args else {
10        return false;
11    };
12    let config = crate::core::config::Config::load();
13    if config.protection.file_patterns.is_empty() {
14        return false;
15    }
16    ["path", "file_path", "filePath"].iter().any(|key| {
17        args.get(*key)
18            .and_then(serde_json::Value::as_str)
19            .is_some_and(|path| config.protection.path_is_protected(path))
20    })
21}
22
23/// #843: precise, pinned reads (`diff`, `lines:N-M`, `anchored`/`anchored:N-M`)
24/// must pass through every mode-override path untouched — bounce-prevention,
25/// pressure-downgrade, and the graph/knowledge heuristics below must never
26/// silently reinterpret one of these to e.g. `full`, which would discard the
27/// exact window/anchors/delta the caller asked for. Classifies off the typed
28/// `ReadMode` (single source of truth, see `tools::ctx_read::mode`) rather than
29/// a hand-maintained string-prefix list, so a future precise mode has to be
30/// added to `ReadMode::is_precise_pinned_read` explicitly instead of silently
31/// falling through an allowlist. An unparseable mode is conservatively treated
32/// as *not* pinned, matching prior behaviour for anything outside this set.
33fn is_precise_pinned_mode(requested_mode: &str) -> bool {
34    requested_mode
35        .parse::<crate::tools::ctx_read::ReadMode>()
36        .is_ok_and(|m| m.is_precise_pinned_read())
37}
38
39#[derive(Debug, Clone)]
40pub struct PreDispatchResult {
41    pub overridden_mode: Option<String>,
42    pub reason: Option<&'static str>,
43    pub pressure_downgraded: bool,
44    pub budget_blocked: bool,
45    pub budget_warning: Option<String>,
46    /// Triage-based output filter aggressiveness: 0=passthrough, 1=moderate, 2=aggressive.
47    pub triage_filter_level: u8,
48}
49
50#[derive(Debug, Clone)]
51pub struct PostDispatchResult {
52    pub eviction_hint: Option<String>,
53    pub elicitation_hint: Option<String>,
54    pub resource_changed: bool,
55    /// FEP prefetch suggestion (#9): files likely needed next, from the co-access
56    /// graph. A warmup hint only — never an automatic read.
57    pub prefetch_hint: Option<String>,
58}
59
60/// Best-effort KnowledgeRouter advice for the completed Context Gate flow.
61pub fn knowledge_advice(
62    query: &str,
63) -> crate::core::knowledge_router::gate_integration::KnowledgeAdvice {
64    let current = crate::core::context_kernel::ContextState::new(
65        Vec::new(),
66        crate::core::knowledge::KnowledgeQuery::default(),
67    );
68    crate::core::knowledge_router::gate_integration::KnowledgeGateAdvisor::advise(query, &current)
69}
70
71pub fn pre_dispatch_read(
72    path: &str,
73    requested_mode: &str,
74    task: Option<&str>,
75    project_root: Option<&str>,
76    pressure: Option<&PressureAction>,
77) -> PreDispatchResult {
78    pre_dispatch_read_for_agent(
79        path,
80        requested_mode,
81        task,
82        project_root,
83        pressure,
84        None,
85        false,
86    )
87}
88
89/// `fresh` is the caller's explicit escape hatch (#1588). Bounce-prevention and
90/// intent-target exist to stop an agent from *drifting* into a compressed view
91/// it will immediately re-read in full; neither should be able to pin a file to
92/// `full` forever. A caller who passes `fresh=true` has said, in the request
93/// itself, that they want this view recomputed — honour it, or those modes are
94/// simply unreachable for the rest of the session.
95pub fn pre_dispatch_read_for_agent(
96    path: &str,
97    requested_mode: &str,
98    task: Option<&str>,
99    project_root: Option<&str>,
100    pressure: Option<&PressureAction>,
101    agent_id: Option<&str>,
102    fresh: bool,
103) -> PreDispatchResult {
104    let no_change = PreDispatchResult {
105        overridden_mode: None,
106        reason: None,
107        pressure_downgraded: false,
108        budget_blocked: false,
109        budget_warning: None,
110        triage_filter_level: 0,
111    };
112
113    if let Some(aid) = agent_id {
114        let estimated_tokens = estimate_read_tokens(path, requested_mode);
115        match crate::core::agent_budget::check_budget(aid, estimated_tokens) {
116            crate::core::agent_budget::BudgetCheckResult::Exceeded { limit, consumed } => {
117                return PreDispatchResult {
118                    overridden_mode: None,
119                    reason: Some("agent-budget-exceeded"),
120                    pressure_downgraded: false,
121                    budget_blocked: true,
122                    budget_warning: Some(format!(
123                        "Agent budget exceeded: {consumed}/{limit} tokens consumed. Reset via ctx_session or set a higher limit."
124                    )),
125                    triage_filter_level: 0,
126                };
127            }
128            crate::core::agent_budget::BudgetCheckResult::Warning {
129                remaining,
130                percent_used,
131            } => {
132                let warning = format!(
133                    "[BUDGET WARNING] Agent '{aid}' at {:.0}% budget ({remaining} tokens remaining)",
134                    percent_used * 100.0
135                );
136                let mut result = no_change.clone();
137                result.budget_warning = Some(warning);
138                if is_precise_pinned_mode(requested_mode) {
139                    return result;
140                }
141                let rest =
142                    pre_dispatch_inner(path, requested_mode, task, project_root, pressure, fresh);
143                return PreDispatchResult {
144                    budget_warning: result.budget_warning,
145                    ..rest
146                };
147            }
148            crate::core::agent_budget::BudgetCheckResult::Allowed { .. } => {}
149        }
150    }
151
152    pre_dispatch_inner(path, requested_mode, task, project_root, pressure, fresh)
153}
154
155/// Does `norm` (a normalized path) actually name the intent target `target`?
156///
157/// The old rule was `norm.ends_with(t) || norm.contains(t)`, which matched on
158/// any substring: a task mentioning `src` or `read` pinned every path
159/// containing those letters to `full` (#1588), including matches that land in
160/// the middle of a longer component (`print` inside `printer.rs`). A target now
161/// has to line up with a whole path component or the file stem, and be long
162/// enough to be a name rather than noise.
163fn path_matches_target(norm: &str, target: &str) -> bool {
164    const MIN_TARGET_LEN: usize = 4;
165    let target = target.trim().trim_matches('/');
166    if target.len() < MIN_TARGET_LEN {
167        return false;
168    }
169    // A target that is itself a path suffix (`src/server/context_gate.rs`).
170    if norm == target || norm.ends_with(&format!("/{target}")) {
171        return true;
172    }
173    // Otherwise: a whole path component, with or without its extension.
174    norm.split('/').any(|component| {
175        component == target
176            || component
177                .rsplit_once('.')
178                .is_some_and(|(stem, _)| stem == target)
179    })
180}
181
182fn pre_dispatch_inner(
183    path: &str,
184    requested_mode: &str,
185    task: Option<&str>,
186    project_root: Option<&str>,
187    pressure: Option<&PressureAction>,
188    fresh: bool,
189) -> PreDispatchResult {
190    let no_change = PreDispatchResult {
191        overridden_mode: None,
192        reason: None,
193        pressure_downgraded: false,
194        budget_blocked: false,
195        budget_warning: None,
196        triage_filter_level: 0,
197    };
198
199    if is_precise_pinned_mode(requested_mode) {
200        return no_change;
201    }
202
203    if let Some(root) = project_root {
204        let overlay = OverlayStore::load_project(&std::path::PathBuf::from(root));
205        if let Some(result) = check_overlay_mode_override(path, requested_mode, &overlay) {
206            return result;
207        }
208    }
209
210    // Explicit mode=full must not be downgraded by pressure or other heuristics.
211    // Only overlays (user-explicit) above can override it.
212    if requested_mode == "full" {
213        return no_change;
214    }
215
216    if let Some(action) = pressure {
217        let no_degrade = crate::core::config::Config::load().no_degrade_effective();
218        let profile = crate::core::profiles::active_profile();
219        if !no_degrade
220            && profile.degradation.enforce_effective()
221            && let Some(downgraded) = pressure_downgrade(requested_mode, action)
222        {
223            return PreDispatchResult {
224                overridden_mode: Some(downgraded),
225                reason: Some("pressure-auto-downgrade"),
226                pressure_downgraded: true,
227                budget_blocked: false,
228                budget_warning: None,
229                triage_filter_level: 0,
230            };
231        }
232    }
233
234    // `fresh` is the documented way out (#1588): the caller re-requested this
235    // view deliberately, so the "you keep bouncing back to full" heuristic has
236    // nothing left to prevent.
237    if !fresh
238        && let Ok(bt) = crate::core::bounce_tracker::global().lock()
239        && bt.should_force_full(path)
240    {
241        return PreDispatchResult {
242            overridden_mode: Some("full".to_string()),
243            reason: Some("bounce-prevention"),
244            pressure_downgraded: false,
245            budget_blocked: false,
246            budget_warning: None,
247            triage_filter_level: 0,
248        };
249    }
250
251    if let Some(task_str) = task
252        && !fresh
253    {
254        let intent = crate::core::intent_engine::StructuredIntent::from_query(task_str);
255        let norm = crate::core::pathutil::normalize_tool_path(path);
256        let is_target = intent.targets.iter().any(|t| path_matches_target(&norm, t));
257        if is_target {
258            return PreDispatchResult {
259                overridden_mode: Some("full".to_string()),
260                reason: Some("intent-target"),
261                pressure_downgraded: false,
262                budget_blocked: false,
263                budget_warning: None,
264                triage_filter_level: 0,
265            };
266        }
267    }
268
269    if let Some(root) = project_root
270        && let Some(open) = try_load_graph(root)
271    {
272        let gp = &open.provider;
273        let related = gp.related(path, 1);
274        if let Some(task_str) = task {
275            let intent = crate::core::intent_engine::StructuredIntent::from_query(task_str);
276            for target in &intent.targets {
277                let target_related = gp.related(target, 1);
278                let norm = crate::core::pathutil::normalize_tool_path(path);
279                if target_related
280                    .iter()
281                    .any(|r| r.contains(&norm) || norm.contains(r))
282                {
283                    return PreDispatchResult {
284                        overridden_mode: Some("map".to_string()),
285                        reason: Some("graph-direct-import"),
286                        pressure_downgraded: false,
287                        budget_blocked: false,
288                        budget_warning: None,
289                        triage_filter_level: 0,
290                    };
291                }
292            }
293        }
294        if !related.is_empty() && requested_mode == "auto" {
295            let reverse_deps = gp.dependents(path);
296            if reverse_deps.len() > 3 {
297                return PreDispatchResult {
298                    overridden_mode: Some("map".to_string()),
299                    reason: Some("graph-hub-file"),
300                    pressure_downgraded: false,
301                    budget_blocked: false,
302                    budget_warning: None,
303                    triage_filter_level: 0,
304                };
305            }
306        }
307    }
308
309    if let Some(root) = project_root
310        && let Some(knowledge) = crate::core::knowledge::ProjectKnowledge::load(root)
311    {
312        let norm = crate::core::pathutil::normalize_tool_path(path);
313        let mentions = knowledge
314            .facts
315            .iter()
316            .filter(|f| f.value.contains(&norm) || f.key.contains(&norm))
317            .count();
318        if mentions >= 3 {
319            return PreDispatchResult {
320                overridden_mode: Some("map".to_string()),
321                reason: Some("knowledge-high-relevance"),
322                pressure_downgraded: false,
323                budget_blocked: false,
324                budget_warning: None,
325                triage_filter_level: 0,
326            };
327        }
328    }
329
330    no_change
331}
332
333fn estimate_read_tokens(path: &str, mode: &str) -> usize {
334    let file_size = std::fs::metadata(path).map_or(4000, |m| m.len() as usize);
335    let char_estimate = file_size;
336    let full_tokens = char_estimate / 4;
337    match mode {
338        "signatures" => full_tokens / 5,
339        "map" => full_tokens / 3,
340        "aggressive" | "entropy" => full_tokens / 4,
341        "diff" => full_tokens / 10,
342        _ if mode.starts_with("lines:") => {
343            if let Some(range) = mode.strip_prefix("lines:") {
344                // #971: comma is multi-select. Splitting the whole payload on
345                // '-' yields 3 parts for `620-622,1214-1218` and fell through to
346                // the whole-file tenth; sum the selected spans instead.
347                let mut selected = 0usize;
348                for part in range.split(',') {
349                    let part = part.trim();
350                    selected += if let Some((s, e)) = part.split_once('-') {
351                        let start = s.trim().parse::<usize>().unwrap_or(1);
352                        let end = e.trim().parse::<usize>().unwrap_or(start + 100);
353                        end.saturating_sub(start) + 1
354                    } else {
355                        1
356                    };
357                }
358                if selected == 0 {
359                    full_tokens / 10
360                } else {
361                    selected * 10
362                }
363            } else {
364                full_tokens / 10
365            }
366        }
367        _ => full_tokens,
368    }
369}
370
371fn pressure_downgrade(requested_mode: &str, action: &PressureAction) -> Option<String> {
372    crate::core::auto_mode_resolver::pressure_downgrade(requested_mode, action)
373}
374
375fn check_overlay_mode_override(
376    path: &str,
377    requested_mode: &str,
378    overlay: &OverlayStore,
379) -> Option<PreDispatchResult> {
380    let item_id = ContextItemId::from_file(path);
381    let overlays = overlay.for_item(&item_id);
382
383    for ov in overlays.iter().rev() {
384        match &ov.operation {
385            OverlayOp::SetView(view) => {
386                let mode_str = view.as_str();
387                if mode_str != requested_mode {
388                    return Some(PreDispatchResult {
389                        overridden_mode: Some(mode_str.to_string()),
390                        reason: Some("overlay-set-view"),
391                        pressure_downgraded: false,
392                        budget_blocked: false,
393                        budget_warning: None,
394                        triage_filter_level: 0,
395                    });
396                }
397            }
398            OverlayOp::Pin { .. } if requested_mode != "full" => {
399                return Some(PreDispatchResult {
400                    overridden_mode: Some("full".to_string()),
401                    reason: Some("pinned"),
402                    pressure_downgraded: false,
403                    budget_blocked: false,
404                    budget_warning: None,
405                    triage_filter_level: 0,
406                });
407            }
408            OverlayOp::Exclude { .. } if requested_mode != "signatures" => {
409                return Some(PreDispatchResult {
410                    overridden_mode: Some("signatures".to_string()),
411                    reason: Some("excluded"),
412                    pressure_downgraded: false,
413                    budget_blocked: false,
414                    budget_warning: None,
415                    triage_filter_level: 0,
416                });
417            }
418            _ => {}
419        }
420    }
421    None
422}
423
424pub fn post_dispatch_record(
425    path: &str,
426    mode: &str,
427    original_tokens: usize,
428    sent_tokens: usize,
429    ledger: &mut ContextLedger,
430    overlay: &OverlayStore,
431) -> PostDispatchResult {
432    post_dispatch_record_with_task(
433        path,
434        mode,
435        original_tokens,
436        sent_tokens,
437        ledger,
438        overlay,
439        None,
440        None,
441    )
442}
443
444pub fn post_dispatch_record_with_task(
445    path: &str,
446    mode: &str,
447    original_tokens: usize,
448    sent_tokens: usize,
449    ledger: &mut ContextLedger,
450    overlay: &OverlayStore,
451    task: Option<&str>,
452    project_root: Option<&str>,
453) -> PostDispatchResult {
454    let prev_count = ledger.entries.len();
455    let prev_pressure = ledger.pressure().recommendation;
456
457    ledger.record_with_task(path, mode, original_tokens, sent_tokens, task);
458
459    let item_id = ContextItemId::from_file(path);
460    let state = overlay.apply_to_state(&item_id, ContextState::Included);
461
462    if state == ContextState::Excluded {
463        return PostDispatchResult {
464            eviction_hint: Some(format!("File '{path}' is excluded by overlay.")),
465            elicitation_hint: None,
466            resource_changed: true,
467            prefetch_hint: None,
468        };
469    }
470
471    let elicitation =
472        super::elicitation::check_elicitation_needed(ledger, Some(path), Some(sent_tokens))
473            .map(|s| s.format_fallback_hint());
474
475    let pressure = ledger.pressure();
476
477    // #6 Global-Workspace ignition: salience outliers are broadcast (pinned) into
478    // the working set BEFORE reinjection, so an ignited item keeps its view while
479    // the rest are downgraded under pressure. Deterministic z-score threshold.
480    let ignited = ledger.ignite_high_salience();
481
482    apply_reinjection_plan(ledger, &pressure.recommendation);
483
484    let new_entry = ledger.entries.len() != prev_count;
485    let pressure_shifted = pressure.recommendation != prev_pressure;
486    let resource_changed = new_entry || pressure_shifted || !ignited.is_empty();
487
488    if pressure.utilization > 0.9 {
489        let candidates = ledger.eviction_candidates_by_phi(3);
490        if !candidates.is_empty() {
491            // #715: emit targets the evict resolver can actually find —
492            // root-relative paths (or the full path), never display-shortened
493            // forms that used to produce "Evicted 0/N".
494            let names: Vec<_> = candidates
495                .iter()
496                .take(3)
497                .map(|p| eviction_target_display(p, project_root))
498                .collect();
499            return PostDispatchResult {
500                eviction_hint: Some(format!(
501                    "Context pressure {:.0}%. Evict: ctx_ledger(action=\"evict\", targets=\"{}\")",
502                    pressure.utilization * 100.0,
503                    names.join(", ")
504                )),
505                elicitation_hint: elicitation,
506                resource_changed,
507                // Under pressure we evict rather than prefetch — no warmup hint.
508                prefetch_hint: None,
509            };
510        }
511    }
512
513    // #9 FEP prefetch: with budget to spare, suggest the files most likely needed
514    // next (co-access graph), so the agent can warm them before the surprise of a
515    // miss. Deterministic; runs in the background post-dispatch, never in output.
516    let prefetch_hint =
517        project_root.and_then(|root| crate::core::fep_prefetch::prefetch_hint(root, path, ledger));
518
519    PostDispatchResult {
520        eviction_hint: None,
521        elicitation_hint: elicitation,
522        resource_changed,
523        prefetch_hint,
524    }
525}
526
527/// #715: a resolvable evict target for hint output — project-root-relative
528/// when the candidate lives under the root, otherwise the full canonical
529/// path. Both forms round-trip through `ContextLedger::resolve_entry`.
530fn eviction_target_display(path: &str, project_root: Option<&str>) -> String {
531    if let Some(root) = project_root.filter(|r| !r.is_empty()) {
532        let root_prefix = format!("{}/", root.trim_end_matches(['/', '\\']).replace('\\', "/"));
533        if let Some(rel) = path.strip_prefix(&root_prefix)
534            && !rel.is_empty()
535        {
536            return rel.to_string();
537        }
538    }
539    path.to_string()
540}
541
542fn apply_reinjection_plan(ledger: &mut ContextLedger, action: &PressureAction) {
543    if *action != PressureAction::ForceCompression && *action != PressureAction::EvictLeastRelevant
544    {
545        return;
546    }
547    for entry in &mut ledger.entries {
548        // #6: ignited / user-pinned items stay broadcast — never downgraded.
549        if entry.state == Some(ContextState::Pinned) {
550            continue;
551        }
552        if entry.mode == "full" {
553            entry.mode = "map".to_string();
554        }
555    }
556}
557
558fn try_load_graph(project_root: &str) -> Option<crate::core::graph_provider::OpenGraphProvider> {
559    crate::core::graph_provider::open_best_effort(project_root)
560}
561
562/// Determines the output-filtering aggressiveness from a task profile.
563///
564/// Fail-safe by construction (community reports on 3.9.19, "triage always
565/// level 2"): the original ladder inverted fail-safety — the empty-query
566/// fallback profile landed on the MOST aggressive level, and per-tool-call
567/// profiles almost always report a low context need (a single tool call
568/// classifies as SingleFile, base 250). A rules-derived profile can now
569/// select at most level 1; uncertainty degrades toward passthrough, never
570/// toward harder filtering.
571pub fn triage_filter_level(profile: &crate::core::triage::profile::TaskProfileLocal) -> u8 {
572    use crate::core::triage::confidence::ACTIONABLE_FLOOR_MILLI;
573    // An unset context need means "unknown", never "needs no context".
574    if profile.confidence_milli < ACTIONABLE_FLOOR_MILLI || profile.context_need_milli == 0 {
575        return 0;
576    }
577    // Level 2 removes declarations and leaves output that parses but no longer
578    // means what it says (#1484). Nothing in a rules-derived profile is precise
579    // enough to justify that: `confidence_milli` measures how sure the intent
580    // classification is, not how much information loss the output tolerates.
581    // The level stays reachable through `apply_triage_filter` for callers that
582    // ask for it — where it is additionally markdown-only, so source code and
583    // logs never lose non-comment lines — and should return here again only
584    // once a model backend can supply that prediction.
585    u8::from(profile.context_need_milli < 600)
586}
587
588/// Filters output according to the task profile and selected triage level.
589pub fn apply_triage_filter(
590    output: &str,
591    profile: &crate::core::triage::profile::TaskProfileLocal,
592    level: u8,
593) -> (String, usize) {
594    if level == 0 || output.chars().count() < 500 {
595        return (output.to_string(), 0);
596    }
597
598    // Never filter structured JSON output — the line-based heuristics destroy
599    // key-value pairs while keeping only braces, producing invalid JSON.
600    let trimmed = output.trim_start();
601    if (trimmed.starts_with('{') || trimmed.starts_with('['))
602        && serde_json::from_str::<serde_json::Value>(trimmed).is_ok()
603    {
604        return (output.to_string(), 0);
605    }
606
607    let lines: Vec<&str> = output.lines().collect();
608
609    // Also bypass when JSON is embedded after a short header (e.g. "ctx_handoff show\n path: …\n{…}")
610    if let Some(json_start) = lines.iter().position(|l| {
611        let t = l.trim_start();
612        t.starts_with('{') || t.starts_with('[')
613    }) {
614        let json_portion = lines[json_start..].join("\n");
615        if serde_json::from_str::<serde_json::Value>(&json_portion).is_ok() {
616            return (output.to_string(), 0);
617        }
618    }
619    // #1570 P4: an explicit <protect> span is a user contract — the whole
620    // output bypasses lossy line filtering (gated on [protection].tags).
621    // Lossless compression (archive digest + ctx_expand) is unaffected:
622    // protection means "never lossy", not "never compressed".
623    if output.contains("<protect>") && crate::core::config::Config::load().protection.tags {
624        return (output.to_string(), 0);
625    }
626    // Build a set of kept lines for O(1) lookup.
627    let keep: std::collections::HashSet<usize> = match level {
628        1 => lines
629            .iter()
630            .enumerate()
631            .filter(|(_, line)| !is_boilerplate_line(line.trim_start()))
632            .map(|(i, _)| i)
633            .collect(),
634        2 => {
635            let keywords = extract_task_keywords(&profile.task_class, &profile.intent);
636            if crate::core::triage::markdown::looks_like_markdown(&lines) {
637                crate::core::triage::markdown::keep_indices(&lines, &keywords)
638            } else {
639                // Community report (3.9.19, "abridged into something that
640                // still looks right"): the structural+keyword keep-set is
641                // provably unsafe for source code — plain `let` bindings
642                // vanished from a Rust fn while the survivors still parsed
643                // (21 of 36 lines dropped, output looked complete, bindings
644                // became undeclared). Line-level lossy triage is therefore
645                // markdown-only; every other content shape gets at most the
646                // level-1 boilerplate strip.
647                lines
648                    .iter()
649                    .enumerate()
650                    .filter(|(_, line)| !is_boilerplate_line(line.trim_start()))
651                    .map(|(i, _)| i)
652                    .collect()
653            }
654        }
655        _ => return (output.to_string(), 0),
656    };
657
658    // #1484: assemble output with inline elision markers so omissions are visible.
659    let removed = lines.len().saturating_sub(keep.len());
660    if removed == 0 {
661        return (output.to_string(), 0);
662    }
663    // #1493: total deletion (100% of lines removed) is never a useful
664    // compression outcome — the marker plus retry costs more than passing
665    // through the original content. Return unfiltered when nothing survives.
666    if keep.is_empty() {
667        return (output.to_string(), 0);
668    }
669    // Heading-only markdown is the same failure mode: ATX titles survive the
670    // markdown keep-set so `keep` is non-empty, but every body paragraph is
671    // gone. Pass through instead of returning a TOC.
672    if crate::core::triage::markdown::is_heading_only_collapse(&lines, &keep) {
673        return (output.to_string(), 0);
674    }
675    let mut result = String::with_capacity(output.len());
676    let mut consecutive_omitted: usize = 0;
677    for (i, line) in lines.iter().enumerate() {
678        if keep.contains(&i) {
679            if consecutive_omitted > 0 {
680                result.push_str(&format!(
681                    "  [...{consecutive_omitted} lines omitted by triage...]\n"
682                ));
683                consecutive_omitted = 0;
684            }
685            result.push_str(line);
686            result.push('\n');
687        } else {
688            consecutive_omitted += 1;
689        }
690    }
691    if consecutive_omitted > 0 {
692        result.push_str(&format!(
693            "  [...{consecutive_omitted} lines omitted by triage...]\n"
694        ));
695    }
696    result.push_str(&format!(
697        "[lean-ctx: {removed} lines filtered by triage (level {level}) — rerun with raw=true for the unfiltered output]"
698    ));
699    (result, removed)
700}
701
702fn extract_task_keywords(task_class: &str, intent: &str) -> Vec<String> {
703    let mut keywords = task_class
704        .split(|character: char| !character.is_alphanumeric())
705        .chain(intent.split(|character: char| !character.is_alphanumeric()))
706        .filter(|keyword| !keyword.is_empty())
707        .map(str::to_lowercase)
708        .collect::<Vec<_>>();
709    keywords.sort_unstable();
710    keywords.dedup();
711    keywords
712}
713
714fn is_boilerplate_line(line: &str) -> bool {
715    line.starts_with("//")
716        && !line.contains("TODO")
717        && !line.contains("FIXME")
718        && !line.contains("SAFETY")
719}
720
721#[cfg(test)]
722mod tests {
723    use super::*;
724    use crate::core::triage::profile::TaskProfileLocal;
725
726    #[test]
727    fn eviction_target_display_emits_resolvable_targets() {
728        // #715: root-relative when under the root, full path otherwise —
729        // never a display-shortened form the resolver cannot find.
730        assert_eq!(
731            eviction_target_display("/w/proj/src/a.rs", Some("/w/proj")),
732            "src/a.rs"
733        );
734        assert_eq!(
735            eviction_target_display("/other/b.rs", Some("/w/proj")),
736            "/other/b.rs"
737        );
738        assert_eq!(eviction_target_display("/x/c.rs", None), "/x/c.rs");
739    }
740
741    #[test]
742    fn pre_dispatch_passthrough_for_full() {
743        let result = pre_dispatch_read("src/main.rs", "full", None, None, None);
744        assert!(result.overridden_mode.is_none());
745    }
746
747    #[test]
748    fn pre_dispatch_passthrough_for_diff() {
749        let result = pre_dispatch_read("src/main.rs", "diff", None, None, None);
750        assert!(result.overridden_mode.is_none());
751    }
752
753    #[test]
754    fn pre_dispatch_passthrough_for_anchored_window() {
755        // #843: a windowed anchored:N-M read must keep its hash anchors —
756        // bounce-prevention, pressure-downgrade, etc. must not clobber it to
757        // "full" and silently drop the window.
758        {
759            let mut bt = crate::core::bounce_tracker::global()
760                .lock()
761                .unwrap_or_else(std::sync::PoisonError::into_inner);
762            bt.set_seq(101);
763            bt.record_read("anchored-bouncy.yml", "map", 30, 400);
764            bt.set_seq(102);
765            bt.record_read("anchored-bouncy.yml", "full", 400, 400);
766            bt.set_seq(103);
767            bt.record_read("a2.yml", "map", 30, 400);
768            bt.set_seq(104);
769            bt.record_read("a2.yml", "full", 400, 400);
770            bt.set_seq(105);
771            bt.record_read("a3.yml", "map", 30, 400);
772            bt.set_seq(106);
773            bt.record_read("a3.yml", "full", 400, 400);
774        }
775        let result = pre_dispatch_read("anchored-new.yml", "anchored:10-40", None, None, None);
776        assert!(
777            result.overridden_mode.is_none(),
778            "anchored:N-M must not be overridden by bounce-prevention"
779        );
780        let bare = pre_dispatch_read("anchored-new.yml", "anchored", None, None, None);
781        assert!(
782            bare.overridden_mode.is_none(),
783            "bare anchored mode must not be overridden by bounce-prevention"
784        );
785    }
786
787    #[test]
788    fn pre_dispatch_passthrough_for_lines_multi_select() {
789        // #971: `lines:A-B,C-D` is a precise pinned window exactly like
790        // `lines:A-B`, but it parsed as Malformed, so `is_precise_pinned_mode`
791        // reported "not pinned" and bounce-prevention rewrote an 8-line request
792        // into a full-file read. Exercises the edit-forced branch, which is what
793        // the field report actually hit (a ctx_patch anchored edit immediately
794        // before the read).
795        {
796            let mut bt = crate::core::bounce_tracker::global()
797                .lock()
798                .unwrap_or_else(std::sync::PoisonError::into_inner);
799            bt.set_seq(201);
800            bt.record_edit("multi-select-971.rs");
801            bt.set_seq(202);
802        }
803
804        // Precondition: the tracker really is armed for this path, so the
805        // assertions below cannot pass vacuously.
806        let forced = pre_dispatch_read("multi-select-971.rs", "map", None, None, None);
807        assert_eq!(
808            forced.overridden_mode.as_deref(),
809            Some("full"),
810            "precondition: a recent edit must force a non-pinned mode to full"
811        );
812
813        let multi = pre_dispatch_read(
814            "multi-select-971.rs",
815            "lines:620-622,1214-1218",
816            None,
817            None,
818            None,
819        );
820        assert!(
821            multi.overridden_mode.is_none(),
822            "lines:A-B,C-D must not be overridden by bounce-prevention (#971)"
823        );
824
825        // Control: the single-range form was already protected.
826        let single = pre_dispatch_read("multi-select-971.rs", "lines:620-622", None, None, None);
827        assert!(
828            single.overridden_mode.is_none(),
829            "lines:A-B must not be overridden by bounce-prevention"
830        );
831    }
832
833    #[test]
834    fn fresh_escapes_bounce_prevention() {
835        // #1588: after an edit the gate pins the file to `full`. Without an
836        // escape hatch, signatures/map/reference stay unreachable for the rest
837        // of the session — `fresh=true` is that hatch.
838        {
839            let mut bt = crate::core::bounce_tracker::global()
840                .lock()
841                .unwrap_or_else(std::sync::PoisonError::into_inner);
842            bt.set_seq(301);
843            bt.record_edit("fresh-escape-1586.rs");
844            bt.set_seq(302);
845        }
846
847        let pinned = pre_dispatch_read("fresh-escape-1586.rs", "signatures", None, None, None);
848        assert_eq!(
849            pinned.overridden_mode.as_deref(),
850            Some("full"),
851            "precondition: the tracker must actually be armed for this path"
852        );
853
854        let escaped = pre_dispatch_read_for_agent(
855            "fresh-escape-1586.rs",
856            "signatures",
857            None,
858            None,
859            None,
860            None,
861            true,
862        );
863        assert!(
864            escaped.overridden_mode.is_none(),
865            "fresh=true must keep the requested mode reachable"
866        );
867    }
868
869    #[test]
870    fn intent_target_matches_whole_components_only() {
871        // #1588: substring matching pinned unrelated files to `full`.
872        assert!(path_matches_target(
873            "/repo/src/server/context_gate.rs",
874            "context_gate"
875        ));
876        assert!(path_matches_target(
877            "/repo/src/server/context_gate.rs",
878            "context_gate.rs"
879        ));
880        assert!(path_matches_target(
881            "/repo/src/server/context_gate.rs",
882            "src/server/context_gate.rs"
883        ));
884
885        assert!(
886            !path_matches_target("/repo/src/printer/link_gate.rs", "print"),
887            "a target must not match the middle of a longer component"
888        );
889        assert!(
890            !path_matches_target("/repo/src/server/context_gate.rs", "src"),
891            "targets below the minimum length are noise, not names"
892        );
893        assert!(!path_matches_target(
894            "/repo/src/server/context_gate.rs",
895            "gate"
896        ));
897    }
898
899    #[test]
900    fn fresh_escapes_intent_target() {
901        let result = pre_dispatch_read_for_agent(
902            "/repo/src/server/context_gate.rs",
903            "reference",
904            Some("fix context_gate overrides"),
905            None,
906            None,
907            None,
908            true,
909        );
910        assert!(
911            result.overridden_mode.is_none(),
912            "fresh=true must also escape the intent-target override"
913        );
914    }
915
916    #[test]
917    fn pre_dispatch_no_override_without_signals() {
918        let result = pre_dispatch_read("src/unknown.rs", "auto", None, None, None);
919        assert!(result.overridden_mode.is_none());
920    }
921
922    #[test]
923    fn pre_dispatch_bounce_prevention_forces_full() {
924        {
925            let mut bt = crate::core::bounce_tracker::global()
926                .lock()
927                .unwrap_or_else(std::sync::PoisonError::into_inner);
928            bt.set_seq(1);
929            bt.record_read("src/bouncy.yml", "map", 30, 400);
930            bt.set_seq(2);
931            bt.record_read("src/bouncy.yml", "full", 400, 400);
932            bt.set_seq(3);
933            bt.record_read("a2.yml", "map", 30, 400);
934            bt.set_seq(4);
935            bt.record_read("a2.yml", "full", 400, 400);
936            bt.set_seq(5);
937            bt.record_read("a3.yml", "map", 30, 400);
938            bt.set_seq(6);
939            bt.record_read("a3.yml", "full", 400, 400);
940        }
941        let result = pre_dispatch_read("new.yml", "auto", None, None, None);
942        assert_eq!(result.overridden_mode, Some("full".to_string()));
943        assert_eq!(result.reason, Some("bounce-prevention"));
944    }
945
946    #[test]
947    fn pressure_does_not_downgrade_explicit_full() {
948        let result = pre_dispatch_read(
949            "c.rs",
950            "full",
951            None,
952            None,
953            Some(&PressureAction::ForceCompression),
954        );
955        assert!(
956            result.overridden_mode.is_none(),
957            "explicit mode=full must never be downgraded by pressure"
958        );
959        assert!(!result.pressure_downgraded);
960    }
961
962    #[test]
963    fn pressure_does_not_downgrade_when_enforce_off() {
964        // Default profile has degradation.enforce = false, so pressure
965        // should NOT downgrade any mode.
966        let result = pre_dispatch_read(
967            "c.rs",
968            "map",
969            None,
970            None,
971            Some(&PressureAction::EvictLeastRelevant),
972        );
973        assert!(
974            result.overridden_mode.is_none(),
975            "pressure must not downgrade when degradation.enforce is off"
976        );
977        assert!(!result.pressure_downgraded);
978    }
979
980    #[test]
981    fn no_pressure_downgrade_when_low() {
982        let result = pre_dispatch_read("c.rs", "full", None, None, Some(&PressureAction::NoAction));
983        assert!(result.overridden_mode.is_none());
984        assert!(!result.pressure_downgraded);
985    }
986
987    #[test]
988    fn suggest_compression_does_not_downgrade_when_enforce_off() {
989        // Default profile has degradation.enforce = false
990        let result = pre_dispatch_read(
991            "c.rs",
992            "auto",
993            None,
994            None,
995            Some(&PressureAction::SuggestCompression),
996        );
997        assert!(
998            result.overridden_mode.is_none(),
999            "suggest_compression must not downgrade when enforce is off"
1000        );
1001        assert!(!result.pressure_downgraded);
1002    }
1003
1004    #[test]
1005    fn suggest_compression_does_not_touch_explicit_full() {
1006        let result = pre_dispatch_read(
1007            "c.rs",
1008            "full",
1009            None,
1010            None,
1011            Some(&PressureAction::SuggestCompression),
1012        );
1013        assert!(result.overridden_mode.is_none());
1014        assert!(!result.pressure_downgraded);
1015    }
1016
1017    #[test]
1018    fn post_dispatch_reinjection_downgrades_entries() {
1019        let mut ledger = ContextLedger::with_window_size(1000);
1020        ledger.record("a.rs", "full", 400, 400);
1021        ledger.record("b.rs", "full", 400, 400);
1022        let overlay = OverlayStore::new();
1023        let result = post_dispatch_record("c.rs", "full", 300, 300, &mut ledger, &overlay);
1024        assert!(result.resource_changed);
1025        let a_entry = ledger.entries.iter().find(|e| e.path == "a.rs").unwrap();
1026        assert_eq!(a_entry.mode, "map");
1027    }
1028
1029    #[test]
1030    fn ignited_item_resists_reinjection_downgrade() {
1031        // #6: a high-salience outlier ignites (pins) and keeps its full view,
1032        // while the rest are downgraded to map by pressure reinjection.
1033        let mut ledger = ContextLedger::with_window_size(1000);
1034        for i in 0..5 {
1035            ledger.record(&format!("bg{i}.rs"), "full", 250, 250);
1036        }
1037        ledger.record("hot.rs", "full", 250, 250);
1038        // Set the salience distribution explicitly (record recomputes Phi, so we
1039        // overwrite afterwards) to make ignition deterministic in the test.
1040        for e in &mut ledger.entries {
1041            e.phi = Some(if e.path == "hot.rs" { 0.97 } else { 0.1 });
1042        }
1043        let ignited = ledger.ignite_high_salience();
1044        assert_eq!(ignited, vec!["hot.rs".to_string()], "outlier should ignite");
1045
1046        apply_reinjection_plan(&mut ledger, &PressureAction::ForceCompression);
1047        let hot = ledger.entries.iter().find(|e| e.path == "hot.rs").unwrap();
1048        assert_eq!(hot.mode, "full", "ignited item keeps its full view");
1049        let bg = ledger.entries.iter().find(|e| e.path == "bg0.rs").unwrap();
1050        assert_eq!(bg.mode, "map", "non-ignited items are downgraded");
1051    }
1052
1053    #[test]
1054    fn overlay_pin_forces_full_mode() {
1055        let dir = tempfile::tempdir().expect("tmp dir");
1056        let root = dir.path();
1057        let mut store = OverlayStore::new();
1058        let target = ContextItemId::from_file("src/important.rs");
1059        store.add(crate::core::context_overlay::ContextOverlay::new(
1060            target,
1061            OverlayOp::Pin { verbatim: false },
1062            crate::core::context_overlay::OverlayScope::Project,
1063            String::new(),
1064            crate::core::context_overlay::OverlayAuthor::User,
1065        ));
1066        store.save_project(root).unwrap();
1067
1068        let result = pre_dispatch_read(
1069            "src/important.rs",
1070            "auto",
1071            None,
1072            Some(root.to_str().unwrap()),
1073            None,
1074        );
1075        assert_eq!(result.overridden_mode, Some("full".to_string()));
1076        assert_eq!(result.reason, Some("pinned"));
1077    }
1078
1079    #[test]
1080    fn overlay_exclude_forces_signatures_mode() {
1081        let dir = tempfile::tempdir().expect("tmp dir");
1082        let root = dir.path();
1083        let mut store = OverlayStore::new();
1084        let target = ContextItemId::from_file("src/noisy.rs");
1085        store.add(crate::core::context_overlay::ContextOverlay::new(
1086            target,
1087            OverlayOp::Exclude {
1088                reason: "noise".to_string(),
1089            },
1090            crate::core::context_overlay::OverlayScope::Project,
1091            String::new(),
1092            crate::core::context_overlay::OverlayAuthor::User,
1093        ));
1094        store.save_project(root).unwrap();
1095
1096        let result = pre_dispatch_read(
1097            "src/noisy.rs",
1098            "auto",
1099            None,
1100            Some(root.to_str().unwrap()),
1101            None,
1102        );
1103        assert_eq!(result.overridden_mode, Some("signatures".to_string()));
1104        assert_eq!(result.reason, Some("excluded"));
1105    }
1106
1107    // --- pressure_downgrade unit tests (pure function) ---
1108
1109    #[test]
1110    fn pressure_downgrade_suggest_auto_to_map() {
1111        let result = pressure_downgrade("auto", &PressureAction::SuggestCompression);
1112        assert_eq!(result, Some("map".to_string()));
1113    }
1114
1115    #[test]
1116    fn pressure_downgrade_suggest_full_to_map() {
1117        let result = pressure_downgrade("full", &PressureAction::SuggestCompression);
1118        assert_eq!(result, Some("map".to_string()));
1119    }
1120
1121    #[test]
1122    fn pressure_downgrade_suggest_does_not_touch_signatures() {
1123        let result = pressure_downgrade("signatures", &PressureAction::SuggestCompression);
1124        assert!(result.is_none());
1125    }
1126
1127    #[test]
1128    fn pressure_downgrade_suggest_does_not_touch_diff() {
1129        let result = pressure_downgrade("diff", &PressureAction::SuggestCompression);
1130        assert!(result.is_none());
1131    }
1132
1133    #[test]
1134    fn pressure_downgrade_force_full_to_map() {
1135        let result = pressure_downgrade("full", &PressureAction::ForceCompression);
1136        assert_eq!(result, Some("map".to_string()));
1137    }
1138
1139    #[test]
1140    fn pressure_downgrade_force_auto_to_signatures() {
1141        let result = pressure_downgrade("auto", &PressureAction::ForceCompression);
1142        assert_eq!(result, Some("signatures".to_string()));
1143    }
1144
1145    #[test]
1146    fn pressure_downgrade_force_map_to_signatures() {
1147        let result = pressure_downgrade("map", &PressureAction::ForceCompression);
1148        assert_eq!(result, Some("signatures".to_string()));
1149    }
1150
1151    #[test]
1152    fn pressure_downgrade_force_does_not_touch_signatures() {
1153        let result = pressure_downgrade("signatures", &PressureAction::ForceCompression);
1154        assert!(result.is_none());
1155    }
1156
1157    #[test]
1158    fn pressure_downgrade_force_does_not_touch_lines() {
1159        let result = pressure_downgrade("lines:1-50", &PressureAction::ForceCompression);
1160        assert!(result.is_none());
1161    }
1162
1163    #[test]
1164    fn pressure_downgrade_evict_full_to_map() {
1165        let result = pressure_downgrade("full", &PressureAction::EvictLeastRelevant);
1166        assert_eq!(result, Some("map".to_string()));
1167    }
1168
1169    #[test]
1170    fn pressure_downgrade_evict_auto_to_signatures() {
1171        let result = pressure_downgrade("auto", &PressureAction::EvictLeastRelevant);
1172        assert_eq!(result, Some("signatures".to_string()));
1173    }
1174
1175    #[test]
1176    fn pressure_downgrade_evict_map_to_signatures() {
1177        let result = pressure_downgrade("map", &PressureAction::EvictLeastRelevant);
1178        assert_eq!(result, Some("signatures".to_string()));
1179    }
1180
1181    #[test]
1182    fn pressure_downgrade_noaction_returns_none() {
1183        let result = pressure_downgrade("full", &PressureAction::NoAction);
1184        assert!(result.is_none());
1185    }
1186
1187    #[test]
1188    fn pressure_downgrade_noaction_auto_returns_none() {
1189        let result = pressure_downgrade("auto", &PressureAction::NoAction);
1190        assert!(result.is_none());
1191    }
1192
1193    // --- pre_dispatch_inner: no_degrade integration ---
1194    // When LCTX_NO_DEGRADE is NOT set (test default), pressure downgrade is active.
1195
1196    #[test]
1197    fn pre_dispatch_does_not_downgrade_full_under_force() {
1198        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1199            return;
1200        }
1201        // Explicit mode=full is protected: pressure cannot downgrade it
1202        let result = pre_dispatch_read(
1203            "nd_test.rs",
1204            "full",
1205            None,
1206            None,
1207            Some(&PressureAction::ForceCompression),
1208        );
1209        assert!(result.overridden_mode.is_none());
1210        assert!(!result.pressure_downgraded);
1211    }
1212
1213    #[test]
1214    fn pre_dispatch_does_not_downgrade_auto_when_enforce_off() {
1215        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1216            return;
1217        }
1218        // Default profile has degradation.enforce = false, so pressure
1219        // should not downgrade even non-full modes
1220        let result = pre_dispatch_read(
1221            "nd_test2.rs",
1222            "auto",
1223            None,
1224            None,
1225            Some(&PressureAction::EvictLeastRelevant),
1226        );
1227        assert!(result.overridden_mode.is_none());
1228        assert!(!result.pressure_downgraded);
1229    }
1230
1231    // --- estimate_read_tokens unit tests ---
1232
1233    #[test]
1234    fn estimate_tokens_diff_mode_is_small() {
1235        let tokens = estimate_read_tokens("nonexistent.rs", "diff");
1236        assert!(tokens < 500, "diff mode should estimate low: got {tokens}");
1237    }
1238
1239    #[test]
1240    fn estimate_tokens_signatures_smaller_than_full() {
1241        let sig = estimate_read_tokens("nonexistent.rs", "signatures");
1242        let full = estimate_read_tokens("nonexistent.rs", "full");
1243        assert!(sig < full, "signatures={sig} should be < full={full}");
1244    }
1245
1246    #[test]
1247    fn estimate_tokens_lines_range() {
1248        let tokens = estimate_read_tokens("nonexistent.rs", "lines:1-10");
1249        assert!(tokens <= 200, "lines:1-10 should be small: got {tokens}");
1250    }
1251
1252    #[test]
1253    fn overlay_set_view_forces_specified_mode() {
1254        let dir = tempfile::tempdir().expect("tmp dir");
1255        let root = dir.path();
1256        let mut store = OverlayStore::new();
1257        let target = ContextItemId::from_file("src/big.rs");
1258        store.add(crate::core::context_overlay::ContextOverlay::new(
1259            target,
1260            OverlayOp::SetView(crate::core::context_field::ViewKind::Map),
1261            crate::core::context_overlay::OverlayScope::Project,
1262            String::new(),
1263            crate::core::context_overlay::OverlayAuthor::User,
1264        ));
1265        store.save_project(root).unwrap();
1266
1267        let result = pre_dispatch_read(
1268            "src/big.rs",
1269            "auto",
1270            None,
1271            Some(root.to_str().unwrap()),
1272            None,
1273        );
1274        assert_eq!(result.overridden_mode, Some("map".to_string()));
1275        assert_eq!(result.reason, Some("overlay-set-view"));
1276    }
1277    use crate::core::triage::profile::TaskScopeLocal;
1278
1279    fn test_profile(confidence: u16, context_need: u16) -> TaskProfileLocal {
1280        TaskProfileLocal {
1281            task_class: "bug_fix".into(),
1282            intent: "fix context gate filtering".into(),
1283            complexity: "low".into(),
1284            scope: TaskScopeLocal::SingleFile,
1285            context_need_milli: context_need,
1286            reasoning_need_milli: 0,
1287            risk_signal_milli: 0,
1288            confidence_milli: confidence,
1289        }
1290    }
1291
1292    #[test]
1293    fn triage_filter_level_selects_expected_level() {
1294        for (confidence, context_need, expected) in [
1295            (200, 200, 0),
1296            // context_need == 0 means "unknown", never "needs no context" —
1297            // the fallback profile must pass through untouched.
1298            (300, 0, 0),
1299            (500, 0, 0),
1300            (500, 200, 1),
1301            (500, 450, 1),
1302            (500, 700, 0),
1303            // A rules-derived profile never selects the lossy level 2, no
1304            // matter how confident the intent classification is.
1305            (700, 200, 1),
1306            (700, 450, 1),
1307            (700, 700, 0),
1308            (1000, 100, 1),
1309        ] {
1310            assert_eq!(
1311                triage_filter_level(&test_profile(confidence, context_need)),
1312                expected,
1313                "confidence={confidence} context_need={context_need}"
1314            );
1315        }
1316    }
1317
1318    #[test]
1319    fn no_model_installed_means_passthrough() {
1320        use crate::core::triage::{TaskAnalysisInput, TaskAnalyzer, rules::RuleTriageBackend};
1321
1322        let profile = RuleTriageBackend
1323            .analyze(&TaskAnalysisInput::default())
1324            .unwrap()
1325            .profile;
1326        assert_eq!(triage_filter_level(&profile), 0);
1327    }
1328
1329    #[test]
1330    fn apply_triage_filter_level_zero_is_passthrough() {
1331        let profile = test_profile(500, 200);
1332        let output = "// boilerplate\n".repeat(40);
1333        assert_eq!(apply_triage_filter(&output, &profile, 0), (output, 0));
1334    }
1335
1336    #[test]
1337    fn apply_triage_filter_short_output_is_passthrough() {
1338        let profile = test_profile(500, 200);
1339        let output = "fn main() {\n    println!(\"hi\");\n}";
1340        assert_eq!(apply_triage_filter(output, &profile, 2), (output.into(), 0));
1341    }
1342
1343    // #1570 P4: a <protect> span is a user contract — the whole output is
1344    // exempt from lossy filtering at every level.
1345    #[test]
1346    fn protect_span_bypasses_lossy_filtering_entirely() {
1347        let profile = test_profile(700, 200);
1348        let output = "// boilerplate noise\n".repeat(30)
1349            + "<protect>operational checklist — must stay verbatim</protect>\n";
1350        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
1351        assert_eq!(removed, 0, "protected output must lose nothing");
1352        assert_eq!(filtered, output);
1353    }
1354
1355    #[test]
1356    fn apply_triage_filter_level_one_preserves_actionable_comments() {
1357        let profile = test_profile(500, 450);
1358        let output = "// boilerplate comment\n".repeat(30)
1359            + "// TODO: keep this\n// FIXME: keep this\n// SAFETY: keep this\nfn keep_me() {}\n";
1360        let (filtered, removed) = apply_triage_filter(&output, &profile, 1);
1361        assert!(!filtered.contains("// boilerplate comment"));
1362        assert!(filtered.contains("// TODO: keep this"));
1363        assert!(filtered.contains("// FIXME: keep this"));
1364        assert!(filtered.contains("// SAFETY: keep this"));
1365        assert!(
1366            filtered
1367                .contains("[lean-ctx: 30 lines filtered by triage (level 1) — rerun with raw=true")
1368        );
1369        assert_eq!(removed, 30);
1370    }
1371
1372    /// Community regression (3.9.19 "abridged into something that still looks
1373    /// right"): level 2 on NON-markdown content must never delete a
1374    /// non-comment line — plain `let` bindings used to vanish from source
1375    /// files while the survivors still parsed.
1376    #[test]
1377    fn apply_triage_filter_level_two_never_drops_code_lines() {
1378        let profile = test_profile(700, 200);
1379        let output = "// boilerplate noise\n".repeat(20)
1380            + "pub fn read_identity() -> Identity {\n"
1381            + "    let serial = read_serial();\n"
1382            + "    let model = read_model();\n"
1383            + "    Identity { serial, model }\n"
1384            + "}\n";
1385        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
1386        // Every code line survives — especially the plain `let` bindings that
1387        // carry neither braces, keywords, nor task keywords.
1388        assert!(filtered.contains("let serial = read_serial();"));
1389        assert!(filtered.contains("let model = read_model();"));
1390        assert!(filtered.contains("Identity { serial, model }"));
1391        // Only the boilerplate comments were stripped, and the footer names
1392        // the escape hatch.
1393        assert_eq!(removed, 20);
1394        assert!(filtered.contains("rerun with raw=true"));
1395    }
1396
1397    #[test]
1398    fn apply_triage_filter_level_two_keeps_keywords_and_structure() {
1399        let profile = test_profile(500, 200);
1400        let output = "// unrelated noise about widgets\n".repeat(20)
1401            + "fix the context gate\n"
1402            + "pub fn unrelated() {}\n"
1403            + "#[derive(Debug)]\n"
1404            + "mod inner {}\n";
1405        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
1406        assert!(filtered.contains("fix the context gate"));
1407        assert!(filtered.contains("pub fn unrelated() {}"));
1408        assert!(filtered.contains("#[derive(Debug)]"));
1409        assert!(filtered.contains("mod inner {}"));
1410        assert!(filtered.contains("[lean-ctx:"));
1411        assert_eq!(removed, 20);
1412    }
1413
1414    #[test]
1415    fn benchmark_apply_triage_filter() {
1416        use std::time::Instant;
1417
1418        let profile = test_profile(500, 200);
1419        // Use a mix of keyword-matching and non-matching lines so triage
1420        // actually filters (100% deletion is now a passthrough per #1493).
1421        let output = "// unrelated noise about widgets\n".repeat(1_999) + "fix the context gate\n";
1422
1423        let started = Instant::now();
1424        for _ in 0..1_000 {
1425            let (_, removed) = apply_triage_filter(&output, &profile, 2);
1426            assert_eq!(removed, 1_999);
1427        }
1428        let average = started.elapsed() / 1_000;
1429        println!("benchmark_apply_triage_filter: {average:?} per call");
1430    }
1431
1432    #[test]
1433    fn gh1493_total_deletion_returns_original_output() {
1434        let profile = test_profile(500, 200);
1435        // 30 lines of plain file names — no keyword match, would be 100% deleted
1436        let output = (1..=30)
1437            .map(|i| format!("plugin/device_{i:03}.go"))
1438            .collect::<Vec<_>>()
1439            .join("\n");
1440        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
1441        assert_eq!(
1442            removed, 0,
1443            "100% deletion must be prevented — output should pass through"
1444        );
1445        assert_eq!(filtered, output);
1446    }
1447
1448    #[test]
1449    fn extract_task_keywords_normalizes_and_deduplicates() {
1450        assert_eq!(
1451            extract_task_keywords("bug_fix", "Fix context-gate"),
1452            ["bug", "context", "fix", "gate"]
1453        );
1454    }
1455
1456    #[test]
1457    fn markdown_level_two_keeps_section_leads_not_just_headings() {
1458        let profile = test_profile(500, 200);
1459        let filler = "Later filler that restates the same loop in racing language. ".repeat(8);
1460        let extra = "Ignore this extra dashboard discussion. ".repeat(8);
1461        let output = [
1462            "# LeanCTX: The Context SDK for AI Agents",
1463            "",
1464            "## The context-performance loop",
1465            "Connect, measure, tune, prove, deploy, repeat.",
1466            "",
1467            filler.as_str(),
1468            "",
1469            "## The Receipt is the trust product",
1470            "A Receipt is evidence, not a decorative log.",
1471            "",
1472            extra.as_str(),
1473            "",
1474            "## Guardrails",
1475            "Local runtime, SDK, CLI, and Receipt stay useful offline.",
1476            "",
1477            extra.as_str(),
1478        ]
1479        .join("\n");
1480        let (filtered, removed) = apply_triage_filter(&output, &profile, 2);
1481        assert!(
1482            filtered.contains("Connect, measure, tune, prove"),
1483            "section lead must survive: {filtered}"
1484        );
1485        assert!(
1486            filtered.contains("A Receipt is evidence"),
1487            "receipt lead must survive: {filtered}"
1488        );
1489        assert!(
1490            !filtered.contains("racing language"),
1491            "later filler should drop: {filtered}"
1492        );
1493        assert!(removed > 0);
1494    }
1495}