1use std::collections::BTreeMap;
21use std::path::Path;
22
23use crate::core::config::Config;
24use crate::core::language_capabilities::language_for_ext;
25
26const LARGE_REPO_FILES: usize = 2000;
28const SMALL_REPO_FILES: usize = 60;
30const POLYGLOT_LANGS: usize = 4;
32const MAX_WALK_FILES: usize = 50_000;
34
35#[derive(Debug, Clone, serde::Serialize)]
37pub struct LanguageCount {
38 pub language: String,
39 pub files: usize,
40}
41
42#[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#[derive(Debug, Clone, serde::Serialize)]
58pub struct RecommendedSettings {
59 pub history_mode: Option<String>,
61 pub output_density: String,
63 pub effort: Option<String>,
65}
66
67#[derive(Debug, Clone, serde::Serialize)]
69pub struct ProfileAlternative {
70 pub profile: String,
71 pub when: String,
72}
73
74#[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#[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 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#[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 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
242fn 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 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
266fn 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
291fn 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}