Skip to main content

lean_ctx/tools/registered/
ctx_compose.rs

1use std::collections::{BTreeMap, HashSet};
2use std::path::Path;
3
4use crate::core::ocla::cache_types::{CacheKeyBuilder, ComposedContextKey};
5use rmcp::ErrorData;
6use rmcp::model::Tool;
7use serde_json::{Map, Value, json};
8
9use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_bool, get_str};
10use crate::tool_defs::tool_def;
11
12pub struct CtxComposeTool;
13
14const MIN_TASK_AWARE_COVERAGE: f32 = 0.20;
15const TASK_AWARE_TOP_K: usize = 2;
16const TASK_AWARE_DIVERSE_SECTIONS: usize = 1;
17const PROFILE_KEYWORD_WEIGHT: f32 = 0.45;
18const STOP_WORD_WEIGHT: f32 = 0.20;
19const QUERY_STOP_WORDS: &[&str] = &[
20    "a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "how", "in", "is", "it", "of",
21    "on", "or", "that", "the", "this", "to", "use", "what", "with",
22];
23
24#[derive(Debug, Clone)]
25struct QueryKeyword {
26    term: String,
27    weight: f32,
28}
29
30#[derive(Debug)]
31struct ScoredSection<'a> {
32    index: usize,
33    text: &'a str,
34    score: f32,
35    matched_terms: HashSet<String>,
36}
37
38fn normalized_keywords(input: &str) -> Vec<String> {
39    let mut keywords = input
40        .split(|character: char| !character.is_alphanumeric())
41        .map(str::to_lowercase)
42        .filter(|keyword| keyword.chars().count() > 1)
43        .collect::<Vec<_>>();
44    keywords.sort_unstable();
45    keywords.dedup();
46    keywords
47}
48
49fn add_keywords(weights: &mut BTreeMap<String, f32>, input: &str, source_weight: f32) {
50    for keyword in normalized_keywords(input) {
51        let weight = if QUERY_STOP_WORDS.contains(&keyword.as_str()) {
52            source_weight * STOP_WORD_WEIGHT
53        } else {
54            source_weight
55        };
56        weights
57            .entry(keyword)
58            .and_modify(|existing| *existing = (*existing).max(weight))
59            .or_insert(weight);
60    }
61}
62
63fn task_aware_keywords(
64    task: &str,
65    profile: &crate::core::triage::profile::TaskProfileLocal,
66) -> Vec<QueryKeyword> {
67    let mut weights = BTreeMap::new();
68    // The caller's task is the retrieval query. Profile fields only provide a
69    // lower-weight session hint so broad classes such as `bug_fix` cannot win.
70    add_keywords(&mut weights, task, 1.0);
71    add_keywords(&mut weights, &profile.task_class, PROFILE_KEYWORD_WEIGHT);
72    add_keywords(&mut weights, &profile.intent, PROFILE_KEYWORD_WEIGHT);
73    weights
74        .into_iter()
75        .map(|(term, weight)| QueryKeyword { term, weight })
76        .collect()
77}
78
79fn score_section(chunk: &str, keywords: &[QueryKeyword]) -> (f32, HashSet<String>) {
80    let terms = normalized_keywords(chunk)
81        .into_iter()
82        .collect::<HashSet<_>>();
83    let mut matched_terms = HashSet::new();
84    let mut matched_weight = 0.0;
85    let mut total_weight = 0.0;
86
87    for keyword in keywords {
88        total_weight += keyword.weight;
89        if terms.contains(&keyword.term) {
90            matched_weight += keyword.weight;
91            matched_terms.insert(keyword.term.clone());
92        }
93    }
94
95    let score = if total_weight > 0.0 {
96        matched_weight / total_weight
97    } else {
98        0.0
99    };
100    (score, matched_terms)
101}
102
103fn select_task_aware_sections<'a>(
104    mut sections: Vec<ScoredSection<'a>>,
105    keywords: &[QueryKeyword],
106    task_terms: &HashSet<String>,
107) -> Vec<ScoredSection<'a>> {
108    sections.retain(|section| section.score >= MIN_TASK_AWARE_COVERAGE);
109    sections.sort_by(|left, right| {
110        right
111            .score
112            .total_cmp(&left.score)
113            .then_with(|| left.index.cmp(&right.index))
114    });
115
116    let top_k = sections.len().min(TASK_AWARE_TOP_K);
117    let mut selected = sections.drain(..top_k).collect::<Vec<_>>();
118    let mut covered_terms = selected
119        .iter()
120        .flat_map(|section| section.matched_terms.iter().cloned())
121        .collect::<HashSet<_>>();
122
123    for _ in 0..TASK_AWARE_DIVERSE_SECTIONS {
124        let Some((position, _)) = sections
125            .iter()
126            .enumerate()
127            .filter_map(|(position, section)| {
128                let novel_weight = keywords
129                    .iter()
130                    .filter(|keyword| {
131                        task_terms.contains(&keyword.term)
132                            && section.matched_terms.contains(&keyword.term)
133                            && !covered_terms.contains(&keyword.term)
134                    })
135                    .map(|keyword| keyword.weight)
136                    .sum::<f32>();
137                (novel_weight > 0.0).then_some((position, novel_weight))
138            })
139            .max_by(
140                |(left_position, left_weight), (right_position, right_weight)| {
141                    left_weight
142                        .total_cmp(right_weight)
143                        .then_with(|| {
144                            sections[*left_position]
145                                .score
146                                .total_cmp(&sections[*right_position].score)
147                        })
148                        .then_with(|| {
149                            sections[*right_position]
150                                .index
151                                .cmp(&sections[*left_position].index)
152                        })
153                },
154            )
155        else {
156            break;
157        };
158
159        let section = sections.remove(position);
160        covered_terms.extend(section.matched_terms.iter().cloned());
161        selected.push(section);
162    }
163
164    selected
165}
166
167fn apply_task_aware_filter(
168    output: &str,
169    task: &str,
170    profile: &crate::core::triage::profile::TaskProfileLocal,
171    enabled: bool,
172) -> String {
173    if !enabled {
174        return output.to_owned();
175    }
176
177    let task_terms = normalized_keywords(task)
178        .into_iter()
179        .collect::<HashSet<_>>();
180    if task_terms.is_empty() {
181        return output.to_owned();
182    }
183    let keywords = task_aware_keywords(task, profile);
184    if keywords.is_empty() {
185        return output.to_owned();
186    }
187
188    let mut chunks = output.split("\n## ");
189    let prefix = chunks.next().unwrap_or_default();
190    let sections = chunks
191        .enumerate()
192        .map(|(index, chunk)| {
193            let (score, matched_terms) = score_section(chunk, &keywords);
194            ScoredSection {
195                index,
196                text: chunk,
197                score,
198                matched_terms,
199            }
200        })
201        .collect::<Vec<_>>();
202    let selected = select_task_aware_sections(sections, &keywords, &task_terms);
203    if selected.is_empty() {
204        return output.to_owned();
205    }
206
207    // Keep selected source byte-for-byte. The global dispatch pipeline owns
208    // line triage and the final turn budget, so compose is never compressed twice.
209    let mut filtered = prefix.to_owned();
210    for section in selected {
211        filtered.push_str("\n## ");
212        filtered.push_str(section.text);
213    }
214    filtered
215}
216
217fn current_task_profile(
218    ctx: &ToolContext,
219) -> Option<crate::core::triage::profile::TaskProfileLocal> {
220    let session = ctx.session.as_ref()?.try_read().ok()?;
221    crate::core::decision_loop_runtime::DecisionLoopRuntime::get_or_init()
222        .profile_for_session(&session.id)
223}
224
225const SOLUTION_HINT_ITEM_LIMIT: usize = 20;
226const UTILITY_DIRECTORIES: &[&str] = &["utils", "helpers", "common"];
227
228/// Collect declared dependencies from manifest files at the project root.
229fn project_dependencies(project_root: &Path) -> Vec<String> {
230    let mut dependencies = Vec::new();
231    cargo_dependencies(&project_root.join("Cargo.toml"), &mut dependencies);
232    package_dependencies(&project_root.join("package.json"), &mut dependencies);
233    requirements_dependencies(&project_root.join("requirements.txt"), &mut dependencies);
234    go_dependencies(&project_root.join("go.mod"), &mut dependencies);
235    dependencies
236}
237
238fn cargo_dependencies(manifest: &Path, dependencies: &mut Vec<String>) {
239    let Ok(content) = std::fs::read_to_string(manifest) else {
240        return;
241    };
242
243    let mut in_dependencies = false;
244    for line in content.lines() {
245        let trimmed = line.trim();
246        if let Some(section) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
247            in_dependencies = section == "dependencies"
248                || section == "workspace.dependencies"
249                || section.ends_with(".dependencies");
250            continue;
251        }
252        if !in_dependencies || trimmed.is_empty() || trimmed.starts_with('#') {
253            continue;
254        }
255        if let Some((name, _)) = trimmed.split_once('=') {
256            add_dependency(dependencies, name.trim().trim_matches(['\"', '\'']));
257        }
258    }
259}
260
261fn package_dependencies(manifest: &Path, dependencies: &mut Vec<String>) {
262    let Ok(content) = std::fs::read_to_string(manifest) else {
263        return;
264    };
265
266    for section in ["dependencies", "devDependencies"] {
267        let Some(dependency_object) = json_object_section(&content, section) else {
268            continue;
269        };
270        for entry in dependency_object.split(',') {
271            let name = entry
272                .trim_start()
273                .strip_prefix('"')
274                .and_then(|entry| entry.split_once('"'))
275                .map(|(name, _)| name)
276                .unwrap_or_default();
277            add_dependency(dependencies, name);
278        }
279    }
280}
281
282fn json_object_section<'a>(content: &'a str, section: &str) -> Option<&'a str> {
283    let section_marker = format!("\"{section}\"");
284    let section_start = content.find(&section_marker)? + section_marker.len();
285    let value = content[section_start..].split_once(':')?.1.trim_start();
286    if !value.starts_with('{') {
287        return None;
288    }
289    let object_start = content.len() - value.len();
290    let mut depth = 0usize;
291    let mut in_string = false;
292    let mut escaped = false;
293
294    for (offset, character) in content[object_start..].char_indices() {
295        if in_string {
296            if escaped {
297                escaped = false;
298            } else if character == '\\' {
299                escaped = true;
300            } else if character == '"' {
301                in_string = false;
302            }
303            continue;
304        }
305        match character {
306            '"' => in_string = true,
307            '{' => depth += 1,
308            '}' => {
309                depth -= 1;
310                if depth == 0 {
311                    return Some(&content[object_start + 1..object_start + offset]);
312                }
313            }
314            _ => {}
315        }
316    }
317    None
318}
319
320fn requirements_dependencies(manifest: &Path, dependencies: &mut Vec<String>) {
321    let Ok(content) = std::fs::read_to_string(manifest) else {
322        return;
323    };
324
325    for line in content.lines() {
326        let requirement = line.split('#').next().unwrap_or_default().trim();
327        if requirement.is_empty() || requirement.starts_with('-') {
328            continue;
329        }
330        let name = requirement
331            .split(|c: char| matches!(c, '=' | '<' | '>' | '!' | '~' | ';' | '[' | ' '))
332            .next()
333            .unwrap_or_default()
334            .trim();
335        add_dependency(dependencies, name);
336    }
337}
338
339fn go_dependencies(manifest: &Path, dependencies: &mut Vec<String>) {
340    let Ok(content) = std::fs::read_to_string(manifest) else {
341        return;
342    };
343
344    let mut in_require_block = false;
345    for line in content.lines() {
346        let trimmed = line.split("//").next().unwrap_or_default().trim();
347        if trimmed.is_empty() {
348            continue;
349        }
350        if let Some(requirement) = trimmed.strip_prefix("require") {
351            let requirement = requirement.trim();
352            if requirement == "(" {
353                in_require_block = true;
354            } else if let Some(name) = requirement.split_whitespace().next() {
355                add_dependency(dependencies, name);
356            }
357            continue;
358        }
359        if in_require_block && trimmed == ")" {
360            in_require_block = false;
361            continue;
362        }
363        if in_require_block {
364            if let Some(name) = trimmed.split_whitespace().next() {
365                add_dependency(dependencies, name);
366            }
367        }
368    }
369}
370
371fn add_dependency(dependencies: &mut Vec<String>, dependency: &str) {
372    if !dependency.is_empty() && !dependencies.iter().any(|known| known == dependency) {
373        dependencies.push(dependency.to_string());
374    }
375}
376
377/// List files in conventional utility directories rooted at the project.
378fn project_utility_files(project_root: &Path) -> Vec<String> {
379    let mut files = Vec::new();
380    for directory in UTILITY_DIRECTORIES {
381        let utility_root = project_root.join(directory);
382        if !utility_root.is_dir() {
383            continue;
384        }
385        for entry in ignore::WalkBuilder::new(&utility_root)
386            .hidden(false)
387            .follow_links(false)
388            .build()
389            .flatten()
390        {
391            if !entry
392                .file_type()
393                .is_some_and(|file_type| file_type.is_file())
394            {
395                continue;
396            }
397            if let Ok(relative_path) = entry.path().strip_prefix(project_root) {
398                files.push(relative_path.to_string_lossy().replace('\\', "/"));
399            }
400        }
401    }
402    files.sort();
403    files.dedup();
404    files
405}
406
407fn utility_hint(utility_files: &[String]) -> Option<String> {
408    (!utility_files.is_empty()).then(|| {
409        let listed = utility_files
410            .iter()
411            .take(SOLUTION_HINT_ITEM_LIMIT)
412            .map(String::as_str)
413            .collect::<Vec<_>>();
414        let remaining = utility_files.len().saturating_sub(listed.len());
415        let suffix = (remaining > 0).then(|| format!(", … (+{remaining} more)"));
416        format!(
417            "Existing utilities: {}{}",
418            listed.join(", "),
419            suffix.unwrap_or_default()
420        )
421    })
422}
423
424/// Extract unique file paths from compose output and sum their raw byte sizes
425/// to compute what the agent would have read without compose.
426fn project_stdlib_hint(project_root: &Path) -> &'static str {
427    if project_root.join("Cargo.toml").is_file() {
428        "std::{fs, path, collections, io, process}"
429    } else if project_root.join("package.json").is_file() {
430        "node:fs, node:path, node:util, node:child_process"
431    } else if project_root.join("requirements.txt").is_file()
432        || project_root.join("pyproject.toml").is_file()
433    {
434        "pathlib, collections, json, subprocess"
435    } else if project_root.join("go.mod").is_file() {
436        "io, os, path/filepath, strings, net/http"
437    } else {
438        "filesystem, collections, and process APIs"
439    }
440}
441
442fn estimate_raw_input_tokens(compose_output: &str, project_root: &str) -> usize {
443    let mut seen = HashSet::new();
444    let mut raw_bytes: u64 = 0;
445    let root = Path::new(project_root);
446
447    for line in compose_output.lines() {
448        let trimmed = line.trim();
449        let candidate = if let Some(rest) = trimmed.strip_prefix("// ") {
450            rest.split(':').next().map(str::trim)
451        } else if trimmed.bytes().next().is_some_and(|b| b.is_ascii_digit()) {
452            trimmed
453                .split_once(". ")
454                .map(|x| x.1)
455                .and_then(|s| s.split(" (").next())
456                .map(str::trim)
457        } else if trimmed.contains(':') && !trimmed.starts_with('#') && !trimmed.starts_with("TASK")
458        {
459            let part = trimmed.split(':').next().unwrap_or("").trim();
460            if part.contains('.') && !part.contains(' ') {
461                Some(part)
462            } else {
463                None
464            }
465        } else {
466            None
467        };
468
469        if let Some(rel) = candidate {
470            if rel.is_empty() || rel.len() > 256 {
471                continue;
472            }
473            let full = root.join(rel);
474            if seen.insert(full.clone()) {
475                if let Ok(meta) = std::fs::metadata(&full) {
476                    if meta.is_file() {
477                        raw_bytes += meta.len();
478                    }
479                }
480            }
481        }
482    }
483
484    (raw_bytes / 4) as usize
485}
486
487impl McpTool for CtxComposeTool {
488    fn name(&self) -> &'static str {
489        "ctx_compose"
490    }
491
492    fn tool_def(&self) -> Tool {
493        tool_def(
494            "ctx_compose",
495            "First-pass context for one task; returns ranked files and inline source — use instead of search→read chains.",
496            json!({
497                "type": "object",
498                "properties": {
499                    "task": { "type": "string", "description": "Short English task/question or symbol names" },
500                    "path": { "type": "string", "description": "Project root" },
501                    "task_aware": { "type": "boolean", "default": true, "description": "Rank compose sections against the task (default: true)" }
502                },
503                "required": ["task"]
504            }),
505        )
506    }
507
508    fn handle(
509        &self,
510        args: &Map<String, Value>,
511        ctx: &ToolContext,
512    ) -> Result<ToolOutput, ErrorData> {
513        let task = get_str(args, "task")
514            .ok_or_else(|| ErrorData::invalid_params("task is required", None))?;
515        let task_aware = get_bool(args, "task_aware").unwrap_or(true);
516        let path = if let Some(p) = ctx.resolved_path("path") {
517            p.to_string()
518        } else if let Some(err) = ctx.path_error("path") {
519            return Err(ErrorData::invalid_params(format!("path: {err}"), None));
520        } else {
521            ctx.project_root.clone()
522        };
523
524        // Share the resident BM25 cache with the composed semantic search.
525        if let Some(ref cache) = ctx.bm25_cache {
526            crate::tools::ctx_semantic_search::set_thread_cache(cache.clone());
527        }
528
529        let cache_enabled = crate::core::config::Config::load()
530            .cache
531            .compose_cache_enabled;
532        let cached = cache_enabled
533            .then(|| crate::core::ocla::compose_cache::global().check(&task, &path))
534            .flatten();
535        let (text, _) = if let Some(text) = cached {
536            let sent = crate::core::tokens::count_tokens(&text);
537            (text, sent)
538        } else {
539            // Cross-process delivery check before expensive computation
540            let compose_builder = ComposedContextKey {
541                task: task.clone(),
542                path: path.clone(),
543                source_digests: Vec::new(),
544            };
545            let ck = compose_builder.cache_key();
546            let cv = compose_builder.validator();
547            if let Some(entry) = crate::core::ocla::cache_delivery::check(&ck, &cv, "ctx_compose") {
548                let stub = crate::core::ocla::cache_delivery::stub(&entry, "compose");
549                let sent = crate::core::tokens::count_tokens(&stub);
550                (stub, sent)
551            } else {
552                let (text, sent) = tokio::task::block_in_place(|| {
553                    crate::tools::ctx_compose::handle(&task, &path, ctx.crp_mode)
554                });
555                if cache_enabled && !text.starts_with("ERROR") {
556                    crate::core::ocla::compose_cache::global().record(&task, &path, text.clone());
557                    crate::core::ocla::cache_delivery::record(
558                        ck,
559                        crate::core::ocla::cache_types::DeliveryKind::ComposedContext,
560                        cv,
561                        Some(path.clone()),
562                        &text,
563                        "ctx_compose",
564                    );
565                }
566                (text, sent)
567            }
568        };
569
570        if text.starts_with("ERROR") {
571            return Err(ErrorData::invalid_params(text, None));
572        }
573
574        let text = current_task_profile(ctx).map_or_else(
575            || text.clone(),
576            |profile| apply_task_aware_filter(&text, &task, &profile, task_aware),
577        );
578        let text = {
579            let cfg = crate::core::config::Config::load();
580            if cfg.solution.enabled && cfg.solution.inject_in_compose {
581                let project_root = Path::new(&path);
582                let project_deps = project_dependencies(project_root);
583                let helper_files = project_utility_files(project_root);
584                let dependencies = if project_deps.is_empty() {
585                    "no manifest dependencies detected".to_string()
586                } else {
587                    project_deps.join(", ")
588                };
589                let mut hints = format!(
590                    "--- SOLUTION HINTS ---\n\
591• Found {} existing helpers that may apply\n\
592• Project uses: {} (check before adding new)\n\
593• stdlib covers: {}",
594                    helper_files.len(),
595                    dependencies,
596                    project_stdlib_hint(project_root),
597                );
598                if let Some(utility_hint) = utility_hint(&helper_files) {
599                    hints.push('\n');
600                    hints.push_str(&utility_hint);
601                }
602                if hints.is_empty() {
603                    text
604                } else {
605                    format!("{text}\n\n{hints}")
606                }
607            } else {
608                text
609            }
610        };
611        let sent = crate::core::tokens::count_tokens(&text);
612
613        let raw_tokens = estimate_raw_input_tokens(&text, &path);
614        let original = if raw_tokens > sent { raw_tokens } else { sent };
615        let saved = original.saturating_sub(sent);
616
617        Ok(ToolOutput {
618            text,
619            original_tokens: original,
620            saved_tokens: saved,
621            mode: Some("compose".to_string()),
622            path: Some(path),
623            changed: false,
624            shell_outcome: None,
625            content_blocks: None,
626        })
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633    use crate::core::triage::profile::{TaskProfileLocal, TaskScopeLocal};
634
635    fn profile(task_class: &str, intent: &str, context_need_milli: u16) -> TaskProfileLocal {
636        TaskProfileLocal {
637            task_class: task_class.into(),
638            intent: intent.into(),
639            complexity: "low".into(),
640            scope: TaskScopeLocal::SingleFile,
641            context_need_milli,
642            reasoning_need_milli: 0,
643            risk_signal_milli: 0,
644            confidence_milli: 500,
645        }
646    }
647
648    #[test]
649    fn task_aware_filter_can_be_disabled() {
650        let output = "TASK: test\n\n## Unrelated\nwidget catalog\n";
651        assert_eq!(
652            apply_task_aware_filter(
653                output,
654                "target query",
655                &profile("bug_fix", "fix filtering", 700),
656                false
657            ),
658            output
659        );
660    }
661
662    use super::{project_dependencies, project_utility_files};
663
664    #[test]
665    fn detects_root_manifest_dependencies() {
666        let root = tempfile::tempdir().expect("tempdir");
667        std::fs::write(
668            root.path().join("Cargo.toml"),
669            "[dependencies]\ntokio = \"1\"\nserde = { version = \"1\" }\n",
670        )
671        .expect("Cargo.toml");
672        std::fs::write(
673            root.path().join("package.json"),
674            r#"{"dependencies":{"react":"1","zod":"1"},"devDependencies":{"vitest":"1"}}"#,
675        )
676        .expect("package.json");
677        std::fs::write(
678            root.path().join("requirements.txt"),
679            "requests>=2\nrich[markdown]==1\n# comment\n",
680        )
681        .expect("requirements.txt");
682        std::fs::write(
683            root.path().join("go.mod"),
684            "module example.com/project\n\nrequire (\n\tgithub.com/gin-gonic/gin v1.0.0\n\tgolang.org/x/crypto v0.1.0\n)\n",
685        )
686        .expect("go.mod");
687
688        assert_eq!(
689            project_dependencies(root.path()),
690            vec![
691                "tokio".to_string(),
692                "serde".to_string(),
693                "react".to_string(),
694                "zod".to_string(),
695                "vitest".to_string(),
696                "requests".to_string(),
697                "rich".to_string(),
698                "github.com/gin-gonic/gin".to_string(),
699                "golang.org/x/crypto".to_string(),
700            ]
701        );
702    }
703
704    #[test]
705    fn task_aware_filter_uses_the_call_task_over_session_profile() {
706        let output = "TASK: test\n\n## Query A\nrenew oauth token\n\n## Query B\noauth renewal flow\n\n## Session profile\nmaintenance routine\n";
707        let filtered = apply_task_aware_filter(
708            output,
709            "renew oauth token",
710            &profile("maintenance", "routine", 700),
711            true,
712        );
713
714        assert!(filtered.contains("## Query A"));
715        assert!(filtered.contains("## Query B"));
716        assert!(!filtered.contains("## Session profile"));
717    }
718
719    #[test]
720    fn task_aware_filter_downweights_stop_words() {
721        let output =
722            "TASK: test\n\n## Generic\nhow to do this\n\n## Parser\nupdate parser properly\n";
723        let filtered = apply_task_aware_filter(
724            output,
725            "how to update the parser properly",
726            &profile("maintenance", "routine", 700),
727            true,
728        );
729
730        assert!(filtered.contains("## Parser"));
731        assert!(!filtered.contains("## Generic"));
732    }
733
734    #[test]
735    fn task_aware_filter_uses_top_k_then_diverse_coverage() {
736        let output = "TASK: test\n\n## A\ncache storage retries\n\n## B\ncache storage retries duplicate\n\n## C\nmetrics\n\n## D\ncache\n";
737        let filtered = apply_task_aware_filter(
738            output,
739            "cache storage retries metrics",
740            &profile("cache", "storage retries metrics", 700),
741            true,
742        );
743
744        assert!(filtered.contains("## A"));
745        assert!(filtered.contains("## B"));
746        assert!(filtered.contains("## C"));
747        assert!(!filtered.contains("## D"));
748    }
749
750    #[test]
751    fn task_aware_filter_leaves_triage_to_the_global_pipeline() {
752        let output = format!(
753            "TASK: test\n\n## Relevant\nfix context gate\n{}// TODO: keep this\n",
754            "// boilerplate\n".repeat(40)
755        );
756        let filtered = apply_task_aware_filter(
757            &output,
758            "fix context gate",
759            &profile("bug_fix", "fix context gate filtering", 450),
760            true,
761        );
762        assert!(filtered.contains("## Relevant"));
763        assert!(filtered.contains("// TODO: keep this"));
764        assert!(filtered.contains("// boilerplate"));
765        assert!(!filtered.contains("filtered by triage"));
766    }
767
768    #[test]
769    fn finds_files_in_root_utility_directories() {
770        let root = tempfile::tempdir().expect("tempdir");
771        std::fs::create_dir_all(root.path().join("utils/nested")).expect("utils directory");
772        std::fs::create_dir_all(root.path().join("helpers")).expect("helpers directory");
773        std::fs::create_dir_all(root.path().join("common")).expect("common directory");
774        for file in [
775            "utils/nested/time.rs",
776            "helpers/format.ts",
777            "common/model.py",
778        ] {
779            std::fs::write(root.path().join(file), "").expect("utility file");
780        }
781
782        assert_eq!(
783            project_utility_files(root.path()),
784            vec![
785                "common/model.py".to_string(),
786                "helpers/format.ts".to_string(),
787                "utils/nested/time.rs".to_string(),
788            ]
789        );
790    }
791}