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/// 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 budget_blocked: bool,
44    pub budget_warning: Option<String>,
45    /// Triage-based output filter aggressiveness: 0=passthrough, 1=moderate, 2=aggressive.
46    pub triage_filter_level: u8,
47}
48
49#[derive(Debug, Clone)]
50pub struct PostDispatchResult {
51    pub eviction_hint: Option<String>,
52    pub elicitation_hint: Option<String>,
53    pub resource_changed: bool,
54}
55
56/// Best-effort KnowledgeRouter advice for the completed Context Gate flow.
57pub fn knowledge_advice(
58    query: &str,
59) -> crate::core::knowledge_router::gate_integration::KnowledgeAdvice {
60    let current = crate::core::context_kernel::ContextState::new(
61        Vec::new(),
62        crate::core::knowledge::KnowledgeQuery::default(),
63    );
64    crate::core::knowledge_router::gate_integration::KnowledgeGateAdvisor::advise(query, &current)
65}
66
67pub fn pre_dispatch_read(
68    path: &str,
69    requested_mode: &str,
70    task: Option<&str>,
71    project_root: Option<&str>,
72) -> PreDispatchResult {
73    pre_dispatch_read_for_agent(path, requested_mode, task, project_root, None, false)
74}
75
76enum AgentBudgetDecision {
77    Allowed,
78    Warning(String),
79    Exceeded(PreDispatchResult),
80}
81
82fn no_change_result() -> PreDispatchResult {
83    PreDispatchResult {
84        overridden_mode: None,
85        reason: None,
86        budget_blocked: false,
87        budget_warning: None,
88        triage_filter_level: 0,
89    }
90}
91
92fn check_agent_budget(
93    path: &str,
94    requested_mode: &str,
95    agent_id: Option<&str>,
96) -> AgentBudgetDecision {
97    let Some(aid) = agent_id else {
98        return AgentBudgetDecision::Allowed;
99    };
100
101    let estimated_tokens = estimate_read_tokens(path, requested_mode);
102    match crate::core::agent_budget::check_budget(aid, estimated_tokens) {
103        crate::core::agent_budget::BudgetCheckResult::Exceeded { limit, consumed } => {
104            let mut result = no_change_result();
105            result.reason = Some("agent-budget-exceeded");
106            result.budget_blocked = true;
107            result.budget_warning = Some(format!(
108                "Agent budget exceeded: {consumed}/{limit} tokens consumed. Reset via ctx_session or set a higher limit."
109            ));
110            AgentBudgetDecision::Exceeded(result)
111        }
112        crate::core::agent_budget::BudgetCheckResult::Warning {
113            remaining,
114            percent_used,
115        } => AgentBudgetDecision::Warning(format!(
116            "[BUDGET WARNING] Agent '{aid}' at {:.0}% budget ({remaining} tokens remaining)",
117            percent_used * 100.0
118        )),
119        crate::core::agent_budget::BudgetCheckResult::Allowed { .. } => {
120            AgentBudgetDecision::Allowed
121        }
122    }
123}
124
125/// Pre-dispatch gate for an explicit caller-pinned mode.
126///
127/// Only the hard per-agent budget gate applies; advisory mode rewriting is
128/// intentionally bypassed so the requested concrete mode remains intact.
129pub fn pre_dispatch_pinned_read_for_agent(
130    path: &str,
131    requested_mode: &str,
132    agent_id: Option<&str>,
133) -> PreDispatchResult {
134    let no_change = no_change_result();
135    match check_agent_budget(path, requested_mode, agent_id) {
136        AgentBudgetDecision::Exceeded(result) => result,
137        AgentBudgetDecision::Warning(warning) => PreDispatchResult {
138            budget_warning: Some(warning),
139            ..no_change
140        },
141        AgentBudgetDecision::Allowed => no_change,
142    }
143}
144
145/// `fresh` is the caller's explicit escape hatch (#1588). Bounce-prevention and
146/// intent-target exist to stop an agent from *drifting* into a compressed view
147/// it will immediately re-read in full; neither should be able to pin a file to
148/// `full` forever. A caller who passes `fresh=true` has said, in the request
149/// itself, that they want this view recomputed — honour it, or those modes are
150/// simply unreachable for the rest of the session.
151pub fn pre_dispatch_read_for_agent(
152    path: &str,
153    requested_mode: &str,
154    task: Option<&str>,
155    project_root: Option<&str>,
156    agent_id: Option<&str>,
157    fresh: bool,
158) -> PreDispatchResult {
159    let no_change = no_change_result();
160
161    match check_agent_budget(path, requested_mode, agent_id) {
162        AgentBudgetDecision::Exceeded(result) => return result,
163        AgentBudgetDecision::Warning(warning) => {
164            let mut result = no_change.clone();
165            result.budget_warning = Some(warning);
166            if is_precise_pinned_mode(requested_mode) {
167                return result;
168            }
169            let rest = pre_dispatch_inner(path, requested_mode, task, project_root, fresh);
170            return PreDispatchResult {
171                budget_warning: result.budget_warning,
172                ..rest
173            };
174        }
175        AgentBudgetDecision::Allowed => {}
176    }
177
178    pre_dispatch_inner(path, requested_mode, task, project_root, fresh)
179}
180
181/// Does `norm` (a normalized path) actually name the intent target `target`?
182///
183/// The old rule was `norm.ends_with(t) || norm.contains(t)`, which matched on
184/// any substring: a task mentioning `src` or `read` pinned every path
185/// containing those letters to `full` (#1588), including matches that land in
186/// the middle of a longer component (`print` inside `printer.rs`). A target now
187/// has to line up with a whole path component or the file stem, and be long
188/// enough to be a name rather than noise.
189fn path_matches_target(norm: &str, target: &str) -> bool {
190    const MIN_TARGET_LEN: usize = 4;
191    let target = target.trim().trim_matches('/');
192    if target.len() < MIN_TARGET_LEN {
193        return false;
194    }
195    // A target that is itself a path suffix (`src/server/context_gate.rs`).
196    if norm == target || norm.ends_with(&format!("/{target}")) {
197        return true;
198    }
199    // Otherwise: a whole path component, with or without its extension.
200    norm.split('/').any(|component| {
201        component == target
202            || component
203                .rsplit_once('.')
204                .is_some_and(|(stem, _)| stem == target)
205    })
206}
207
208/// Explicitly requested views that drop content: the lossy summaries plus
209/// `reference` and `density:`. Lossless, pinned and `auto` requests are not.
210fn is_explicit_compressing_mode(mode: &str) -> bool {
211    use crate::tools::ctx_read::ReadMode;
212    mode.parse::<ReadMode>().is_ok_and(|parsed| {
213        parsed.is_lossy_summary() || matches!(parsed, ReadMode::Reference | ReadMode::Density(_))
214    })
215}
216
217fn pre_dispatch_inner(
218    path: &str,
219    requested_mode: &str,
220    task: Option<&str>,
221    project_root: Option<&str>,
222    fresh: bool,
223) -> PreDispatchResult {
224    let no_change = PreDispatchResult {
225        overridden_mode: None,
226        reason: None,
227        budget_blocked: false,
228        budget_warning: None,
229        triage_filter_level: 0,
230    };
231
232    if is_precise_pinned_mode(requested_mode) {
233        return no_change;
234    }
235
236    if let Some(root) = project_root {
237        let overlay = OverlayStore::load_project(&std::path::PathBuf::from(root));
238        if let Some(result) = check_overlay_mode_override(path, requested_mode, &overlay) {
239            return result;
240        }
241    }
242
243    // Explicit mode=full must not be rewritten by heuristics.
244    // Only overlays (user-explicit) above can override it.
245    if requested_mode == "full" {
246        return no_change;
247    }
248
249    // `fresh` is the documented way out (#1588): the caller re-requested this
250    // view deliberately, so the "you keep bouncing back to full" heuristic has
251    // nothing left to prevent.
252    if !fresh
253        && let Ok(bt) = crate::core::bounce_tracker::global().lock()
254        && bt.should_force_full(path)
255    {
256        return PreDispatchResult {
257            overridden_mode: Some("full".to_string()),
258            reason: Some("bounce-prevention"),
259            budget_blocked: false,
260            budget_warning: None,
261            triage_filter_level: 0,
262        };
263    }
264
265    // #496 learned per-path memory: a file the agent keeps re-reading in full
266    // after compressed views is delivered in full for explicit compressing
267    // modes too (`auto` consults the same memory in its resolver). The caller
268    // sees the stable `[mode overridden: … reason=learned-full …]` notice.
269    if !fresh
270        && is_explicit_compressing_mode(requested_mode)
271        && crate::core::path_mode_memory::should_force_full(path)
272    {
273        return PreDispatchResult {
274            overridden_mode: Some("full".to_string()),
275            reason: Some("learned-full"),
276            budget_blocked: false,
277            budget_warning: None,
278            triage_filter_level: 0,
279        };
280    }
281
282    if let Some(task_str) = task
283        && !fresh
284    {
285        let intent = crate::core::intent_engine::StructuredIntent::from_query(task_str);
286        let norm = crate::core::pathutil::normalize_tool_path(path);
287        let is_target = intent.targets.iter().any(|t| path_matches_target(&norm, t));
288        if is_target {
289            return PreDispatchResult {
290                overridden_mode: Some("full".to_string()),
291                reason: Some("intent-target"),
292                budget_blocked: false,
293                budget_warning: None,
294                triage_filter_level: 0,
295            };
296        }
297    }
298
299    if let Some(root) = project_root
300        && let Some(open) = try_load_graph(root)
301    {
302        let gp = &open.provider;
303        let related = gp.related(path, 1);
304        if let Some(task_str) = task {
305            let intent = crate::core::intent_engine::StructuredIntent::from_query(task_str);
306            for target in &intent.targets {
307                let target_related = gp.related(target, 1);
308                let norm = crate::core::pathutil::normalize_tool_path(path);
309                if target_related
310                    .iter()
311                    .any(|r| r.contains(&norm) || norm.contains(r))
312                {
313                    return PreDispatchResult {
314                        overridden_mode: Some("map".to_string()),
315                        reason: Some("graph-direct-import"),
316                        budget_blocked: false,
317                        budget_warning: None,
318                        triage_filter_level: 0,
319                    };
320                }
321            }
322        }
323        if !related.is_empty() && requested_mode == "auto" {
324            let reverse_deps = gp.dependents(path);
325            if reverse_deps.len() > 3 {
326                return PreDispatchResult {
327                    overridden_mode: Some("map".to_string()),
328                    reason: Some("graph-hub-file"),
329                    budget_blocked: false,
330                    budget_warning: None,
331                    triage_filter_level: 0,
332                };
333            }
334        }
335    }
336
337    if let Some(root) = project_root
338        && let Some(knowledge) = crate::core::knowledge::ProjectKnowledge::load(root)
339    {
340        let norm = crate::core::pathutil::normalize_tool_path(path);
341        let mentions = knowledge
342            .facts
343            .iter()
344            .filter(|f| f.value.contains(&norm) || f.key.contains(&norm))
345            .count();
346        if mentions >= 3 {
347            return PreDispatchResult {
348                overridden_mode: Some("map".to_string()),
349                reason: Some("knowledge-high-relevance"),
350                budget_blocked: false,
351                budget_warning: None,
352                triage_filter_level: 0,
353            };
354        }
355    }
356
357    no_change
358}
359
360fn estimate_read_tokens(path: &str, mode: &str) -> usize {
361    let file_size = std::fs::metadata(path).map_or(4000, |m| m.len() as usize);
362    let char_estimate = file_size;
363    let full_tokens = char_estimate / 4;
364    match mode {
365        "signatures" => full_tokens / 5,
366        "map" => full_tokens / 3,
367        "aggressive" | "entropy" => full_tokens / 4,
368        "diff" => full_tokens / 10,
369        _ if mode.starts_with("lines:") => {
370            if let Some(range) = mode.strip_prefix("lines:") {
371                // #971: comma is multi-select. Splitting the whole payload on
372                // '-' yields 3 parts for `620-622,1214-1218` and fell through to
373                // the whole-file tenth; sum the selected spans instead.
374                let mut selected = 0usize;
375                for part in range.split(',') {
376                    let part = part.trim();
377                    selected += if let Some((s, e)) = part.split_once('-') {
378                        let start = s.trim().parse::<usize>().unwrap_or(1);
379                        let end = e.trim().parse::<usize>().unwrap_or(start + 100);
380                        end.saturating_sub(start) + 1
381                    } else {
382                        1
383                    };
384                }
385                if selected == 0 {
386                    full_tokens / 10
387                } else {
388                    selected * 10
389                }
390            } else {
391                full_tokens / 10
392            }
393        }
394        _ => full_tokens,
395    }
396}
397
398fn check_overlay_mode_override(
399    path: &str,
400    requested_mode: &str,
401    overlay: &OverlayStore,
402) -> Option<PreDispatchResult> {
403    let item_id = ContextItemId::from_file(path);
404    let overlays = overlay.for_item(&item_id);
405
406    for ov in overlays.iter().rev() {
407        match &ov.operation {
408            OverlayOp::SetView(view) => {
409                let mode_str = view.as_str();
410                if mode_str != requested_mode {
411                    return Some(PreDispatchResult {
412                        overridden_mode: Some(mode_str.to_string()),
413                        reason: Some("overlay-set-view"),
414                        budget_blocked: false,
415                        budget_warning: None,
416                        triage_filter_level: 0,
417                    });
418                }
419            }
420            OverlayOp::Pin { .. } if requested_mode != "full" => {
421                return Some(PreDispatchResult {
422                    overridden_mode: Some("full".to_string()),
423                    reason: Some("pinned"),
424                    budget_blocked: false,
425                    budget_warning: None,
426                    triage_filter_level: 0,
427                });
428            }
429            OverlayOp::Exclude { .. } if requested_mode != "signatures" => {
430                return Some(PreDispatchResult {
431                    overridden_mode: Some("signatures".to_string()),
432                    reason: Some("excluded"),
433                    budget_blocked: false,
434                    budget_warning: None,
435                    triage_filter_level: 0,
436                });
437            }
438            _ => {}
439        }
440    }
441    None
442}
443
444pub fn post_dispatch_record(
445    path: &str,
446    mode: &str,
447    original_tokens: usize,
448    sent_tokens: usize,
449    ledger: &mut ContextLedger,
450    overlay: &OverlayStore,
451) -> PostDispatchResult {
452    post_dispatch_record_with_task(
453        path,
454        mode,
455        original_tokens,
456        sent_tokens,
457        ledger,
458        overlay,
459        None,
460        None,
461    )
462}
463
464pub fn post_dispatch_record_with_task(
465    path: &str,
466    mode: &str,
467    original_tokens: usize,
468    sent_tokens: usize,
469    ledger: &mut ContextLedger,
470    overlay: &OverlayStore,
471    task: Option<&str>,
472    project_root: Option<&str>,
473) -> PostDispatchResult {
474    let prev_count = ledger.entries.len();
475    let prev_pressure = ledger.pressure().recommendation;
476
477    ledger.record_with_task(path, mode, original_tokens, sent_tokens, task);
478
479    let item_id = ContextItemId::from_file(path);
480    let state = overlay.apply_to_state(&item_id, ContextState::Included);
481
482    if state == ContextState::Excluded {
483        return PostDispatchResult {
484            eviction_hint: Some(format!("File '{path}' is excluded by overlay.")),
485            elicitation_hint: None,
486            resource_changed: true,
487        };
488    }
489
490    let elicitation =
491        super::elicitation::check_elicitation_needed(ledger, Some(path), Some(sent_tokens))
492            .map(|s| s.format_fallback_hint());
493
494    let pressure = ledger.pressure();
495
496    // #6 Global-Workspace ignition: salience outliers are broadcast (pinned) into
497    // the working set BEFORE reinjection, so an ignited item keeps its view while
498    // the rest are downgraded under pressure. Deterministic z-score threshold.
499    let ignited = ledger.ignite_high_salience();
500
501    apply_reinjection_plan(ledger, &pressure.recommendation);
502
503    let new_entry = ledger.entries.len() != prev_count;
504    let pressure_shifted = pressure.recommendation != prev_pressure;
505    let resource_changed = new_entry || pressure_shifted || !ignited.is_empty();
506
507    if pressure.utilization > 0.9 {
508        let candidates = ledger.eviction_candidates_by_phi(3);
509        if !candidates.is_empty() {
510            // #715: emit targets the evict resolver can actually find —
511            // root-relative paths (or the full path), never display-shortened
512            // forms that used to produce "Evicted 0/N".
513            let names: Vec<_> = candidates
514                .iter()
515                .take(3)
516                .map(|p| eviction_target_display(p, project_root))
517                .collect();
518            return PostDispatchResult {
519                eviction_hint: Some(format!(
520                    "Context pressure {:.0}%. Evict: ctx_control(action=\"evict\", targets=\"{}\")",
521                    pressure.utilization * 100.0,
522                    names.join(", ")
523                )),
524                elicitation_hint: elicitation,
525                resource_changed,
526            };
527        }
528    }
529
530    PostDispatchResult {
531        eviction_hint: None,
532        elicitation_hint: elicitation,
533        resource_changed,
534    }
535}
536
537/// #715: a resolvable evict target for hint output — project-root-relative
538/// when the candidate lives under the root, otherwise the full canonical
539/// path. Both forms round-trip through `ContextLedger::resolve_entry`.
540fn eviction_target_display(path: &str, project_root: Option<&str>) -> String {
541    if let Some(root) = project_root.filter(|r| !r.is_empty()) {
542        let root_prefix = format!("{}/", root.trim_end_matches(['/', '\\']).replace('\\', "/"));
543        if let Some(rel) = path.strip_prefix(&root_prefix)
544            && !rel.is_empty()
545        {
546            return rel.to_string();
547        }
548    }
549    path.to_string()
550}
551
552fn apply_reinjection_plan(ledger: &mut ContextLedger, action: &PressureAction) {
553    if *action != PressureAction::ForceCompression && *action != PressureAction::EvictLeastRelevant
554    {
555        return;
556    }
557    for entry in &mut ledger.entries {
558        // #6: ignited / user-pinned items stay broadcast — never downgraded.
559        if entry.state == Some(ContextState::Pinned) {
560            continue;
561        }
562        if entry.mode == "full" {
563            entry.mode = "map".to_string();
564        }
565    }
566}
567
568/// Graph for the per-read mode decision. Only an already populated property
569/// graph: this runs before every `ctx_read`, and the JSON-index fallback of
570/// `open_best_effort` re-parsed the whole index on each read of a cold
571/// session (focus analysis 2026-10-15).
572fn try_load_graph(project_root: &str) -> Option<crate::core::graph_provider::OpenGraphProvider> {
573    crate::core::graph_provider::open_ready(project_root)
574}
575
576/// Determines the output-filtering aggressiveness from a task profile.
577///
578/// Fail-safe by construction (community reports on 3.9.19, "triage always
579/// level 2"): the original ladder inverted fail-safety — the empty-query
580/// fallback profile landed on the MOST aggressive level, and per-tool-call
581/// profiles almost always report a low context need (a single tool call
582/// classifies as SingleFile, base 250). A rules-derived profile can now
583/// select at most level 1; uncertainty degrades toward passthrough, never
584/// toward harder filtering.
585pub fn triage_filter_level(profile: &crate::core::triage::profile::TaskProfileLocal) -> u8 {
586    use crate::core::triage::confidence::ACTIONABLE_FLOOR_MILLI;
587    // An unset context need means "unknown", never "needs no context".
588    if profile.confidence_milli < ACTIONABLE_FLOOR_MILLI || profile.context_need_milli == 0 {
589        return 0;
590    }
591    // Level 2 removes declarations and leaves output that parses but no longer
592    // means what it says (#1484). Nothing in a rules-derived profile is precise
593    // enough to justify that: `confidence_milli` measures how sure the intent
594    // classification is, not how much information loss the output tolerates.
595    // The level stays reachable through `apply_triage_filter` for callers that
596    // ask for it — where it is additionally markdown-only, so source code and
597    // logs never lose non-comment lines — and should return here again only
598    // once a model backend can supply that prediction.
599    u8::from(profile.context_need_milli < 600)
600}
601
602/// Filters output according to the task profile and selected triage level.
603pub fn apply_triage_filter(
604    output: &str,
605    profile: &crate::core::triage::profile::TaskProfileLocal,
606    level: u8,
607) -> (String, usize) {
608    if level == 0 || output.chars().count() < 500 {
609        return (output.to_string(), 0);
610    }
611
612    // Never filter structured JSON output — the line-based heuristics destroy
613    // key-value pairs while keeping only braces, producing invalid JSON.
614    let trimmed = output.trim_start();
615    if (trimmed.starts_with('{') || trimmed.starts_with('['))
616        && serde_json::from_str::<serde_json::Value>(trimmed).is_ok()
617    {
618        return (output.to_string(), 0);
619    }
620
621    let lines: Vec<&str> = output.lines().collect();
622
623    // Also bypass when JSON is embedded after a short header (e.g. "ctx_handoff show\n path: …\n{…}")
624    if let Some(json_start) = lines.iter().position(|l| {
625        let t = l.trim_start();
626        t.starts_with('{') || t.starts_with('[')
627    }) {
628        let json_portion = lines[json_start..].join("\n");
629        if serde_json::from_str::<serde_json::Value>(&json_portion).is_ok() {
630            return (output.to_string(), 0);
631        }
632    }
633    // #1570 P4: an explicit <protect> span is a user contract — the whole
634    // output bypasses lossy line filtering (gated on [protection].tags).
635    // Lossless compression (archive digest + ctx_expand) is unaffected:
636    // protection means "never lossy", not "never compressed".
637    if output.contains("<protect>") && crate::core::config::Config::load().protection.tags {
638        return (output.to_string(), 0);
639    }
640    // Build a set of kept lines for O(1) lookup.
641    let keep: std::collections::HashSet<usize> = match level {
642        1 => lines
643            .iter()
644            .enumerate()
645            .filter(|(_, line)| !is_boilerplate_line(line.trim_start()))
646            .map(|(i, _)| i)
647            .collect(),
648        2 => {
649            let keywords = extract_task_keywords(&profile.task_class, &profile.intent);
650            if crate::core::triage::markdown::looks_like_markdown(&lines) {
651                crate::core::triage::markdown::keep_indices(&lines, &keywords)
652            } else {
653                // Community report (3.9.19, "abridged into something that
654                // still looks right"): the structural+keyword keep-set is
655                // provably unsafe for source code — plain `let` bindings
656                // vanished from a Rust fn while the survivors still parsed
657                // (21 of 36 lines dropped, output looked complete, bindings
658                // became undeclared). Line-level lossy triage is therefore
659                // markdown-only; every other content shape gets at most the
660                // level-1 boilerplate strip.
661                lines
662                    .iter()
663                    .enumerate()
664                    .filter(|(_, line)| !is_boilerplate_line(line.trim_start()))
665                    .map(|(i, _)| i)
666                    .collect()
667            }
668        }
669        _ => return (output.to_string(), 0),
670    };
671
672    // #1484: assemble output with inline elision markers so omissions are visible.
673    let removed = lines.len().saturating_sub(keep.len());
674    if removed == 0 {
675        return (output.to_string(), 0);
676    }
677    // #1493: total deletion (100% of lines removed) is never a useful
678    // compression outcome — the marker plus retry costs more than passing
679    // through the original content. Return unfiltered when nothing survives.
680    if keep.is_empty() {
681        return (output.to_string(), 0);
682    }
683    // Heading-only markdown is the same failure mode: ATX titles survive the
684    // markdown keep-set so `keep` is non-empty, but every body paragraph is
685    // gone. Pass through instead of returning a TOC.
686    if crate::core::triage::markdown::is_heading_only_collapse(&lines, &keep) {
687        return (output.to_string(), 0);
688    }
689    let mut result = String::with_capacity(output.len());
690    let mut consecutive_omitted: usize = 0;
691    for (i, line) in lines.iter().enumerate() {
692        if keep.contains(&i) {
693            if consecutive_omitted > 0 {
694                result.push_str(&format!(
695                    "  [...{consecutive_omitted} lines omitted by triage...]\n"
696                ));
697                consecutive_omitted = 0;
698            }
699            result.push_str(line);
700            result.push('\n');
701        } else {
702            consecutive_omitted += 1;
703        }
704    }
705    if consecutive_omitted > 0 {
706        result.push_str(&format!(
707            "  [...{consecutive_omitted} lines omitted by triage...]\n"
708        ));
709    }
710    result.push_str(&format!(
711        "[lean-ctx: {removed} lines filtered by triage (level {level}) — rerun with raw=true for the unfiltered output]"
712    ));
713    (result, removed)
714}
715
716fn extract_task_keywords(task_class: &str, intent: &str) -> Vec<String> {
717    let mut keywords = task_class
718        .split(|character: char| !character.is_alphanumeric())
719        .chain(intent.split(|character: char| !character.is_alphanumeric()))
720        .filter(|keyword| !keyword.is_empty())
721        .map(str::to_lowercase)
722        .collect::<Vec<_>>();
723    keywords.sort_unstable();
724    keywords.dedup();
725    keywords
726}
727
728fn is_boilerplate_line(line: &str) -> bool {
729    line.starts_with("//")
730        && !line.contains("TODO")
731        && !line.contains("FIXME")
732        && !line.contains("SAFETY")
733}
734
735#[cfg(test)]
736#[path = "context_gate_tests.rs"]
737mod tests;