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