Skip to main content

lean_ctx_ext/core/
task_briefing.rs

1// SPDX-License-Identifier: Apache-2.0
2use crate::core::intent_engine::{TaskClassification, TaskType, classify};
3
4#[derive(Debug)]
5pub struct TaskBriefing {
6    pub classification: TaskClassification,
7    pub completeness_signal: CompletenessSignal,
8    pub output_instruction: &'static str,
9    pub context_hints: Vec<String>,
10    /// Lab-only: thinking instruction for direct LLM API calls.
11    /// NEVER inject into MCP tool outputs — would override user's model thinking behavior.
12    pub lab_thinking_instruction: &'static str,
13}
14
15#[derive(Debug, Clone, Copy)]
16pub enum CompletenessSignal {
17    SingleFile,
18    MultiFile,
19    CrossModule,
20    Unknown,
21}
22
23impl CompletenessSignal {
24    pub fn as_str(&self) -> &'static str {
25        match self {
26            Self::SingleFile => "SCOPE:single-file",
27            Self::MultiFile => "SCOPE:multi-file",
28            Self::CrossModule => "SCOPE:cross-module",
29            Self::Unknown => "SCOPE:unknown",
30        }
31    }
32}
33
34pub fn build_briefing(task: &str, file_context: &[(String, usize)]) -> TaskBriefing {
35    let classification = classify(task);
36
37    let completeness = estimate_completeness(&classification, file_context);
38    let context_hints = build_context_hints(&classification, file_context);
39
40    let output_instruction = classification.task_type.output_format().instruction();
41    let lab_thinking_instruction = classification.task_type.thinking_budget().instruction();
42
43    TaskBriefing {
44        classification,
45        completeness_signal: completeness,
46        output_instruction,
47        context_hints,
48        lab_thinking_instruction,
49    }
50}
51
52fn estimate_completeness(
53    classification: &TaskClassification,
54    file_context: &[(String, usize)],
55) -> CompletenessSignal {
56    if file_context.is_empty() {
57        return CompletenessSignal::Unknown;
58    }
59
60    let unique_dirs: std::collections::HashSet<&str> = file_context
61        .iter()
62        .filter_map(|(path, _)| std::path::Path::new(path).parent().and_then(|p| p.to_str()))
63        .collect();
64
65    if classification.targets.len() <= 1 && unique_dirs.len() <= 1 {
66        CompletenessSignal::SingleFile
67    } else if unique_dirs.len() <= 3 {
68        CompletenessSignal::MultiFile
69    } else {
70        CompletenessSignal::CrossModule
71    }
72}
73
74fn build_context_hints(
75    classification: &TaskClassification,
76    file_context: &[(String, usize)],
77) -> Vec<String> {
78    let mut hints = Vec::new();
79
80    match classification.task_type {
81        TaskType::Generate => {
82            hints.push("Pattern: match existing code style in context".to_string());
83            if !classification.targets.is_empty() {
84                hints.push(format!(
85                    "Insert near: {}",
86                    classification.targets.join(", ")
87                ));
88            }
89        }
90        TaskType::FixBug => {
91            hints.push("Focus: identify root cause, minimal fix".to_string());
92            if let Some(largest) = file_context.iter().max_by_key(|(_, lines)| *lines) {
93                hints.push(format!("Primary file: {} ({}L)", largest.0, largest.1));
94            }
95        }
96        TaskType::Refactor => {
97            hints.push("Preserve: all public APIs and behavior".to_string());
98            hints.push(format!("Files in scope: {}", file_context.len()));
99        }
100        TaskType::Explore => {
101            hints.push("Depth: signatures + key logic, skip boilerplate".to_string());
102        }
103        TaskType::Test => {
104            hints.push("Pattern: follow existing test patterns in codebase".to_string());
105        }
106        TaskType::Debug => {
107            hints.push("Trace: follow data flow through call chain".to_string());
108        }
109        _ => {}
110    }
111
112    hints
113}
114
115pub fn format_briefing(briefing: &TaskBriefing) -> String {
116    format_briefing_with(briefing, true)
117}
118
119/// Render a briefing, optionally without its `OUTPUT-HINT:` line (#1763).
120///
121/// The hint tells the assistant how to *format its answer*. That is a
122/// behaviour nudge, not retrieval output, so callers that surface a briefing
123/// inside a tool result gate it on the same `behavior_nudges` config key the
124/// nudge system honours — `off` must silence every answer-shaping directive,
125/// not just the ones emitted post-dispatch.
126pub fn format_briefing_with(briefing: &TaskBriefing, include_output_hint: bool) -> String {
127    let mut parts = Vec::new();
128
129    parts.push(format!(
130        "[TASK:{} {}]",
131        briefing.classification.task_type.as_str(),
132        briefing.completeness_signal.as_str(),
133    ));
134
135    if include_output_hint {
136        parts.push(briefing.output_instruction.to_string());
137    }
138
139    if !briefing.context_hints.is_empty() {
140        for hint in &briefing.context_hints {
141            parts.push(format!("• {hint}"));
142        }
143    }
144
145    parts.join("\n")
146}
147
148pub fn inject_into_instructions(base_instructions: &str, task: &str) -> String {
149    if task.trim().is_empty() {
150        return base_instructions.to_string();
151    }
152
153    let file_context: Vec<(String, usize)> = Vec::new();
154    let briefing = build_briefing(task, &file_context);
155    let briefing_block = format_briefing(&briefing);
156
157    format!("{base_instructions}\n\n{briefing_block}")
158}
159
160#[cfg(test)]
161pub mod tests {
162    use super::*;
163
164    #[test]
165    fn briefing_for_generate_task() {
166        let files = vec![("src/core/entropy.rs".to_string(), 120)];
167        let briefing = build_briefing("add normalized_token_entropy to entropy.rs", &files);
168        assert_eq!(briefing.classification.task_type, TaskType::Generate);
169        assert!(briefing.output_instruction.contains("code blocks"));
170        assert!(briefing.lab_thinking_instruction.contains("Skip analysis"));
171    }
172
173    #[test]
174    fn briefing_for_fix_bug() {
175        let files = vec![
176            ("src/core/entropy.rs".to_string(), 200),
177            ("src/core/tokens.rs".to_string(), 50),
178        ];
179        let briefing = build_briefing("fix the NaN bug in token_entropy", &files);
180        assert_eq!(briefing.classification.task_type, TaskType::FixBug);
181        assert!(briefing.output_instruction.contains("changed lines"));
182        assert!(
183            !briefing.lab_thinking_instruction.is_empty(),
184            "`briefing.lab_thinking_instruction` is empty"
185        );
186    }
187
188    #[test]
189    fn completeness_single_file() {
190        let files = vec![("src/core/entropy.rs".to_string(), 200)];
191        let briefing = build_briefing("add a function", &files);
192        matches!(briefing.completeness_signal, CompletenessSignal::SingleFile);
193    }
194
195    #[test]
196    fn completeness_cross_module() {
197        let files = vec![
198            ("src/core/a.rs".to_string(), 100),
199            ("src/tools/b.rs".to_string(), 100),
200            ("src/server.rs".to_string(), 100),
201            ("tests/integration.rs".to_string(), 100),
202        ];
203        let briefing = build_briefing("refactor compression pipeline", &files);
204        matches!(
205            briefing.completeness_signal,
206            CompletenessSignal::CrossModule
207        );
208    }
209
210    #[test]
211    fn format_briefing_includes_all_sections() {
212        let files = vec![("src/core/entropy.rs".to_string(), 120)];
213        let briefing = build_briefing("fix bug in entropy.rs", &files);
214        let formatted = format_briefing(&briefing);
215        assert!(formatted.contains("[TASK:"));
216        assert!(formatted.contains("OUTPUT-HINT:"));
217        assert!(formatted.contains("SCOPE:"));
218    }
219
220    #[test]
221    fn format_briefing_without_output_hint_keeps_classification_and_hints() {
222        // #1763: with nudges off the answer-shaping directive is dropped, but
223        // the task classification and the context hints still render.
224        let files = vec![("src/core/entropy.rs".to_string(), 120)];
225        let briefing = build_briefing("how does the entropy scorer work?", &files);
226        let quiet = format_briefing_with(&briefing, false);
227        assert!(quiet.contains("[TASK:"));
228        assert!(quiet.contains("SCOPE:"));
229        assert!(!quiet.contains("OUTPUT-HINT:"), "{quiet}");
230        assert!(
231            !briefing.context_hints.is_empty(),
232            "explore tasks carry hints"
233        );
234        for hint in &briefing.context_hints {
235            assert!(quiet.contains(hint), "hint '{hint}' must survive");
236        }
237        // The default rendering is unchanged.
238        assert_eq!(
239            format_briefing(&briefing),
240            format_briefing_with(&briefing, true)
241        );
242    }
243
244    #[test]
245    fn inject_empty_task_unchanged() {
246        let base = "some instructions";
247        let result = inject_into_instructions(base, "");
248        assert_eq!(result, base);
249    }
250
251    #[test]
252    fn briefing_covers_all_task_types() {
253        let scenarios: &[(&str, &str)] = &[
254            ("add a new function to entropy.rs", "generate"),
255            ("fix the bug in token_optimizer.rs", "fix_bug"),
256            ("how does the session cache work?", "explore"),
257            ("refactor compression pipeline", "refactor"),
258            ("write unit tests for entropy", "test"),
259            ("debug why compression ratio drops", "debug"),
260        ];
261        for &(task, expected_type) in scenarios {
262            let briefing = build_briefing(task, &[("src/main.rs".to_string(), 100)]);
263            assert_eq!(
264                briefing.classification.task_type.as_str(),
265                expected_type,
266                "Task '{task}' should be classified as '{expected_type}'",
267            );
268            let formatted = format_briefing(&briefing);
269            assert!(formatted.contains("[TASK:"));
270            assert!(formatted.contains("OUTPUT-HINT:"));
271        }
272    }
273}