1use crate::core::context_field::{ContextItemId, ContextState};
2use crate::core::context_ledger::{ContextLedger, PressureAction};
3use crate::core::context_overlay::{OverlayOp, OverlayStore};
4
5pub(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
23fn is_precise_pinned_mode(requested_mode: &str) -> bool {
34 requested_mode
35 .parse::<crate::tools::ctx_read::ReadMode>()
36 .is_ok_and(|m| m.is_precise_pinned_read())
37}
38
39#[derive(Debug, Clone)]
40pub struct PreDispatchResult {
41 pub overridden_mode: Option<String>,
42 pub reason: Option<&'static str>,
43 pub pressure_downgraded: bool,
44 pub budget_blocked: bool,
45 pub budget_warning: Option<String>,
46 pub triage_filter_level: u8,
48}
49
50#[derive(Debug, Clone)]
51pub struct PostDispatchResult {
52 pub eviction_hint: Option<String>,
53 pub elicitation_hint: Option<String>,
54 pub resource_changed: bool,
55 pub prefetch_hint: Option<String>,
58}
59
60pub fn knowledge_advice(
62 query: &str,
63) -> crate::core::knowledge_router::gate_integration::KnowledgeAdvice {
64 let current = crate::core::context_kernel::ContextState::new(
65 Vec::new(),
66 crate::core::knowledge::KnowledgeQuery::default(),
67 );
68 crate::core::knowledge_router::gate_integration::KnowledgeGateAdvisor::advise(query, ¤t)
69}
70
71pub fn pre_dispatch_read(
72 path: &str,
73 requested_mode: &str,
74 task: Option<&str>,
75 project_root: Option<&str>,
76 pressure: Option<&PressureAction>,
77) -> PreDispatchResult {
78 pre_dispatch_read_for_agent(
79 path,
80 requested_mode,
81 task,
82 project_root,
83 pressure,
84 None,
85 false,
86 )
87}
88
89enum AgentBudgetDecision {
90 Allowed,
91 Warning(String),
92 Exceeded(PreDispatchResult),
93}
94
95fn no_change_result() -> PreDispatchResult {
96 PreDispatchResult {
97 overridden_mode: None,
98 reason: None,
99 pressure_downgraded: false,
100 budget_blocked: false,
101 budget_warning: None,
102 triage_filter_level: 0,
103 }
104}
105
106fn check_agent_budget(
107 path: &str,
108 requested_mode: &str,
109 agent_id: Option<&str>,
110) -> AgentBudgetDecision {
111 let Some(aid) = agent_id else {
112 return AgentBudgetDecision::Allowed;
113 };
114
115 let estimated_tokens = estimate_read_tokens(path, requested_mode);
116 match crate::core::agent_budget::check_budget(aid, estimated_tokens) {
117 crate::core::agent_budget::BudgetCheckResult::Exceeded { limit, consumed } => {
118 let mut result = no_change_result();
119 result.reason = Some("agent-budget-exceeded");
120 result.budget_blocked = true;
121 result.budget_warning = Some(format!(
122 "Agent budget exceeded: {consumed}/{limit} tokens consumed. Reset via ctx_session or set a higher limit."
123 ));
124 AgentBudgetDecision::Exceeded(result)
125 }
126 crate::core::agent_budget::BudgetCheckResult::Warning {
127 remaining,
128 percent_used,
129 } => AgentBudgetDecision::Warning(format!(
130 "[BUDGET WARNING] Agent '{aid}' at {:.0}% budget ({remaining} tokens remaining)",
131 percent_used * 100.0
132 )),
133 crate::core::agent_budget::BudgetCheckResult::Allowed { .. } => {
134 AgentBudgetDecision::Allowed
135 }
136 }
137}
138
139pub fn pre_dispatch_pinned_read_for_agent(
144 path: &str,
145 requested_mode: &str,
146 agent_id: Option<&str>,
147) -> PreDispatchResult {
148 let no_change = no_change_result();
149 match check_agent_budget(path, requested_mode, agent_id) {
150 AgentBudgetDecision::Exceeded(result) => result,
151 AgentBudgetDecision::Warning(warning) => PreDispatchResult {
152 budget_warning: Some(warning),
153 ..no_change
154 },
155 AgentBudgetDecision::Allowed => no_change,
156 }
157}
158
159pub fn pre_dispatch_read_for_agent(
166 path: &str,
167 requested_mode: &str,
168 task: Option<&str>,
169 project_root: Option<&str>,
170 pressure: Option<&PressureAction>,
171 agent_id: Option<&str>,
172 fresh: bool,
173) -> PreDispatchResult {
174 let no_change = no_change_result();
175
176 match check_agent_budget(path, requested_mode, agent_id) {
177 AgentBudgetDecision::Exceeded(result) => return result,
178 AgentBudgetDecision::Warning(warning) => {
179 let mut result = no_change.clone();
180 result.budget_warning = Some(warning);
181 if is_precise_pinned_mode(requested_mode) {
182 return result;
183 }
184 let rest =
185 pre_dispatch_inner(path, requested_mode, task, project_root, pressure, fresh);
186 return PreDispatchResult {
187 budget_warning: result.budget_warning,
188 ..rest
189 };
190 }
191 AgentBudgetDecision::Allowed => {}
192 }
193
194 pre_dispatch_inner(path, requested_mode, task, project_root, pressure, fresh)
195}
196
197fn path_matches_target(norm: &str, target: &str) -> bool {
206 const MIN_TARGET_LEN: usize = 4;
207 let target = target.trim().trim_matches('/');
208 if target.len() < MIN_TARGET_LEN {
209 return false;
210 }
211 if norm == target || norm.ends_with(&format!("/{target}")) {
213 return true;
214 }
215 norm.split('/').any(|component| {
217 component == target
218 || component
219 .rsplit_once('.')
220 .is_some_and(|(stem, _)| stem == target)
221 })
222}
223
224fn pre_dispatch_inner(
225 path: &str,
226 requested_mode: &str,
227 task: Option<&str>,
228 project_root: Option<&str>,
229 pressure: Option<&PressureAction>,
230 fresh: bool,
231) -> PreDispatchResult {
232 let no_change = PreDispatchResult {
233 overridden_mode: None,
234 reason: None,
235 pressure_downgraded: false,
236 budget_blocked: false,
237 budget_warning: None,
238 triage_filter_level: 0,
239 };
240
241 if is_precise_pinned_mode(requested_mode) {
242 return no_change;
243 }
244
245 if let Some(root) = project_root {
246 let overlay = OverlayStore::load_project(&std::path::PathBuf::from(root));
247 if let Some(result) = check_overlay_mode_override(path, requested_mode, &overlay) {
248 return result;
249 }
250 }
251
252 if requested_mode == "full" {
255 return no_change;
256 }
257
258 if let Some(action) = pressure {
259 let no_degrade = crate::core::config::Config::load().no_degrade_effective();
260 let profile = crate::core::profiles::active_profile();
261 if !no_degrade
262 && profile.degradation.enforce_effective()
263 && let Some(downgraded) = pressure_downgrade(requested_mode, action)
264 {
265 return PreDispatchResult {
266 overridden_mode: Some(downgraded),
267 reason: Some("pressure-auto-downgrade"),
268 pressure_downgraded: true,
269 budget_blocked: false,
270 budget_warning: None,
271 triage_filter_level: 0,
272 };
273 }
274 }
275
276 if !fresh
280 && let Ok(bt) = crate::core::bounce_tracker::global().lock()
281 && bt.should_force_full(path)
282 {
283 return PreDispatchResult {
284 overridden_mode: Some("full".to_string()),
285 reason: Some("bounce-prevention"),
286 pressure_downgraded: false,
287 budget_blocked: false,
288 budget_warning: None,
289 triage_filter_level: 0,
290 };
291 }
292
293 if let Some(task_str) = task
294 && !fresh
295 {
296 let intent = crate::core::intent_engine::StructuredIntent::from_query(task_str);
297 let norm = crate::core::pathutil::normalize_tool_path(path);
298 let is_target = intent.targets.iter().any(|t| path_matches_target(&norm, t));
299 if is_target {
300 return PreDispatchResult {
301 overridden_mode: Some("full".to_string()),
302 reason: Some("intent-target"),
303 pressure_downgraded: false,
304 budget_blocked: false,
305 budget_warning: None,
306 triage_filter_level: 0,
307 };
308 }
309 }
310
311 if let Some(root) = project_root
312 && let Some(open) = try_load_graph(root)
313 {
314 let gp = &open.provider;
315 let related = gp.related(path, 1);
316 if let Some(task_str) = task {
317 let intent = crate::core::intent_engine::StructuredIntent::from_query(task_str);
318 for target in &intent.targets {
319 let target_related = gp.related(target, 1);
320 let norm = crate::core::pathutil::normalize_tool_path(path);
321 if target_related
322 .iter()
323 .any(|r| r.contains(&norm) || norm.contains(r))
324 {
325 return PreDispatchResult {
326 overridden_mode: Some("map".to_string()),
327 reason: Some("graph-direct-import"),
328 pressure_downgraded: false,
329 budget_blocked: false,
330 budget_warning: None,
331 triage_filter_level: 0,
332 };
333 }
334 }
335 }
336 if !related.is_empty() && requested_mode == "auto" {
337 let reverse_deps = gp.dependents(path);
338 if reverse_deps.len() > 3 {
339 return PreDispatchResult {
340 overridden_mode: Some("map".to_string()),
341 reason: Some("graph-hub-file"),
342 pressure_downgraded: false,
343 budget_blocked: false,
344 budget_warning: None,
345 triage_filter_level: 0,
346 };
347 }
348 }
349 }
350
351 if let Some(root) = project_root
352 && let Some(knowledge) = crate::core::knowledge::ProjectKnowledge::load(root)
353 {
354 let norm = crate::core::pathutil::normalize_tool_path(path);
355 let mentions = knowledge
356 .facts
357 .iter()
358 .filter(|f| f.value.contains(&norm) || f.key.contains(&norm))
359 .count();
360 if mentions >= 3 {
361 return PreDispatchResult {
362 overridden_mode: Some("map".to_string()),
363 reason: Some("knowledge-high-relevance"),
364 pressure_downgraded: false,
365 budget_blocked: false,
366 budget_warning: None,
367 triage_filter_level: 0,
368 };
369 }
370 }
371
372 no_change
373}
374
375fn estimate_read_tokens(path: &str, mode: &str) -> usize {
376 let file_size = std::fs::metadata(path).map_or(4000, |m| m.len() as usize);
377 let char_estimate = file_size;
378 let full_tokens = char_estimate / 4;
379 match mode {
380 "signatures" => full_tokens / 5,
381 "map" => full_tokens / 3,
382 "aggressive" | "entropy" => full_tokens / 4,
383 "diff" => full_tokens / 10,
384 _ if mode.starts_with("lines:") => {
385 if let Some(range) = mode.strip_prefix("lines:") {
386 let mut selected = 0usize;
390 for part in range.split(',') {
391 let part = part.trim();
392 selected += if let Some((s, e)) = part.split_once('-') {
393 let start = s.trim().parse::<usize>().unwrap_or(1);
394 let end = e.trim().parse::<usize>().unwrap_or(start + 100);
395 end.saturating_sub(start) + 1
396 } else {
397 1
398 };
399 }
400 if selected == 0 {
401 full_tokens / 10
402 } else {
403 selected * 10
404 }
405 } else {
406 full_tokens / 10
407 }
408 }
409 _ => full_tokens,
410 }
411}
412
413fn pressure_downgrade(requested_mode: &str, action: &PressureAction) -> Option<String> {
414 crate::core::auto_mode_resolver::pressure_downgrade(requested_mode, action)
415}
416
417fn check_overlay_mode_override(
418 path: &str,
419 requested_mode: &str,
420 overlay: &OverlayStore,
421) -> Option<PreDispatchResult> {
422 let item_id = ContextItemId::from_file(path);
423 let overlays = overlay.for_item(&item_id);
424
425 for ov in overlays.iter().rev() {
426 match &ov.operation {
427 OverlayOp::SetView(view) => {
428 let mode_str = view.as_str();
429 if mode_str != requested_mode {
430 return Some(PreDispatchResult {
431 overridden_mode: Some(mode_str.to_string()),
432 reason: Some("overlay-set-view"),
433 pressure_downgraded: false,
434 budget_blocked: false,
435 budget_warning: None,
436 triage_filter_level: 0,
437 });
438 }
439 }
440 OverlayOp::Pin { .. } if requested_mode != "full" => {
441 return Some(PreDispatchResult {
442 overridden_mode: Some("full".to_string()),
443 reason: Some("pinned"),
444 pressure_downgraded: false,
445 budget_blocked: false,
446 budget_warning: None,
447 triage_filter_level: 0,
448 });
449 }
450 OverlayOp::Exclude { .. } if requested_mode != "signatures" => {
451 return Some(PreDispatchResult {
452 overridden_mode: Some("signatures".to_string()),
453 reason: Some("excluded"),
454 pressure_downgraded: false,
455 budget_blocked: false,
456 budget_warning: None,
457 triage_filter_level: 0,
458 });
459 }
460 _ => {}
461 }
462 }
463 None
464}
465
466pub fn post_dispatch_record(
467 path: &str,
468 mode: &str,
469 original_tokens: usize,
470 sent_tokens: usize,
471 ledger: &mut ContextLedger,
472 overlay: &OverlayStore,
473) -> PostDispatchResult {
474 post_dispatch_record_with_task(
475 path,
476 mode,
477 original_tokens,
478 sent_tokens,
479 ledger,
480 overlay,
481 None,
482 None,
483 )
484}
485
486pub fn post_dispatch_record_with_task(
487 path: &str,
488 mode: &str,
489 original_tokens: usize,
490 sent_tokens: usize,
491 ledger: &mut ContextLedger,
492 overlay: &OverlayStore,
493 task: Option<&str>,
494 project_root: Option<&str>,
495) -> PostDispatchResult {
496 let prev_count = ledger.entries.len();
497 let prev_pressure = ledger.pressure().recommendation;
498
499 ledger.record_with_task(path, mode, original_tokens, sent_tokens, task);
500
501 let item_id = ContextItemId::from_file(path);
502 let state = overlay.apply_to_state(&item_id, ContextState::Included);
503
504 if state == ContextState::Excluded {
505 return PostDispatchResult {
506 eviction_hint: Some(format!("File '{path}' is excluded by overlay.")),
507 elicitation_hint: None,
508 resource_changed: true,
509 prefetch_hint: None,
510 };
511 }
512
513 let elicitation =
514 super::elicitation::check_elicitation_needed(ledger, Some(path), Some(sent_tokens))
515 .map(|s| s.format_fallback_hint());
516
517 let pressure = ledger.pressure();
518
519 let ignited = ledger.ignite_high_salience();
523
524 apply_reinjection_plan(ledger, &pressure.recommendation);
525
526 let new_entry = ledger.entries.len() != prev_count;
527 let pressure_shifted = pressure.recommendation != prev_pressure;
528 let resource_changed = new_entry || pressure_shifted || !ignited.is_empty();
529
530 if pressure.utilization > 0.9 {
531 let candidates = ledger.eviction_candidates_by_phi(3);
532 if !candidates.is_empty() {
533 let names: Vec<_> = candidates
537 .iter()
538 .take(3)
539 .map(|p| eviction_target_display(p, project_root))
540 .collect();
541 return PostDispatchResult {
542 eviction_hint: Some(format!(
543 "Context pressure {:.0}%. Evict: ctx_ledger(action=\"evict\", targets=\"{}\")",
544 pressure.utilization * 100.0,
545 names.join(", ")
546 )),
547 elicitation_hint: elicitation,
548 resource_changed,
549 prefetch_hint: None,
551 };
552 }
553 }
554
555 let prefetch_hint =
559 project_root.and_then(|root| crate::core::fep_prefetch::prefetch_hint(root, path, ledger));
560
561 PostDispatchResult {
562 eviction_hint: None,
563 elicitation_hint: elicitation,
564 resource_changed,
565 prefetch_hint,
566 }
567}
568
569fn eviction_target_display(path: &str, project_root: Option<&str>) -> String {
573 if let Some(root) = project_root.filter(|r| !r.is_empty()) {
574 let root_prefix = format!("{}/", root.trim_end_matches(['/', '\\']).replace('\\', "/"));
575 if let Some(rel) = path.strip_prefix(&root_prefix)
576 && !rel.is_empty()
577 {
578 return rel.to_string();
579 }
580 }
581 path.to_string()
582}
583
584fn apply_reinjection_plan(ledger: &mut ContextLedger, action: &PressureAction) {
585 if *action != PressureAction::ForceCompression && *action != PressureAction::EvictLeastRelevant
586 {
587 return;
588 }
589 for entry in &mut ledger.entries {
590 if entry.state == Some(ContextState::Pinned) {
592 continue;
593 }
594 if entry.mode == "full" {
595 entry.mode = "map".to_string();
596 }
597 }
598}
599
600fn try_load_graph(project_root: &str) -> Option<crate::core::graph_provider::OpenGraphProvider> {
601 crate::core::graph_provider::open_best_effort(project_root)
602}
603
604pub fn triage_filter_level(profile: &crate::core::triage::profile::TaskProfileLocal) -> u8 {
614 use crate::core::triage::confidence::ACTIONABLE_FLOOR_MILLI;
615 if profile.confidence_milli < ACTIONABLE_FLOOR_MILLI || profile.context_need_milli == 0 {
617 return 0;
618 }
619 u8::from(profile.context_need_milli < 600)
628}
629
630pub fn apply_triage_filter(
632 output: &str,
633 profile: &crate::core::triage::profile::TaskProfileLocal,
634 level: u8,
635) -> (String, usize) {
636 if level == 0 || output.chars().count() < 500 {
637 return (output.to_string(), 0);
638 }
639
640 let trimmed = output.trim_start();
643 if (trimmed.starts_with('{') || trimmed.starts_with('['))
644 && serde_json::from_str::<serde_json::Value>(trimmed).is_ok()
645 {
646 return (output.to_string(), 0);
647 }
648
649 let lines: Vec<&str> = output.lines().collect();
650
651 if let Some(json_start) = lines.iter().position(|l| {
653 let t = l.trim_start();
654 t.starts_with('{') || t.starts_with('[')
655 }) {
656 let json_portion = lines[json_start..].join("\n");
657 if serde_json::from_str::<serde_json::Value>(&json_portion).is_ok() {
658 return (output.to_string(), 0);
659 }
660 }
661 if output.contains("<protect>") && crate::core::config::Config::load().protection.tags {
666 return (output.to_string(), 0);
667 }
668 let keep: std::collections::HashSet<usize> = match level {
670 1 => lines
671 .iter()
672 .enumerate()
673 .filter(|(_, line)| !is_boilerplate_line(line.trim_start()))
674 .map(|(i, _)| i)
675 .collect(),
676 2 => {
677 let keywords = extract_task_keywords(&profile.task_class, &profile.intent);
678 if crate::core::triage::markdown::looks_like_markdown(&lines) {
679 crate::core::triage::markdown::keep_indices(&lines, &keywords)
680 } else {
681 lines
690 .iter()
691 .enumerate()
692 .filter(|(_, line)| !is_boilerplate_line(line.trim_start()))
693 .map(|(i, _)| i)
694 .collect()
695 }
696 }
697 _ => return (output.to_string(), 0),
698 };
699
700 let removed = lines.len().saturating_sub(keep.len());
702 if removed == 0 {
703 return (output.to_string(), 0);
704 }
705 if keep.is_empty() {
709 return (output.to_string(), 0);
710 }
711 if crate::core::triage::markdown::is_heading_only_collapse(&lines, &keep) {
715 return (output.to_string(), 0);
716 }
717 let mut result = String::with_capacity(output.len());
718 let mut consecutive_omitted: usize = 0;
719 for (i, line) in lines.iter().enumerate() {
720 if keep.contains(&i) {
721 if consecutive_omitted > 0 {
722 result.push_str(&format!(
723 " [...{consecutive_omitted} lines omitted by triage...]\n"
724 ));
725 consecutive_omitted = 0;
726 }
727 result.push_str(line);
728 result.push('\n');
729 } else {
730 consecutive_omitted += 1;
731 }
732 }
733 if consecutive_omitted > 0 {
734 result.push_str(&format!(
735 " [...{consecutive_omitted} lines omitted by triage...]\n"
736 ));
737 }
738 result.push_str(&format!(
739 "[lean-ctx: {removed} lines filtered by triage (level {level}) — rerun with raw=true for the unfiltered output]"
740 ));
741 (result, removed)
742}
743
744fn extract_task_keywords(task_class: &str, intent: &str) -> Vec<String> {
745 let mut keywords = task_class
746 .split(|character: char| !character.is_alphanumeric())
747 .chain(intent.split(|character: char| !character.is_alphanumeric()))
748 .filter(|keyword| !keyword.is_empty())
749 .map(str::to_lowercase)
750 .collect::<Vec<_>>();
751 keywords.sort_unstable();
752 keywords.dedup();
753 keywords
754}
755
756fn is_boilerplate_line(line: &str) -> bool {
757 line.starts_with("//")
758 && !line.contains("TODO")
759 && !line.contains("FIXME")
760 && !line.contains("SAFETY")
761}
762
763#[cfg(test)]
764#[path = "context_gate_tests.rs"]
765mod tests;