Skip to main content

lean_ctx_ext/core/
profile_suggest.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Repo-stack-aware profile recommendation (#851).
3//!
4//! Powers `lean-ctx profile suggest`: scan the current repo for deterministic
5//! signals (languages, source-file count, monorepo layout, build/CI markers,
6//! configured LLM providers) and recommend a context profile plus a few key
7//! settings (`history_mode`, output density, `effort`).
8//!
9//! Strictly **read-only and local-only**: it prints a suggestion and the exact
10//! commands to apply it, and never writes config. All signals come from the
11//! filesystem + local config/env, so the output is a deterministic function of
12//! the repo and environment (no network, no telemetry).
13//!
14//! Reuses existing detectors rather than reinventing them:
15//! [`language_for_ext`] for language classification and
16//! [`crate::core::pathutil::has_multi_repo_children`] for the monorepo check.
17//! The pure mapping ([`suggest`]) is separated from the I/O scan ([`analyze`])
18//! so the heuristic is unit-tested without touching disk.
19
20use std::collections::BTreeMap;
21use std::path::Path;
22
23use crate::core::config::Config;
24use crate::core::language_capabilities::language_for_ext;
25
26/// A repo is "large" past this many indexed source files (favors broad context).
27const LARGE_REPO_FILES: usize = 2000;
28/// A repo is "small" at or below this many source files (a focused default fits).
29const SMALL_REPO_FILES: usize = 60;
30/// This many distinct languages counts as polyglot (favors broad context).
31const POLYGLOT_LANGS: usize = 4;
32/// Hard cap on files visited during the scan, so `suggest` stays fast on huge trees.
33const MAX_WALK_FILES: usize = 50_000;
34
35/// Files counted for one language. Serialized for `--json`.
36#[derive(Debug, Clone, serde::Serialize)]
37pub struct LanguageCount {
38    pub language: String,
39    pub files: usize,
40}
41
42/// Deterministic, locally-detected signals about the repo + environment.
43#[derive(Debug, Clone, serde::Serialize)]
44pub struct RepoSignals {
45    pub root: String,
46    pub source_files: usize,
47    pub languages: Vec<LanguageCount>,
48    pub monorepo: bool,
49    pub workspace_markers: Vec<String>,
50    pub build_markers: Vec<String>,
51    pub ci: bool,
52    pub providers: Vec<String>,
53    pub proxy_enabled: bool,
54}
55
56/// Key settings the suggestion recommends alongside the profile.
57#[derive(Debug, Clone, serde::Serialize)]
58pub struct RecommendedSettings {
59    /// `proxy.history_mode` — `None` ⇒ leave the default untouched.
60    pub history_mode: Option<String>,
61    /// `output_density`.
62    pub output_density: String,
63    /// `proxy.effort` — `None` ⇒ leave off (opt-in; never inferred from a repo).
64    pub effort: Option<String>,
65}
66
67/// A task-oriented profile the user can switch to, with the situation it fits.
68#[derive(Debug, Clone, serde::Serialize)]
69pub struct ProfileAlternative {
70    pub profile: String,
71    pub when: String,
72}
73
74/// The full recommendation: a primary profile, why, the settings, and
75/// task-oriented alternatives.
76#[derive(Debug, Clone, serde::Serialize)]
77pub struct Suggestion {
78    pub profile: String,
79    pub rationale: Vec<String>,
80    pub settings: RecommendedSettings,
81    pub alternatives: Vec<ProfileAlternative>,
82}
83
84/// Scans `root` and collects [`RepoSignals`]. Respects `.gitignore` (so vendored
85/// / build dirs don't skew the language mix) and is bounded by `MAX_WALK_FILES`.
86#[must_use]
87pub fn analyze(root: &str) -> RepoSignals {
88    let root_path = Path::new(root);
89
90    let mut lang_counts: BTreeMap<&'static str, usize> = BTreeMap::new();
91    let mut source_files = 0usize;
92
93    for entry in ignore::WalkBuilder::new(root_path)
94        .standard_filters(true)
95        .build()
96        .flatten()
97    {
98        if source_files >= MAX_WALK_FILES {
99            break;
100        }
101        if !entry.file_type().is_some_and(|t| t.is_file()) {
102            continue;
103        }
104        let Some(ext) = entry.path().extension().and_then(|e| e.to_str()) else {
105            continue;
106        };
107        if let Some(lang) = language_for_ext(ext) {
108            *lang_counts.entry(lang.id_str()).or_insert(0) += 1;
109            source_files += 1;
110        }
111    }
112
113    let mut languages: Vec<LanguageCount> = lang_counts
114        .into_iter()
115        .map(|(language, files)| LanguageCount {
116            language: language.to_string(),
117            files,
118        })
119        .collect();
120    // Stable order: most files first, ties broken by name.
121    languages.sort_by(|a, b| {
122        b.files
123            .cmp(&a.files)
124            .then_with(|| a.language.cmp(&b.language))
125    });
126
127    let workspace_markers = detect_workspace_markers(root_path);
128    let monorepo =
129        !workspace_markers.is_empty() || crate::core::pathutil::has_multi_repo_children(root_path);
130
131    let build_markers = detect_build_markers(root_path);
132    let ci = root_path.join(".github/workflows").is_dir()
133        || root_path.join(".gitlab-ci.yml").is_file()
134        || root_path.join(".circleci").is_dir()
135        || root_path.join("azure-pipelines.yml").is_file();
136
137    let cfg = Config::load();
138    let providers = detect_providers(&cfg);
139    let proxy_enabled = cfg.proxy_enabled.unwrap_or(false);
140
141    RepoSignals {
142        root: root.to_string(),
143        source_files,
144        languages,
145        monorepo,
146        workspace_markers,
147        build_markers,
148        ci,
149        providers,
150        proxy_enabled,
151    }
152}
153
154/// Maps signals to a recommendation. Pure and deterministic (no I/O), so the
155/// heuristic is fully unit-tested.
156#[must_use]
157pub fn suggest(signals: &RepoSignals) -> Suggestion {
158    let polyglot = signals.languages.len() >= POLYGLOT_LANGS;
159    let large = signals.source_files >= LARGE_REPO_FILES;
160    let small = signals.source_files <= SMALL_REPO_FILES;
161
162    let mut rationale = Vec::new();
163
164    let profile = if signals.monorepo {
165        rationale.push("monorepo layout → broad cross-package context".to_string());
166        "exploration"
167    } else if large {
168        rationale.push(format!(
169            "large repo ({} source files) → wider, map-first context",
170            signals.source_files
171        ));
172        "exploration"
173    } else if polyglot {
174        rationale.push(format!(
175            "polyglot ({} languages) → wider context to span stacks",
176            signals.languages.len()
177        ));
178        "exploration"
179    } else if small {
180        rationale.push(format!(
181            "small repo ({} source files) → a focused default is enough",
182            signals.source_files
183        ));
184        "coder"
185    } else {
186        rationale.push(format!(
187            "typical project size ({} source files) → balanced default",
188            signals.source_files
189        ));
190        "coder"
191    };
192
193    let broad = signals.monorepo || large || polyglot;
194    let output_density = if broad { "terse" } else { "normal" };
195    if broad {
196        rationale.push("dense output (terse) to fit the larger surface in budget".to_string());
197    }
198
199    let history_mode = if signals.proxy_enabled || !signals.providers.is_empty() {
200        rationale
201            .push("provider proxy active → cache-aware history (cache-stable pruning)".to_string());
202        Some("cache-aware".to_string())
203    } else {
204        None
205    };
206
207    // `effort` is a cost/latency knob with no repo signal — never inferred here.
208    let effort = None;
209
210    let mut alternatives = Vec::new();
211    if signals.ci {
212        alternatives.push(ProfileAlternative {
213            profile: "ci-debug".to_string(),
214            when: "iterating on CI / shell failures".to_string(),
215        });
216    }
217    alternatives.push(ProfileAlternative {
218        profile: "hotfix".to_string(),
219        when: "urgent one-file fix — minimal context".to_string(),
220    });
221    alternatives.push(ProfileAlternative {
222        profile: "bugfix".to_string(),
223        when: "debugging a specific issue".to_string(),
224    });
225    alternatives.push(ProfileAlternative {
226        profile: "review".to_string(),
227        when: "read-only code review".to_string(),
228    });
229
230    Suggestion {
231        profile: profile.to_string(),
232        rationale,
233        settings: RecommendedSettings {
234            history_mode,
235            output_density: output_density.to_string(),
236            effort,
237        },
238        alternatives,
239    }
240}
241
242/// Monorepo / workspace marker files at the repo root (deterministic file probes).
243fn detect_workspace_markers(root: &Path) -> Vec<String> {
244    const MARKERS: &[&str] = &[
245        "pnpm-workspace.yaml",
246        "lerna.json",
247        "nx.json",
248        "turbo.json",
249        "rush.json",
250        "go.work",
251    ];
252    let mut found: Vec<String> = MARKERS
253        .iter()
254        .filter(|m| root.join(m).exists())
255        .map(|m| (*m).to_string())
256        .collect();
257    // A Cargo workspace is expressed inside Cargo.toml rather than its own file.
258    if std::fs::read_to_string(root.join("Cargo.toml"))
259        .is_ok_and(|s| s.lines().any(|l| l.trim_start().starts_with("[workspace]")))
260    {
261        found.push("Cargo.toml [workspace]".to_string());
262    }
263    found
264}
265
266/// Build-tool markers at the repo root, de-duplicated by tool name.
267fn detect_build_markers(root: &Path) -> Vec<String> {
268    const MARKERS: &[(&str, &str)] = &[
269        ("Cargo.toml", "cargo"),
270        ("package.json", "npm"),
271        ("go.mod", "go"),
272        ("pyproject.toml", "python"),
273        ("requirements.txt", "python"),
274        ("setup.py", "python"),
275        ("pom.xml", "maven"),
276        ("build.gradle", "gradle"),
277        ("Gemfile", "bundler"),
278        ("composer.json", "composer"),
279        ("Makefile", "make"),
280        ("Dockerfile", "docker"),
281    ];
282    let mut found: Vec<String> = Vec::new();
283    for (file, name) in MARKERS {
284        if root.join(file).exists() && !found.iter().any(|f| f == name) {
285            found.push((*name).to_string());
286        }
287    }
288    found
289}
290
291/// LLM providers in use, from local config upstreams + environment API keys.
292fn detect_providers(cfg: &Config) -> Vec<String> {
293    let mut providers: Vec<String> = Vec::new();
294
295    if env_set("ANTHROPIC_API_KEY") || env_set("ANTHROPIC_AUTH_TOKEN") {
296        push_unique(&mut providers, "anthropic");
297    }
298    if env_set("OPENAI_API_KEY") {
299        push_unique(&mut providers, "openai");
300    }
301    if env_set("GEMINI_API_KEY") || env_set("GOOGLE_API_KEY") {
302        push_unique(&mut providers, "gemini");
303    }
304    if cfg.proxy.anthropic_upstream.is_some() {
305        push_unique(&mut providers, "anthropic");
306    }
307    if cfg.proxy.openai_upstream.is_some() {
308        push_unique(&mut providers, "openai");
309    }
310    if cfg.proxy.chatgpt_upstream.is_some() {
311        push_unique(&mut providers, "chatgpt");
312    }
313    if cfg.proxy.gemini_upstream.is_some() {
314        push_unique(&mut providers, "gemini");
315    }
316
317    providers.sort();
318    providers
319}
320
321fn push_unique(v: &mut Vec<String>, name: &str) {
322    if !v.iter().any(|p| p == name) {
323        v.push(name.to_string());
324    }
325}
326
327fn env_set(key: &str) -> bool {
328    std::env::var(key).is_ok_and(|v| !v.trim().is_empty())
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    fn signals(source_files: usize, langs: &[&str], monorepo: bool) -> RepoSignals {
336        RepoSignals {
337            root: "/tmp/x".to_string(),
338            source_files,
339            languages: langs
340                .iter()
341                .map(|l| LanguageCount {
342                    language: (*l).to_string(),
343                    files: 1,
344                })
345                .collect(),
346            monorepo,
347            workspace_markers: vec![],
348            build_markers: vec![],
349            ci: false,
350            providers: vec![],
351            proxy_enabled: false,
352        }
353    }
354
355    #[test]
356    fn monorepo_suggests_exploration() {
357        let s = suggest(&signals(300, &["rust", "typescript"], true));
358        assert_eq!(s.profile, "exploration");
359        assert_eq!(s.settings.output_density, "terse");
360    }
361
362    #[test]
363    fn large_repo_suggests_exploration() {
364        let s = suggest(&signals(5000, &["rust"], false));
365        assert_eq!(s.profile, "exploration");
366        assert_eq!(s.settings.output_density, "terse");
367    }
368
369    #[test]
370    fn polyglot_suggests_exploration() {
371        let s = suggest(&signals(
372            300,
373            &["rust", "go", "python", "typescript"],
374            false,
375        ));
376        assert_eq!(s.profile, "exploration");
377    }
378
379    #[test]
380    fn small_repo_suggests_coder_normal_density() {
381        let s = suggest(&signals(20, &["rust"], false));
382        assert_eq!(s.profile, "coder");
383        assert_eq!(s.settings.output_density, "normal");
384    }
385
386    #[test]
387    fn typical_repo_suggests_coder() {
388        let s = suggest(&signals(400, &["rust", "typescript"], false));
389        assert_eq!(s.profile, "coder");
390        assert_eq!(s.settings.output_density, "normal");
391    }
392
393    #[test]
394    fn effort_is_never_inferred() {
395        let s = suggest(&signals(5000, &["rust", "go", "python", "ts"], true));
396        assert!(s.settings.effort.is_none());
397    }
398
399    #[test]
400    fn history_mode_recommended_only_with_providers() {
401        let mut s = signals(400, &["rust"], false);
402        assert!(suggest(&s).settings.history_mode.is_none());
403        s.providers = vec!["anthropic".to_string()];
404        assert_eq!(
405            suggest(&s).settings.history_mode.as_deref(),
406            Some("cache-aware")
407        );
408    }
409
410    #[test]
411    fn ci_adds_ci_debug_alternative_first() {
412        let mut s = signals(400, &["rust"], false);
413        s.ci = true;
414        let out = suggest(&s);
415        assert_eq!(out.alternatives.first().unwrap().profile, "ci-debug");
416    }
417
418    #[test]
419    fn suggestion_is_deterministic() {
420        let s = signals(5000, &["rust", "go"], true);
421        let a = suggest(&s);
422        let b = suggest(&s);
423        assert_eq!(a.profile, b.profile);
424        assert_eq!(a.rationale, b.rationale);
425    }
426}