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 budget_blocked: bool,
44 pub budget_warning: Option<String>,
45 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
56pub 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, ¤t)
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
125pub 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
145pub 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
181fn 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 if norm == target || norm.ends_with(&format!("/{target}")) {
197 return true;
198 }
199 norm.split('/').any(|component| {
201 component == target
202 || component
203 .rsplit_once('.')
204 .is_some_and(|(stem, _)| stem == target)
205 })
206}
207
208fn 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 if requested_mode == "full" {
246 return no_change;
247 }
248
249 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 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 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 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 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
537fn 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 if entry.state == Some(ContextState::Pinned) {
560 continue;
561 }
562 if entry.mode == "full" {
563 entry.mode = "map".to_string();
564 }
565 }
566}
567
568fn try_load_graph(project_root: &str) -> Option<crate::core::graph_provider::OpenGraphProvider> {
573 crate::core::graph_provider::open_ready(project_root)
574}
575
576pub fn triage_filter_level(profile: &crate::core::triage::profile::TaskProfileLocal) -> u8 {
586 use crate::core::triage::confidence::ACTIONABLE_FLOOR_MILLI;
587 if profile.confidence_milli < ACTIONABLE_FLOOR_MILLI || profile.context_need_milli == 0 {
589 return 0;
590 }
591 u8::from(profile.context_need_milli < 600)
600}
601
602pub 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 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 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 if output.contains("<protect>") && crate::core::config::Config::load().protection.tags {
638 return (output.to_string(), 0);
639 }
640 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 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 let removed = lines.len().saturating_sub(keep.len());
674 if removed == 0 {
675 return (output.to_string(), 0);
676 }
677 if keep.is_empty() {
681 return (output.to_string(), 0);
682 }
683 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;