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