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                // Search-style tools taught agents `query`; ctx_compose declares
561                // no other text field, so those spellings can only mean the task.
562                let task = ["task", "query", "question", "prompt", "goal"]
563                    .iter()
564                    .find_map(|key| get_str(args, key).filter(|v| !v.trim().is_empty()))
565                    .ok_or_else(|| {
566                        ErrorData::invalid_params(
567                            "task is required — the question or goal to gather context for, \
568                             e.g. ctx_compose(task=\"how is auth wired\")",
569                            None,
570                        )
571                    })?;
572                let task_aware = get_bool(args, "task_aware").unwrap_or(true);
573                let path = if let Some(p) = ctx.resolved_path("path") {
574                    p.to_string()
575                } else if let Some(err) = ctx.path_error("path") {
576                    return Err(ErrorData::invalid_params(format!("path: {err}"), None));
577                } else {
578                    ctx.project_root.clone()
579                };
580
581                // Share the resident BM25 cache with the composed semantic search.
582                if let Some(ref cache) = ctx.bm25_cache {
583                    crate::tools::ctx_semantic_search::set_thread_cache(cache.clone());
584                }
585
586                let cache_enabled = crate::core::config::Config::load()
587                    .cache
588                    .compose_cache_enabled;
589                let cache_task =
590                    crate::core::context_kernel::bridge::runtime::compose_cache_task(&task);
591                let cached = cache_enabled
592                    .then(|| crate::core::ocla::compose_cache::global().check(&cache_task, &path))
593                    .flatten();
594                let (text, _) = if let Some(text) = cached {
595                    let sent = crate::core::tokens::count_tokens(&text);
596                    (text, sent)
597                } else {
598                    // Cross-process delivery check before expensive computation
599                    let source_revision = crate::core::ocla::compose_cache::source_revision(&path);
600                    let compose_builder = ComposedContextKey {
601                        task: cache_task.clone(),
602                        path: path.clone(),
603                        source_digests: source_revision.iter().cloned().collect(),
604                    };
605                    let ck = compose_builder.cache_key();
606                    let cv = compose_builder.validator();
607                    if let Some(entry) = source_revision.as_ref().and_then(|_| {
608                        crate::core::ocla::cache_delivery::check(&ck, &cv, "ctx_compose")
609                    }) {
610                        let stub = crate::core::ocla::cache_delivery::stub(&entry, "compose");
611                        let sent = crate::core::tokens::count_tokens(&stub);
612                        (stub, sent)
613                    } else {
614                        let (text, sent) = tokio::task::block_in_place(|| {
615                            crate::tools::ctx_compose::handle(&task, &path, ctx.crp_mode)
616                        });
617                        if cache_enabled && source_revision.is_some() && !text.starts_with("ERROR")
618                        {
619                            pending_cache = Some((
620                                cache_task,
621                                path.clone(),
622                                text.clone(),
623                                source_revision,
624                                ck,
625                                cv,
626                            ));
627                        }
628                        (text, sent)
629                    }
630                };
631
632                if text.starts_with("ERROR") {
633                    return Err(ErrorData::invalid_params(text, None));
634                }
635
636                let text = current_task_profile(ctx).map_or_else(
637                    || text.clone(),
638                    |profile| apply_task_aware_filter(&text, &task, &profile, task_aware),
639                );
640                let text = {
641                    let cfg = crate::core::config::Config::load();
642                    if cfg.solution.enabled && cfg.solution.inject_in_compose {
643                        let project_root = Path::new(&path);
644                        let project_deps = project_dependencies(project_root);
645                        let helper_files = project_utility_files(project_root);
646                        let dependencies = if project_deps.is_empty() {
647                            "no manifest dependencies detected".to_string()
648                        } else {
649                            project_deps.join(", ")
650                        };
651                        let mut hints = format!(
652                            "--- SOLUTION HINTS ---\n\
653• Found {} existing helpers that may apply\n\
654• Project uses: {} (check before adding new)\n\
655• stdlib covers: {}",
656                            helper_files.len(),
657                            dependencies,
658                            project_stdlib_hint(project_root),
659                        );
660                        if let Some(utility_hint) = utility_hint(&helper_files) {
661                            hints.push('\n');
662                            hints.push_str(&utility_hint);
663                        }
664                        if hints.is_empty() {
665                            text
666                        } else {
667                            format!("{text}\n\n{hints}")
668                        }
669                    } else {
670                        text
671                    }
672                };
673                let sent = crate::core::tokens::count_tokens(&text);
674
675                let raw_tokens = estimate_raw_input_tokens(&text, &path);
676                let original = if raw_tokens > sent { raw_tokens } else { sent };
677                let saved = original.saturating_sub(sent);
678
679                Ok(ToolOutput {
680                    text,
681                    original_tokens: original,
682                    saved_tokens: saved,
683                    mode: Some("compose".to_string()),
684                    path: Some(path),
685                    changed: false,
686                    shell_outcome: None,
687                    content_blocks: None,
688                })
689            })
690            .unwrap_or_else(|reason| {
691                // The reason is a fixed, content-free policy-runtime string;
692                // naming it separates a real policy change from a stale view.
693                Err(ErrorData::internal_error(
694                    format!(
695                        "Context output withheld: source authority changed or could not be verified ({reason})"
696                    ),
697                    None,
698                ))
699            });
700        // No candidate content is persisted before the source-view guard accepts it.
701        if result.is_ok() {
702            if let Some((task, path, text, Some(revision), key, validator)) = pending_cache {
703                let _ = crate::core::policy::runtime::with_project_source_view(
704                    &ctx.project_root,
705                    || {
706                        if crate::core::ocla::compose_cache::global().record(
707                            &task,
708                            &path,
709                            text.clone(),
710                            &revision,
711                        ) {
712                            crate::core::ocla::cache_delivery::record(
713                                key,
714                                crate::core::ocla::cache_types::DeliveryKind::ComposedContext,
715                                validator,
716                                Some(path),
717                                &text,
718                                "ctx_compose",
719                            );
720                        }
721                    },
722                );
723            }
724        }
725        result
726    }
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732    use crate::core::triage::profile::{TaskProfileLocal, TaskScopeLocal};
733
734    fn profile(task_class: &str, intent: &str, context_need_milli: u16) -> TaskProfileLocal {
735        TaskProfileLocal {
736            task_class: task_class.into(),
737            intent: intent.into(),
738            complexity: "low".into(),
739            scope: TaskScopeLocal::SingleFile,
740            context_need_milli,
741            reasoning_need_milli: 0,
742            risk_signal_milli: 0,
743            confidence_milli: 500,
744        }
745    }
746
747    #[test]
748    fn task_aware_filter_can_be_disabled() {
749        let output = "TASK: test\n\n## Unrelated\nwidget catalog\n";
750        assert_eq!(
751            apply_task_aware_filter(
752                output,
753                "target query",
754                &profile("bug_fix", "fix filtering", 700),
755                false
756            ),
757            output
758        );
759    }
760
761    use super::{project_dependencies, project_utility_files};
762
763    #[test]
764    fn detects_root_manifest_dependencies() {
765        let root = tempfile::tempdir().expect("tempdir");
766        std::fs::write(
767            root.path().join("Cargo.toml"),
768            "[dependencies]\ntokio = \"1\"\nserde = { version = \"1\" }\n",
769        )
770        .expect("Cargo.toml");
771        std::fs::write(
772            root.path().join("package.json"),
773            r#"{"dependencies":{"react":"1","zod":"1"},"devDependencies":{"vitest":"1"}}"#,
774        )
775        .expect("package.json");
776        std::fs::write(
777            root.path().join("requirements.txt"),
778            "requests>=2\nrich[markdown]==1\n# comment\n",
779        )
780        .expect("requirements.txt");
781        std::fs::write(
782            root.path().join("go.mod"),
783            "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",
784        )
785        .expect("go.mod");
786
787        assert_eq!(
788            project_dependencies(root.path()),
789            vec![
790                "tokio".to_string(),
791                "serde".to_string(),
792                "react".to_string(),
793                "zod".to_string(),
794                "vitest".to_string(),
795                "requests".to_string(),
796                "rich".to_string(),
797                "github.com/gin-gonic/gin".to_string(),
798                "golang.org/x/crypto".to_string(),
799            ]
800        );
801    }
802
803    #[test]
804    fn task_aware_filter_uses_the_call_task_over_session_profile() {
805        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";
806        let filtered = apply_task_aware_filter(
807            output,
808            "renew oauth token",
809            &profile("maintenance", "routine", 700),
810            true,
811        );
812
813        assert!(filtered.contains("## Query A"));
814        assert!(filtered.contains("## Query B"));
815        assert!(!filtered.contains("## Session profile"));
816    }
817
818    #[test]
819    fn task_aware_filter_downweights_stop_words() {
820        let output =
821            "TASK: test\n\n## Generic\nhow to do this\n\n## Parser\nupdate parser properly\n";
822        let filtered = apply_task_aware_filter(
823            output,
824            "how to update the parser properly",
825            &profile("maintenance", "routine", 700),
826            true,
827        );
828
829        assert!(filtered.contains("## Parser"));
830        assert!(!filtered.contains("## Generic"));
831    }
832
833    #[test]
834    fn task_aware_filter_uses_top_k_then_diverse_coverage() {
835        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";
836        let filtered = apply_task_aware_filter(
837            output,
838            "cache storage retries metrics",
839            &profile("cache", "storage retries metrics", 700),
840            true,
841        );
842
843        assert!(filtered.contains("## A"));
844        assert!(filtered.contains("## B"));
845        assert!(filtered.contains("## C"));
846        assert!(!filtered.contains("## D"));
847    }
848
849    #[test]
850    fn task_aware_filter_leaves_triage_to_the_global_pipeline() {
851        let output = format!(
852            "TASK: test\n\n## Relevant\nfix context gate\n{}// TODO: keep this\n",
853            "// boilerplate\n".repeat(40)
854        );
855        let filtered = apply_task_aware_filter(
856            &output,
857            "fix context gate",
858            &profile("bug_fix", "fix context gate filtering", 450),
859            true,
860        );
861        assert!(filtered.contains("## Relevant"));
862        assert!(filtered.contains("// TODO: keep this"));
863        assert!(filtered.contains("// boilerplate"));
864        assert!(!filtered.contains("filtered by triage"));
865    }
866
867    #[test]
868    fn finds_files_in_root_utility_directories() {
869        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
870        let root = tempfile::tempdir().expect("tempdir");
871        std::fs::create_dir_all(root.path().join("utils/nested")).expect("utils directory");
872        std::fs::create_dir_all(root.path().join("helpers")).expect("helpers directory");
873        std::fs::create_dir_all(root.path().join("common")).expect("common directory");
874        for file in [
875            "utils/nested/time.rs",
876            "helpers/format.ts",
877            "common/model.py",
878        ] {
879            std::fs::write(root.path().join(file), "").expect("utility file");
880        }
881
882        assert_eq!(
883            project_utility_files(root.path()),
884            vec![
885                "common/model.py".to_string(),
886                "helpers/format.ts".to_string(),
887                "utils/nested/time.rs".to_string(),
888            ]
889        );
890    }
891
892    #[test]
893    fn community_utility_names_obey_secret_path_role_admission() {
894        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
895        let root = tempfile::tempdir().unwrap();
896        std::fs::create_dir(root.path().join("helpers")).unwrap();
897        std::fs::write(root.path().join("helpers/id_rsa"), "private key fixture").unwrap();
898        std::fs::write(root.path().join("helpers/allowed.rs"), "fn allowed() {}\n").unwrap();
899        let mut role = crate::core::roles::load_role("coder").unwrap();
900        role.io.allow_secret_paths = false;
901        crate::core::roles::with_test_active_role(role, || {
902            assert_eq!(
903                project_utility_files(root.path()),
904                vec!["helpers/allowed.rs"]
905            );
906        });
907    }
908}