Skip to main content

lean_ctx_ext/core/
context_deficit.rs

1// SPDX-License-Identifier: Apache-2.0
2use super::context_field::ContextItemId;
3use super::context_ledger::{ContextLedger, PressureAction};
4use super::intent_engine::{IntentScope, StructuredIntent, TaskType};
5
6#[derive(Debug, Clone)]
7pub struct ContextDeficit {
8    pub missing_targets: Vec<String>,
9    pub suggested_files: Vec<SuggestedFile>,
10    pub pressure_action: PressureAction,
11    pub budget_remaining: usize,
12}
13
14#[derive(Debug, Clone)]
15pub struct SuggestedFile {
16    pub path: String,
17    pub item_id: ContextItemId,
18    pub reason: DeficitReason,
19    pub estimated_tokens: usize,
20    pub recommended_mode: String,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum DeficitReason {
25    TargetNotLoaded,
26    DependencyOfTarget,
27    TestFileForTarget,
28    ConfigForTask,
29}
30
31impl DeficitReason {
32    fn priority(&self) -> u8 {
33        match self {
34            Self::TargetNotLoaded => 0,
35            Self::DependencyOfTarget => 1,
36            Self::TestFileForTarget => 2,
37            Self::ConfigForTask => 3,
38        }
39    }
40}
41
42pub fn detect_deficit(
43    ledger: &ContextLedger,
44    intent: &StructuredIntent,
45    known_files: &[String],
46) -> ContextDeficit {
47    let loaded_paths: Vec<&str> = ledger.entries.iter().map(|e| e.path.as_str()).collect();
48    let pressure = ledger.pressure();
49
50    let mut missing_targets = Vec::new();
51    let mut suggestions = Vec::new();
52
53    for target in &intent.targets {
54        if target.contains('.') || target.contains('/') {
55            let is_loaded = loaded_paths
56                .iter()
57                .any(|p| p.ends_with(target) || p.contains(target));
58            if !is_loaded {
59                missing_targets.push(target.clone());
60
61                let matching: Vec<&String> = known_files
62                    .iter()
63                    .filter(|f| f.ends_with(target) || f.contains(target))
64                    .collect();
65
66                for file in matching {
67                    let mode = mode_for_pressure(&pressure.recommendation, &intent.scope);
68                    suggestions.push(SuggestedFile {
69                        path: file.clone(),
70                        item_id: ContextItemId::from_file(file),
71                        reason: DeficitReason::TargetNotLoaded,
72                        estimated_tokens: estimate_tokens_for_mode(&mode),
73                        recommended_mode: mode,
74                    });
75                }
76            }
77        }
78    }
79
80    if intent.task_type == TaskType::FixBug || intent.task_type == TaskType::Test {
81        for target in &intent.targets {
82            if target.contains('.') || target.contains('/') {
83                let test_patterns = derive_test_paths(target);
84                for test_path in &test_patterns {
85                    let matching: Vec<&String> = known_files
86                        .iter()
87                        .filter(|f| f.contains(test_path))
88                        .collect();
89                    for file in matching {
90                        if !loaded_paths.contains(&file.as_str())
91                            && !suggestions.iter().any(|s| s.path == *file)
92                        {
93                            let mode = mode_for_pressure(&pressure.recommendation, &intent.scope);
94                            suggestions.push(SuggestedFile {
95                                path: file.clone(),
96                                item_id: ContextItemId::from_file(file),
97                                reason: DeficitReason::TestFileForTarget,
98                                estimated_tokens: estimate_tokens_for_mode(&mode),
99                                recommended_mode: mode,
100                            });
101                        }
102                    }
103                }
104            }
105        }
106    }
107
108    if intent.task_type == TaskType::Config || intent.task_type == TaskType::Deploy {
109        let config_patterns = [
110            "Cargo.toml",
111            "package.json",
112            "tsconfig.json",
113            "pyproject.toml",
114            ".env",
115            "Dockerfile",
116        ];
117        for pattern in &config_patterns {
118            let matching: Vec<&String> = known_files
119                .iter()
120                .filter(|f| f.ends_with(pattern))
121                .collect();
122            for file in matching {
123                if !loaded_paths.contains(&file.as_str())
124                    && !suggestions.iter().any(|s| s.path == *file)
125                {
126                    suggestions.push(SuggestedFile {
127                        path: file.clone(),
128                        item_id: ContextItemId::from_file(file),
129                        reason: DeficitReason::ConfigForTask,
130                        estimated_tokens: estimate_tokens_for_mode("full"),
131                        recommended_mode: "full".to_string(),
132                    });
133                }
134            }
135        }
136    }
137
138    suggestions.sort_by_key(|s| s.reason.priority());
139
140    let budget_remaining = pressure.remaining_tokens;
141    let mut cumulative = 0usize;
142    suggestions.retain(|s| {
143        cumulative += s.estimated_tokens;
144        cumulative <= budget_remaining
145    });
146
147    ContextDeficit {
148        missing_targets,
149        suggested_files: suggestions,
150        pressure_action: pressure.recommendation,
151        budget_remaining,
152    }
153}
154
155fn mode_for_pressure(action: &PressureAction, scope: &IntentScope) -> String {
156    match action {
157        PressureAction::EvictLeastRelevant => "reference".to_string(),
158        PressureAction::ForceCompression => "signatures".to_string(),
159        PressureAction::SuggestCompression => match scope {
160            IntentScope::SingleFile => "full".to_string(),
161            IntentScope::MultiFile => "signatures".to_string(),
162            IntentScope::CrossModule | IntentScope::ProjectWide => "map".to_string(),
163        },
164        PressureAction::NoAction => match scope {
165            IntentScope::SingleFile | IntentScope::MultiFile => "full".to_string(),
166            IntentScope::CrossModule => "signatures".to_string(),
167            IntentScope::ProjectWide => "map".to_string(),
168        },
169    }
170}
171
172fn estimate_tokens_for_mode(mode: &str) -> usize {
173    match mode {
174        "full" => 2000,
175        "signatures" => 400,
176        "map" => 200,
177        "reference" => 50,
178        "aggressive" => 800,
179        _ => 1000,
180    }
181}
182
183fn derive_test_paths(file_path: &str) -> Vec<String> {
184    let stem = std::path::Path::new(file_path)
185        .file_stem()
186        .and_then(|s| s.to_str())
187        .unwrap_or("");
188    if stem.is_empty() {
189        return Vec::new();
190    }
191    vec![
192        format!("{stem}_test"),
193        format!("test_{stem}"),
194        format!("{stem}.test"),
195        format!("{stem}.spec"),
196        format!("{stem}_spec"),
197    ]
198}
199
200#[cfg(test)]
201pub mod tests {
202    use super::*;
203
204    #[test]
205    fn detects_missing_target() {
206        let ledger = ContextLedger::new();
207        let intent = StructuredIntent::from_query("fix bug in auth.rs");
208        let known = vec!["src/auth.rs".to_string(), "src/db.rs".to_string()];
209        let deficit = detect_deficit(&ledger, &intent, &known);
210        assert!(
211            !deficit.missing_targets.is_empty(),
212            "`deficit.missing_targets` is empty"
213        );
214        assert!(
215            deficit
216                .suggested_files
217                .iter()
218                .any(|s| s.path.contains("auth"))
219        );
220    }
221
222    #[test]
223    fn no_deficit_when_loaded() {
224        let mut ledger = ContextLedger::new();
225        ledger.record("src/auth.rs", "full", 500, 500);
226        let intent = StructuredIntent::from_query("fix bug in auth.rs");
227        let known = vec!["src/auth.rs".to_string()];
228        let deficit = detect_deficit(&ledger, &intent, &known);
229        assert!(
230            deficit.missing_targets.is_empty(),
231            "{:?}",
232            deficit.missing_targets
233        );
234    }
235
236    #[test]
237    fn suggests_test_files_for_fixbug() {
238        let mut ledger = ContextLedger::new();
239        ledger.record("src/auth.rs", "full", 500, 500);
240        let intent = StructuredIntent::from_query("fix bug in auth.rs");
241        let known = vec!["src/auth.rs".to_string(), "tests/auth_test.rs".to_string()];
242        let deficit = detect_deficit(&ledger, &intent, &known);
243        let test_suggestions: Vec<_> = deficit
244            .suggested_files
245            .iter()
246            .filter(|s| s.reason == DeficitReason::TestFileForTarget)
247            .collect();
248        assert!(
249            !test_suggestions.is_empty(),
250            "should suggest test files for FixBug"
251        );
252    }
253
254    #[test]
255    fn respects_budget() {
256        let mut ledger = ContextLedger::with_window_size(1000);
257        ledger.record("existing.rs", "full", 900, 900);
258        let intent = StructuredIntent::from_query("fix bug in big_file.rs");
259        let known = vec!["src/big_file.rs".to_string()];
260        let deficit = detect_deficit(&ledger, &intent, &known);
261        assert!(
262            deficit.suggested_files.is_empty() || deficit.budget_remaining < 200,
263            "should respect budget constraints"
264        );
265    }
266
267    #[test]
268    fn config_task_suggests_config_files() {
269        let ledger = ContextLedger::new();
270        let intent = StructuredIntent::from_query("configure env settings for the project");
271        let known = vec![
272            "src/main.rs".to_string(),
273            "Cargo.toml".to_string(),
274            "package.json".to_string(),
275        ];
276        let deficit = detect_deficit(&ledger, &intent, &known);
277        let config_suggestions: Vec<_> = deficit
278            .suggested_files
279            .iter()
280            .filter(|s| s.reason == DeficitReason::ConfigForTask)
281            .collect();
282        assert!(!config_suggestions.is_empty());
283    }
284
285    #[test]
286    fn mode_adapts_to_pressure() {
287        let mode_low = mode_for_pressure(&PressureAction::NoAction, &IntentScope::SingleFile);
288        let mode_high = mode_for_pressure(
289            &PressureAction::EvictLeastRelevant,
290            &IntentScope::SingleFile,
291        );
292        assert_eq!(mode_low, "full");
293        assert_eq!(mode_high, "reference");
294    }
295
296    #[test]
297    fn derive_test_paths_generates_variants() {
298        let paths = derive_test_paths("src/auth.rs");
299        assert!(paths.contains(&"auth_test".to_string()));
300        assert!(paths.contains(&"test_auth".to_string()));
301        assert!(paths.contains(&"auth.test".to_string()));
302        assert!(paths.contains(&"auth.spec".to_string()));
303    }
304}