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 read_manifest(manifest: &Path) -> std::io::Result<String> {
239    let root = manifest.parent().unwrap_or(manifest);
240    crate::tools::ctx_read::read_file_for_tool_rooted(
241        &manifest.to_string_lossy(),
242        &root.to_string_lossy(),
243        "ctx_compose",
244    )
245}
246
247fn cargo_dependencies(manifest: &Path, dependencies: &mut Vec<String>) {
248    let Ok(content) = read_manifest(manifest) else {
249        return;
250    };
251
252    let mut in_dependencies = false;
253    for line in content.lines() {
254        let trimmed = line.trim();
255        if let Some(section) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
256            in_dependencies = section == "dependencies"
257                || section == "workspace.dependencies"
258                || section.ends_with(".dependencies");
259            continue;
260        }
261        if !in_dependencies || trimmed.is_empty() || trimmed.starts_with('#') {
262            continue;
263        }
264        if let Some((name, _)) = trimmed.split_once('=') {
265            add_dependency(dependencies, name.trim().trim_matches(['\"', '\'']));
266        }
267    }
268}
269
270fn package_dependencies(manifest: &Path, dependencies: &mut Vec<String>) {
271    let Ok(content) = read_manifest(manifest) else {
272        return;
273    };
274
275    for section in ["dependencies", "devDependencies"] {
276        let Some(dependency_object) = json_object_section(&content, section) else {
277            continue;
278        };
279        for entry in dependency_object.split(',') {
280            let name = entry
281                .trim_start()
282                .strip_prefix('"')
283                .and_then(|entry| entry.split_once('"'))
284                .map(|(name, _)| name)
285                .unwrap_or_default();
286            add_dependency(dependencies, name);
287        }
288    }
289}
290
291fn json_object_section<'a>(content: &'a str, section: &str) -> Option<&'a str> {
292    let section_marker = format!("\"{section}\"");
293    let section_start = content.find(&section_marker)? + section_marker.len();
294    let value = content[section_start..].split_once(':')?.1.trim_start();
295    if !value.starts_with('{') {
296        return None;
297    }
298    let object_start = content.len() - value.len();
299    let mut depth = 0usize;
300    let mut in_string = false;
301    let mut escaped = false;
302
303    for (offset, character) in content[object_start..].char_indices() {
304        if in_string {
305            if escaped {
306                escaped = false;
307            } else if character == '\\' {
308                escaped = true;
309            } else if character == '"' {
310                in_string = false;
311            }
312            continue;
313        }
314        match character {
315            '"' => in_string = true,
316            '{' => depth += 1,
317            '}' => {
318                depth -= 1;
319                if depth == 0 {
320                    return Some(&content[object_start + 1..object_start + offset]);
321                }
322            }
323            _ => {}
324        }
325    }
326    None
327}
328
329fn requirements_dependencies(manifest: &Path, dependencies: &mut Vec<String>) {
330    let Ok(content) = read_manifest(manifest) else {
331        return;
332    };
333
334    for line in content.lines() {
335        let requirement = line.split('#').next().unwrap_or_default().trim();
336        if requirement.is_empty() || requirement.starts_with('-') {
337            continue;
338        }
339        let name = requirement
340            .split(|c: char| matches!(c, '=' | '<' | '>' | '!' | '~' | ';' | '[' | ' '))
341            .next()
342            .unwrap_or_default()
343            .trim();
344        add_dependency(dependencies, name);
345    }
346}
347
348fn go_dependencies(manifest: &Path, dependencies: &mut Vec<String>) {
349    let Ok(content) = read_manifest(manifest) else {
350        return;
351    };
352
353    let mut in_require_block = false;
354    for line in content.lines() {
355        let trimmed = line.split("//").next().unwrap_or_default().trim();
356        if trimmed.is_empty() {
357            continue;
358        }
359        if let Some(requirement) = trimmed.strip_prefix("require") {
360            let requirement = requirement.trim();
361            if requirement == "(" {
362                in_require_block = true;
363            } else if let Some(name) = requirement.split_whitespace().next() {
364                add_dependency(dependencies, name);
365            }
366            continue;
367        }
368        if in_require_block && trimmed == ")" {
369            in_require_block = false;
370            continue;
371        }
372        if in_require_block {
373            if let Some(name) = trimmed.split_whitespace().next() {
374                add_dependency(dependencies, name);
375            }
376        }
377    }
378}
379
380fn add_dependency(dependencies: &mut Vec<String>, dependency: &str) {
381    if !dependency.is_empty() && !dependencies.iter().any(|known| known == dependency) {
382        dependencies.push(dependency.to_string());
383    }
384}
385
386/// List files in conventional utility directories rooted at the project.
387fn project_utility_files(project_root: &Path) -> Vec<String> {
388    let mut files = Vec::new();
389    let protected = crate::core::policy::runtime::is_active();
390    let mut inspected = 0usize;
391    let mut remaining_bytes = 8 * 1024 * 1024;
392    'directories: for directory in UTILITY_DIRECTORIES {
393        let utility_root = project_root.join(directory);
394        if !utility_root.is_dir() {
395            continue;
396        }
397        for entry in ignore::WalkBuilder::new(&utility_root)
398            .hidden(false)
399            .follow_links(false)
400            .build()
401            .flatten()
402            .take(256)
403        {
404            if !entry
405                .file_type()
406                .is_some_and(|file_type| file_type.is_file())
407            {
408                continue;
409            }
410            if let Ok(relative_path) = entry.path().strip_prefix(project_root) {
411                if crate::core::io_boundary::jail_and_check_path(
412                    "ctx_compose",
413                    entry.path(),
414                    project_root,
415                )
416                .is_err()
417                {
418                    continue;
419                }
420                if protected {
421                    if inspected >= 32 || remaining_bytes == 0 {
422                        break 'directories;
423                    }
424                    inspected += 1;
425                    let Ok(_) = crate::tools::ctx_read::read_file_for_tool_rooted_budgeted(
426                        &entry.path().to_string_lossy(),
427                        &project_root.to_string_lossy(),
428                        "ctx_compose",
429                        &mut remaining_bytes,
430                    ) else {
431                        continue;
432                    };
433                }
434                files.push(relative_path.to_string_lossy().replace('\\', "/"));
435            }
436        }
437    }
438    files.sort();
439    files.dedup();
440    files
441}
442
443fn utility_hint(utility_files: &[String]) -> Option<String> {
444    (!utility_files.is_empty()).then(|| {
445        let listed = utility_files
446            .iter()
447            .take(SOLUTION_HINT_ITEM_LIMIT)
448            .map(String::as_str)
449            .collect::<Vec<_>>();
450        let remaining = utility_files.len().saturating_sub(listed.len());
451        let suffix = (remaining > 0).then(|| format!(", … (+{remaining} more)"));
452        format!(
453            "Existing utilities: {}{}",
454            listed.join(", "),
455            suffix.unwrap_or_default()
456        )
457    })
458}
459
460/// Extract unique file paths from compose output and sum their raw byte sizes
461/// to compute what the agent would have read without compose.
462fn project_stdlib_hint(project_root: &Path) -> &'static str {
463    if read_manifest(&project_root.join("Cargo.toml")).is_ok() {
464        "std::{fs, path, collections, io, process}"
465    } else if read_manifest(&project_root.join("package.json")).is_ok() {
466        "node:fs, node:path, node:util, node:child_process"
467    } else if read_manifest(&project_root.join("requirements.txt")).is_ok()
468        || read_manifest(&project_root.join("pyproject.toml")).is_ok()
469    {
470        "pathlib, collections, json, subprocess"
471    } else if read_manifest(&project_root.join("go.mod")).is_ok() {
472        "io, os, path/filepath, strings, net/http"
473    } else {
474        "filesystem, collections, and process APIs"
475    }
476}
477
478fn estimate_raw_input_tokens(compose_output: &str, project_root: &str) -> usize {
479    // Text-derived paths are not receipts for original protected bytes. Avoid
480    // disclosing metadata or claiming savings from an unverified source set.
481    if crate::core::policy::runtime::is_active() {
482        return 0;
483    }
484    let mut seen = HashSet::new();
485    let mut raw_bytes: u64 = 0;
486    let root = Path::new(project_root);
487
488    for line in compose_output.lines() {
489        let trimmed = line.trim();
490        let candidate = if let Some(rest) = trimmed.strip_prefix("// ") {
491            rest.split(':').next().map(str::trim)
492        } else if trimmed.bytes().next().is_some_and(|b| b.is_ascii_digit()) {
493            trimmed
494                .split_once(". ")
495                .map(|x| x.1)
496                .and_then(|s| s.split(" (").next())
497                .map(str::trim)
498        } else if trimmed.contains(':') && !trimmed.starts_with('#') && !trimmed.starts_with("TASK")
499        {
500            let part = trimmed.split(':').next().unwrap_or("").trim();
501            if part.contains('.') && !part.contains(' ') {
502                Some(part)
503            } else {
504                None
505            }
506        } else {
507            None
508        };
509
510        if let Some(rel) = candidate {
511            if rel.is_empty() || rel.len() > 256 {
512                continue;
513            }
514            let full = root.join(rel);
515            if crate::core::io_boundary::jail_and_check_path("ctx_compose", &full, root).is_err() {
516                continue;
517            }
518            if seen.insert(full.clone()) {
519                if let Ok(meta) = std::fs::metadata(&full) {
520                    if meta.is_file() {
521                        raw_bytes += meta.len();
522                    }
523                }
524            }
525        }
526    }
527
528    (raw_bytes / 4) as usize
529}
530
531impl McpTool for CtxComposeTool {
532    fn name(&self) -> &'static str {
533        "ctx_compose"
534    }
535
536    fn tool_def(&self) -> Tool {
537        tool_def(
538            "ctx_compose",
539            "First-pass context for one task; returns ranked files and inline source — use instead of search→read chains.",
540            json!({
541                "type": "object",
542                "properties": {
543                    "task": { "type": "string", "description": "Short English task/question or symbol names" },
544                    "path": { "type": "string", "description": "Project root" },
545                    "task_aware": { "type": "boolean", "default": true, "description": "Rank compose sections against the task (default: true)" }
546                },
547                "required": ["task"]
548            }),
549        )
550    }
551
552    fn handle(
553        &self,
554        args: &Map<String, Value>,
555        ctx: &ToolContext,
556    ) -> Result<ToolOutput, ErrorData> {
557        let mut pending_cache = None;
558        let result =
559            crate::core::policy::runtime::with_project_source_view(&ctx.project_root, || {
560                let task = get_str(args, "task")
561                    .ok_or_else(|| ErrorData::invalid_params("task is required", None))?;
562                let task_aware = get_bool(args, "task_aware").unwrap_or(true);
563                let path = if let Some(p) = ctx.resolved_path("path") {
564                    p.to_string()
565                } else if let Some(err) = ctx.path_error("path") {
566                    return Err(ErrorData::invalid_params(format!("path: {err}"), None));
567                } else {
568                    ctx.project_root.clone()
569                };
570
571                // Share the resident BM25 cache with the composed semantic search.
572                if let Some(ref cache) = ctx.bm25_cache {
573                    crate::tools::ctx_semantic_search::set_thread_cache(cache.clone());
574                }
575
576                let cache_enabled = crate::core::config::Config::load()
577                    .cache
578                    .compose_cache_enabled;
579                let cache_task =
580                    crate::core::context_kernel::bridge::runtime::compose_cache_task(&task);
581                let cached = cache_enabled
582                    .then(|| crate::core::ocla::compose_cache::global().check(&cache_task, &path))
583                    .flatten();
584                let (text, _) = if let Some(text) = cached {
585                    let sent = crate::core::tokens::count_tokens(&text);
586                    (text, sent)
587                } else {
588                    // Cross-process delivery check before expensive computation
589                    let source_revision = crate::core::ocla::compose_cache::source_revision(&path);
590                    let compose_builder = ComposedContextKey {
591                        task: cache_task.clone(),
592                        path: path.clone(),
593                        source_digests: source_revision.iter().cloned().collect(),
594                    };
595                    let ck = compose_builder.cache_key();
596                    let cv = compose_builder.validator();
597                    if let Some(entry) = source_revision.as_ref().and_then(|_| {
598                        crate::core::ocla::cache_delivery::check(&ck, &cv, "ctx_compose")
599                    }) {
600                        let stub = crate::core::ocla::cache_delivery::stub(&entry, "compose");
601                        let sent = crate::core::tokens::count_tokens(&stub);
602                        (stub, sent)
603                    } else {
604                        let (text, sent) = tokio::task::block_in_place(|| {
605                            crate::tools::ctx_compose::handle(&task, &path, ctx.crp_mode)
606                        });
607                        if cache_enabled && source_revision.is_some() && !text.starts_with("ERROR")
608                        {
609                            pending_cache = Some((
610                                cache_task,
611                                path.clone(),
612                                text.clone(),
613                                source_revision,
614                                ck,
615                                cv,
616                            ));
617                        }
618                        (text, sent)
619                    }
620                };
621
622                if text.starts_with("ERROR") {
623                    return Err(ErrorData::invalid_params(text, None));
624                }
625
626                let text = current_task_profile(ctx).map_or_else(
627                    || text.clone(),
628                    |profile| apply_task_aware_filter(&text, &task, &profile, task_aware),
629                );
630                let text = {
631                    let cfg = crate::core::config::Config::load();
632                    if cfg.solution.enabled && cfg.solution.inject_in_compose {
633                        let project_root = Path::new(&path);
634                        let project_deps = project_dependencies(project_root);
635                        let helper_files = project_utility_files(project_root);
636                        let dependencies = if project_deps.is_empty() {
637                            "no manifest dependencies detected".to_string()
638                        } else {
639                            project_deps.join(", ")
640                        };
641                        let mut hints = format!(
642                            "--- SOLUTION HINTS ---\n\
643• Found {} existing helpers that may apply\n\
644• Project uses: {} (check before adding new)\n\
645• stdlib covers: {}",
646                            helper_files.len(),
647                            dependencies,
648                            project_stdlib_hint(project_root),
649                        );
650                        if let Some(utility_hint) = utility_hint(&helper_files) {
651                            hints.push('\n');
652                            hints.push_str(&utility_hint);
653                        }
654                        if hints.is_empty() {
655                            text
656                        } else {
657                            format!("{text}\n\n{hints}")
658                        }
659                    } else {
660                        text
661                    }
662                };
663                let sent = crate::core::tokens::count_tokens(&text);
664
665                let raw_tokens = estimate_raw_input_tokens(&text, &path);
666                let original = if raw_tokens > sent { raw_tokens } else { sent };
667                let saved = original.saturating_sub(sent);
668
669                Ok(ToolOutput {
670                    text,
671                    original_tokens: original,
672                    saved_tokens: saved,
673                    mode: Some("compose".to_string()),
674                    path: Some(path),
675                    changed: false,
676                    shell_outcome: None,
677                    content_blocks: None,
678                })
679            })
680            .unwrap_or_else(|_| {
681                Err(ErrorData::internal_error(
682                    "Context output withheld: source authority changed or could not be verified",
683                    None,
684                ))
685            });
686        // No candidate content is persisted before the source-view guard accepts it.
687        if result.is_ok() {
688            if let Some((task, path, text, Some(revision), key, validator)) = pending_cache {
689                let _ = crate::core::policy::runtime::with_project_source_view(
690                    &ctx.project_root,
691                    || {
692                        if crate::core::ocla::compose_cache::global().record(
693                            &task,
694                            &path,
695                            text.clone(),
696                            &revision,
697                        ) {
698                            crate::core::ocla::cache_delivery::record(
699                                key,
700                                crate::core::ocla::cache_types::DeliveryKind::ComposedContext,
701                                validator,
702                                Some(path),
703                                &text,
704                                "ctx_compose",
705                            );
706                        }
707                    },
708                );
709            }
710        }
711        result
712    }
713}
714
715#[cfg(test)]
716mod tests {
717    use super::*;
718    use crate::core::triage::profile::{TaskProfileLocal, TaskScopeLocal};
719
720    fn profile(task_class: &str, intent: &str, context_need_milli: u16) -> TaskProfileLocal {
721        TaskProfileLocal {
722            task_class: task_class.into(),
723            intent: intent.into(),
724            complexity: "low".into(),
725            scope: TaskScopeLocal::SingleFile,
726            context_need_milli,
727            reasoning_need_milli: 0,
728            risk_signal_milli: 0,
729            confidence_milli: 500,
730        }
731    }
732
733    #[test]
734    fn task_aware_filter_can_be_disabled() {
735        let output = "TASK: test\n\n## Unrelated\nwidget catalog\n";
736        assert_eq!(
737            apply_task_aware_filter(
738                output,
739                "target query",
740                &profile("bug_fix", "fix filtering", 700),
741                false
742            ),
743            output
744        );
745    }
746
747    use super::{project_dependencies, project_utility_files};
748
749    #[test]
750    fn detects_root_manifest_dependencies() {
751        let root = tempfile::tempdir().expect("tempdir");
752        std::fs::write(
753            root.path().join("Cargo.toml"),
754            "[dependencies]\ntokio = \"1\"\nserde = { version = \"1\" }\n",
755        )
756        .expect("Cargo.toml");
757        std::fs::write(
758            root.path().join("package.json"),
759            r#"{"dependencies":{"react":"1","zod":"1"},"devDependencies":{"vitest":"1"}}"#,
760        )
761        .expect("package.json");
762        std::fs::write(
763            root.path().join("requirements.txt"),
764            "requests>=2\nrich[markdown]==1\n# comment\n",
765        )
766        .expect("requirements.txt");
767        std::fs::write(
768            root.path().join("go.mod"),
769            "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",
770        )
771        .expect("go.mod");
772
773        assert_eq!(
774            project_dependencies(root.path()),
775            vec![
776                "tokio".to_string(),
777                "serde".to_string(),
778                "react".to_string(),
779                "zod".to_string(),
780                "vitest".to_string(),
781                "requests".to_string(),
782                "rich".to_string(),
783                "github.com/gin-gonic/gin".to_string(),
784                "golang.org/x/crypto".to_string(),
785            ]
786        );
787    }
788
789    #[test]
790    fn task_aware_filter_uses_the_call_task_over_session_profile() {
791        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";
792        let filtered = apply_task_aware_filter(
793            output,
794            "renew oauth token",
795            &profile("maintenance", "routine", 700),
796            true,
797        );
798
799        assert!(filtered.contains("## Query A"));
800        assert!(filtered.contains("## Query B"));
801        assert!(!filtered.contains("## Session profile"));
802    }
803
804    #[test]
805    fn task_aware_filter_downweights_stop_words() {
806        let output =
807            "TASK: test\n\n## Generic\nhow to do this\n\n## Parser\nupdate parser properly\n";
808        let filtered = apply_task_aware_filter(
809            output,
810            "how to update the parser properly",
811            &profile("maintenance", "routine", 700),
812            true,
813        );
814
815        assert!(filtered.contains("## Parser"));
816        assert!(!filtered.contains("## Generic"));
817    }
818
819    #[test]
820    fn task_aware_filter_uses_top_k_then_diverse_coverage() {
821        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";
822        let filtered = apply_task_aware_filter(
823            output,
824            "cache storage retries metrics",
825            &profile("cache", "storage retries metrics", 700),
826            true,
827        );
828
829        assert!(filtered.contains("## A"));
830        assert!(filtered.contains("## B"));
831        assert!(filtered.contains("## C"));
832        assert!(!filtered.contains("## D"));
833    }
834
835    #[test]
836    fn task_aware_filter_leaves_triage_to_the_global_pipeline() {
837        let output = format!(
838            "TASK: test\n\n## Relevant\nfix context gate\n{}// TODO: keep this\n",
839            "// boilerplate\n".repeat(40)
840        );
841        let filtered = apply_task_aware_filter(
842            &output,
843            "fix context gate",
844            &profile("bug_fix", "fix context gate filtering", 450),
845            true,
846        );
847        assert!(filtered.contains("## Relevant"));
848        assert!(filtered.contains("// TODO: keep this"));
849        assert!(filtered.contains("// boilerplate"));
850        assert!(!filtered.contains("filtered by triage"));
851    }
852
853    #[test]
854    fn finds_files_in_root_utility_directories() {
855        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
856        let root = tempfile::tempdir().expect("tempdir");
857        std::fs::create_dir_all(root.path().join("utils/nested")).expect("utils directory");
858        std::fs::create_dir_all(root.path().join("helpers")).expect("helpers directory");
859        std::fs::create_dir_all(root.path().join("common")).expect("common directory");
860        for file in [
861            "utils/nested/time.rs",
862            "helpers/format.ts",
863            "common/model.py",
864        ] {
865            std::fs::write(root.path().join(file), "").expect("utility file");
866        }
867
868        assert_eq!(
869            project_utility_files(root.path()),
870            vec![
871                "common/model.py".to_string(),
872                "helpers/format.ts".to_string(),
873                "utils/nested/time.rs".to_string(),
874            ]
875        );
876    }
877
878    #[test]
879    fn community_utility_names_obey_secret_path_role_admission() {
880        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
881        let root = tempfile::tempdir().unwrap();
882        std::fs::create_dir(root.path().join("helpers")).unwrap();
883        std::fs::write(root.path().join("helpers/id_rsa"), "private key fixture").unwrap();
884        std::fs::write(root.path().join("helpers/allowed.rs"), "fn allowed() {}\n").unwrap();
885        let mut role = crate::core::roles::load_role("coder").unwrap();
886        role.io.allow_secret_paths = false;
887        crate::core::roles::with_test_active_role(role, || {
888            assert_eq!(
889                project_utility_files(root.path()),
890                vec!["helpers/allowed.rs"]
891            );
892        });
893    }
894}