Skip to main content

vtcode_core/commands/init/
mod.rs

1//! Guided `/init` support for repository analysis and `AGENTS.md` generation.
2
3use anyhow::{Context, Result};
4use indexmap::IndexMap;
5use serde::{Deserialize, Serialize};
6use serde_json::Value as JsonValue;
7use std::collections::{BTreeMap, BTreeSet};
8use std::fs;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11use vtcode_commons::walk::{build_default_walker, is_excluded_dir};
12
13mod analysis;
14use analysis::analyze_project;
15
16const AGENTS_FILENAME: &str = "AGENTS.md";
17const MAX_SCAN_DEPTH: usize = 4;
18const MAX_FILE_BYTES: usize = 64 * 1024;
19const CLEAR_SCORE_GAP: u32 = 3;
20const CONTROL_GENERIC: &str = "__generic__";
21const CONTROL_NONE: &str = "__none__";
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24enum PackageManager {
25    Npm,
26    Pnpm,
27    Yarn,
28    Bun,
29}
30
31impl PackageManager {
32    fn command(self) -> &'static str {
33        match self {
34            Self::Npm => "npm",
35            Self::Pnpm => "pnpm",
36            Self::Yarn => "yarn",
37            Self::Bun => "bun",
38        }
39    }
40}
41
42#[derive(Debug, Clone)]
43struct SignalCandidate {
44    value: String,
45    label: String,
46    description: String,
47    score: u32,
48}
49
50#[derive(Debug, Default)]
51struct CandidateAccumulator {
52    values: BTreeMap<String, SignalCandidate>,
53}
54
55impl CandidateAccumulator {
56    fn add(&mut self, value: impl Into<String>, label: impl Into<String>, description: impl Into<String>, score: u32) {
57        let value = value.into();
58        let normalized = value.trim();
59        if normalized.is_empty() {
60            return;
61        }
62
63        let label = label.into();
64        let description = description.into();
65        let entry = self.values.entry(normalized.to_owned()).or_insert_with(|| SignalCandidate {
66            value: normalized.to_owned(),
67            label,
68            description,
69            score: 0,
70        });
71
72        entry.score += score;
73    }
74
75    fn into_sorted(self) -> Vec<SignalCandidate> {
76        let mut values: Vec<_> = self.values.into_values().collect();
77        values.sort_by(|left, right| right.score.cmp(&left.score).then_with(|| left.value.cmp(&right.value)));
78        values
79    }
80}
81
82#[derive(Debug, Clone)]
83struct ProjectAnalysis {
84    project_name: String,
85    grounded_project_summary: Option<String>,
86    languages: Vec<String>,
87    build_systems: Vec<String>,
88    scripts: Vec<String>,
89    dependencies: IndexMap<String, Vec<String>>,
90    source_dirs: Vec<String>,
91    config_files: Vec<String>,
92    documentation_files: Vec<String>,
93    commit_patterns: Vec<String>,
94    has_git_history: bool,
95    is_library: bool,
96    is_application: bool,
97    has_ci_cd: bool,
98    has_docker: bool,
99    package_manager: Option<PackageManager>,
100    verification_candidates: Vec<SignalCandidate>,
101    orientation_candidates: Vec<SignalCandidate>,
102    critical_instruction_candidates: Vec<SignalCandidate>,
103    selected_verification_command: Option<String>,
104    selected_orientation_doc: Option<String>,
105    selected_critical_instruction: Option<String>,
106    grounded_verification_command: Option<String>,
107    grounded_orientation_doc: Option<String>,
108    grounded_critical_instruction: Option<String>,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum GenerateAgentsFileStatus {
113    Created,
114    Overwritten,
115    SkippedExisting,
116}
117
118#[derive(Debug, Clone)]
119pub struct GenerateAgentsFileReport {
120    pub path: PathBuf,
121    pub status: GenerateAgentsFileStatus,
122}
123
124#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
125pub struct GuidedInitGrounding {
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub project_summary: Option<String>,
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub verification_command: Option<String>,
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub orientation_doc: Option<String>,
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub critical_instruction: Option<String>,
134}
135
136impl GuidedInitGrounding {
137    #[must_use]
138    pub fn has_any(&self) -> bool {
139        self.project_summary.is_some()
140            || self.verification_command.is_some()
141            || self.orientation_doc.is_some()
142            || self.critical_instruction.is_some()
143    }
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
147pub enum GuidedInitQuestionKey {
148    VerificationCommand,
149    OrientationDoc,
150    CriticalInstruction,
151}
152
153impl GuidedInitQuestionKey {
154    pub fn as_str(self) -> &'static str {
155        match self {
156            Self::VerificationCommand => "verification_command",
157            Self::OrientationDoc => "orientation_doc",
158            Self::CriticalInstruction => "critical_instruction",
159        }
160    }
161
162    pub fn header(self) -> &'static str {
163        match self {
164            Self::VerificationCommand => "Verify",
165            Self::OrientationDoc => "Orient",
166            Self::CriticalInstruction => "Rule",
167        }
168    }
169
170    pub fn custom_label(self) -> &'static str {
171        match self {
172            Self::VerificationCommand => "Custom command",
173            Self::OrientationDoc => "Custom path",
174            Self::CriticalInstruction => "Custom instruction",
175        }
176    }
177
178    pub fn custom_placeholder(self) -> &'static str {
179        match self {
180            Self::VerificationCommand => "cargo nextest run",
181            Self::OrientationDoc => "AGENTS.md",
182            Self::CriticalInstruction => "State the one rule agents should always follow",
183        }
184    }
185
186    fn blank_custom_value(self) -> &'static str {
187        match self {
188            Self::CriticalInstruction => CONTROL_NONE,
189            Self::VerificationCommand | Self::OrientationDoc => CONTROL_GENERIC,
190        }
191    }
192}
193
194impl std::str::FromStr for GuidedInitQuestionKey {
195    type Err = anyhow::Error;
196
197    fn from_str(value: &str) -> Result<Self> {
198        match value {
199            "verification_command" => Ok(Self::VerificationCommand),
200            "orientation_doc" => Ok(Self::OrientationDoc),
201            "critical_instruction" => Ok(Self::CriticalInstruction),
202            other => anyhow::bail!("unknown guided init question key: {other}"),
203        }
204    }
205}
206
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct GuidedInitQuestionOption {
209    pub value: String,
210    pub label: String,
211    pub description: String,
212    pub recommended: bool,
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct GuidedInitQuestion {
217    pub key: GuidedInitQuestionKey,
218    pub header: String,
219    pub prompt: String,
220    pub options: Vec<GuidedInitQuestionOption>,
221    pub allow_custom: bool,
222}
223
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct GuidedInitAnswer {
226    pub key: GuidedInitQuestionKey,
227    pub selected: String,
228    pub custom: Option<String>,
229}
230
231impl GuidedInitAnswer {
232    pub fn from_input(key: GuidedInitQuestionKey, selected: Option<&str>, custom: Option<&str>) -> Option<Self> {
233        let custom_selected = custom.is_some();
234        if let Some(custom) = custom.map(str::trim).filter(|value| !value.is_empty()) {
235            return Some(Self {
236                key,
237                selected: String::new(),
238                custom: Some(custom.to_owned()),
239            });
240        }
241
242        if let Some(selected) = selected.map(str::trim).filter(|value| !value.is_empty()) {
243            return Some(Self { key, selected: selected.to_owned(), custom: None });
244        }
245
246        custom_selected.then(|| Self {
247            key,
248            selected: key.blank_custom_value().to_owned(),
249            custom: None,
250        })
251    }
252}
253
254#[derive(Debug, Clone, Default, PartialEq, Eq)]
255pub struct GuidedInitAnswers {
256    answers: BTreeMap<GuidedInitQuestionKey, GuidedInitAnswer>,
257}
258
259impl GuidedInitAnswers {
260    pub fn insert(&mut self, answer: GuidedInitAnswer) {
261        self.answers.insert(answer.key, answer);
262    }
263
264    pub fn answer(&self, key: GuidedInitQuestionKey) -> Option<&GuidedInitAnswer> {
265        self.answers.get(&key)
266    }
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270pub enum GuidedInitOverwriteState {
271    Skip,
272    Confirm,
273    Force,
274}
275
276impl GuidedInitOverwriteState {
277    pub fn requires_confirmation(self) -> bool {
278        matches!(self, Self::Confirm)
279    }
280}
281
282#[derive(Debug, Clone)]
283pub struct GuidedInitPlan {
284    pub path: PathBuf,
285    pub questions: Vec<GuidedInitQuestion>,
286    pub overwrite_state: GuidedInitOverwriteState,
287    analysis: ProjectAnalysis,
288}
289
290impl GuidedInitPlan {
291    #[must_use]
292    pub fn with_grounding(mut self, grounding: GuidedInitGrounding) -> Self {
293        if !grounding.has_any() {
294            return self;
295        }
296
297        self.analysis.apply_grounding(grounding);
298        self.questions = build_guided_questions(&self.analysis);
299        self
300    }
301}
302
303pub fn prepare_guided_init(workspace: &Path, force: bool) -> Result<GuidedInitPlan> {
304    let analysis = analyze_project(workspace)?;
305    let path = workspace.join(AGENTS_FILENAME);
306    let overwrite_state = if force {
307        GuidedInitOverwriteState::Force
308    } else if path.exists() {
309        GuidedInitOverwriteState::Confirm
310    } else {
311        GuidedInitOverwriteState::Skip
312    };
313
314    Ok(GuidedInitPlan {
315        path,
316        questions: build_guided_questions(&analysis),
317        overwrite_state,
318        analysis,
319    })
320}
321
322pub fn render_agents_md(plan: &GuidedInitPlan, answers: &GuidedInitAnswers) -> Result<String> {
323    let analysis = &plan.analysis;
324    let verification_command = resolve_verification_command(analysis, answers);
325    let orientation_doc = resolve_orientation_doc(analysis, answers);
326    let critical_instruction = resolve_critical_instruction(analysis, answers);
327
328    let mut content = String::new();
329    content.push_str("# AGENTS.md\n\n");
330    content.push_str(&build_quick_start_section(analysis, verification_command.as_deref()));
331    content.push_str(&build_architecture_section(analysis, orientation_doc.as_deref()));
332    if let Some(section) = build_important_instructions_section(critical_instruction.as_deref()) {
333        content.push_str(&section);
334    }
335    content.push_str(&build_code_style_section(analysis));
336    content.push_str(&build_testing_section(analysis, verification_command.as_deref()));
337    content.push_str(&build_performance_section());
338    if let Some(section) = build_pr_guidelines_section(analysis) {
339        content.push_str(&section);
340    }
341    if let Some(section) = build_additional_guidance_section(analysis, orientation_doc.as_deref()) {
342        content.push_str(&section);
343    }
344
345    Ok(content)
346}
347
348pub fn write_agents_file(workspace: &Path, content: &str, overwrite: bool) -> Result<GenerateAgentsFileReport> {
349    let path = workspace.join(AGENTS_FILENAME);
350    let existed_before = path.exists();
351
352    if existed_before && !overwrite {
353        return Ok(GenerateAgentsFileReport {
354            path,
355            status: GenerateAgentsFileStatus::SkippedExisting,
356        });
357    }
358
359    fs::write(&path, content).with_context(|| format!("failed to write AGENTS.md to {}", path.display()))?;
360
361    let status = if existed_before {
362        GenerateAgentsFileStatus::Overwritten
363    } else {
364        GenerateAgentsFileStatus::Created
365    };
366
367    Ok(GenerateAgentsFileReport { path, status })
368}
369
370fn build_guided_questions(analysis: &ProjectAnalysis) -> Vec<GuidedInitQuestion> {
371    let mut questions = Vec::new();
372
373    let verification_needs_question = analysis.selected_verification_command.is_none()
374        || grounded_differs_from_selected(
375            analysis.selected_verification_command.as_deref(),
376            analysis.grounded_verification_command.as_deref(),
377        );
378    if verification_needs_question {
379        let options = build_guided_options(
380            analysis.grounded_verification_command.as_deref(),
381            "Use the explorer-grounded verification command.",
382            &analysis.verification_candidates,
383            Some(GuidedInitQuestionOption {
384                value: CONTROL_GENERIC.to_owned(),
385                label: "Keep generic guidance".to_owned(),
386                description: "Leave verification instructions generic for now.".to_owned(),
387                recommended: analysis.verification_candidates.is_empty()
388                    && analysis.grounded_verification_command.is_none(),
389            }),
390            3,
391        );
392        questions.push(GuidedInitQuestion {
393            key: GuidedInitQuestionKey::VerificationCommand,
394            header: GuidedInitQuestionKey::VerificationCommand.header().to_owned(),
395            prompt: "Which command should agents run by default before claiming the work is done?".to_owned(),
396            options,
397            allow_custom: true,
398        });
399    }
400
401    let orientation_needs_question = analysis.selected_orientation_doc.is_none()
402        || grounded_differs_from_selected(
403            analysis.selected_orientation_doc.as_deref(),
404            analysis.grounded_orientation_doc.as_deref(),
405        );
406    if orientation_needs_question {
407        let options = build_guided_options(
408            analysis.grounded_orientation_doc.as_deref(),
409            "Use the explorer-grounded orientation doc.",
410            &analysis.orientation_candidates,
411            Some(GuidedInitQuestionOption {
412                value: CONTROL_GENERIC.to_owned(),
413                label: "Keep generic orientation".to_owned(),
414                description: "Avoid pinning one doc as the first read.".to_owned(),
415                recommended: analysis.orientation_candidates.is_empty() && analysis.grounded_orientation_doc.is_none(),
416            }),
417            3,
418        );
419        questions.push(GuidedInitQuestion {
420            key: GuidedInitQuestionKey::OrientationDoc,
421            header: GuidedInitQuestionKey::OrientationDoc.header().to_owned(),
422            prompt: "Which file should agents read first when they need repo orientation?".to_owned(),
423            options,
424            allow_custom: true,
425        });
426    }
427
428    let critical_needs_question = (analysis.selected_critical_instruction.is_none()
429        && (!analysis.critical_instruction_candidates.is_empty() || analysis.grounded_critical_instruction.is_some()))
430        || grounded_differs_from_selected(
431            analysis.selected_critical_instruction.as_deref(),
432            analysis.grounded_critical_instruction.as_deref(),
433        );
434    if critical_needs_question {
435        let options = build_guided_options(
436            analysis.grounded_critical_instruction.as_deref(),
437            "Use the explorer-grounded repo-wide instruction.",
438            &analysis.critical_instruction_candidates,
439            Some(GuidedInitQuestionOption {
440                value: CONTROL_NONE.to_owned(),
441                label: "No repo-wide rule".to_owned(),
442                description: "Do not add a dedicated always-follow instruction.".to_owned(),
443                recommended: false,
444            }),
445            3,
446        );
447        questions.push(GuidedInitQuestion {
448            key: GuidedInitQuestionKey::CriticalInstruction,
449            header: GuidedInitQuestionKey::CriticalInstruction.header().to_owned(),
450            prompt: "Is there one repo-wide instruction agents should always follow?".to_owned(),
451            options,
452            allow_custom: true,
453        });
454    }
455
456    questions
457}
458
459fn grounded_differs_from_selected(selected: Option<&str>, grounded: Option<&str>) -> bool {
460    let Some(grounded) = grounded.map(str::trim).filter(|value| !value.is_empty()) else {
461        return false;
462    };
463    let Some(selected) = selected.map(str::trim).filter(|value| !value.is_empty()) else {
464        return false;
465    };
466    grounded != selected
467}
468
469fn build_guided_options(
470    grounded_value: Option<&str>,
471    grounded_description: &str,
472    candidates: &[SignalCandidate],
473    trailing: Option<GuidedInitQuestionOption>,
474    max_candidates: usize,
475) -> Vec<GuidedInitQuestionOption> {
476    let mut options = Vec::new();
477
478    if let Some(value) = grounded_value.map(str::trim).filter(|value| !value.is_empty()) {
479        options.push(GuidedInitQuestionOption {
480            value: value.to_owned(),
481            label: value.to_owned(),
482            description: grounded_description.to_owned(),
483            recommended: true,
484        });
485    }
486
487    for (index, candidate) in candidates.iter().take(max_candidates).enumerate() {
488        if options.iter().any(|existing| existing.value == candidate.value) {
489            continue;
490        }
491        options.push(GuidedInitQuestionOption {
492            value: candidate.value.clone(),
493            label: candidate.label.clone(),
494            description: candidate.description.clone(),
495            recommended: grounded_value.is_none() && index == 0,
496        });
497    }
498
499    if let Some(option) = trailing
500        && options.iter().all(|existing| existing.value != option.value)
501    {
502        options.push(option);
503    }
504
505    if options.is_empty() {
506        options.push(GuidedInitQuestionOption {
507            value: CONTROL_GENERIC.to_owned(),
508            label: "Keep generic guidance".to_owned(),
509            description: "Leave this section generic for now.".to_owned(),
510            recommended: true,
511        });
512    }
513
514    options
515}
516
517fn resolve_verification_command(analysis: &ProjectAnalysis, answers: &GuidedInitAnswers) -> Option<String> {
518    resolve_guided_answer(
519        answers.answer(GuidedInitQuestionKey::VerificationCommand),
520        analysis.grounded_verification_command.clone(),
521        analysis.selected_verification_command.clone(),
522        analysis
523            .verification_candidates
524            .first()
525            .map(|candidate| candidate.value.clone()),
526    )
527}
528
529fn resolve_orientation_doc(analysis: &ProjectAnalysis, answers: &GuidedInitAnswers) -> Option<String> {
530    resolve_guided_answer(
531        answers.answer(GuidedInitQuestionKey::OrientationDoc),
532        analysis.grounded_orientation_doc.clone(),
533        analysis.selected_orientation_doc.clone(),
534        analysis.orientation_candidates.first().map(|candidate| candidate.value.clone()),
535    )
536}
537
538fn resolve_critical_instruction(analysis: &ProjectAnalysis, answers: &GuidedInitAnswers) -> Option<String> {
539    resolve_guided_answer(
540        answers.answer(GuidedInitQuestionKey::CriticalInstruction),
541        analysis.grounded_critical_instruction.clone(),
542        analysis.selected_critical_instruction.clone(),
543        None,
544    )
545}
546
547fn resolve_guided_answer(
548    answer: Option<&GuidedInitAnswer>,
549    grounded: Option<String>,
550    selected: Option<String>,
551    fallback: Option<String>,
552) -> Option<String> {
553    match resolve_answered_value(answer) {
554        AnsweredValue::Value(value) => Some(value),
555        AnsweredValue::Control => None,
556        AnsweredValue::Missing => grounded.or(selected).or(fallback),
557    }
558}
559
560enum AnsweredValue {
561    Missing,
562    Control,
563    Value(String),
564}
565
566fn resolve_answered_value(answer: Option<&GuidedInitAnswer>) -> AnsweredValue {
567    let Some(answer) = answer else {
568        return AnsweredValue::Missing;
569    };
570
571    if let Some(custom) = answer
572        .custom
573        .as_ref()
574        .map(|value| value.trim())
575        .filter(|value| !value.is_empty())
576    {
577        return AnsweredValue::Value(custom.to_owned());
578    }
579
580    let selected = answer.selected.trim();
581    if selected.is_empty() {
582        return AnsweredValue::Missing;
583    }
584
585    if matches!(selected, CONTROL_GENERIC | CONTROL_NONE) {
586        return AnsweredValue::Control;
587    }
588
589    AnsweredValue::Value(selected.to_owned())
590}
591
592fn build_quick_start_section(analysis: &ProjectAnalysis, verification_command: Option<&str>) -> String {
593    let mut lines = Vec::new();
594
595    if let Some(command) = verification_command {
596        lines.push(format!("Default verification command: `{command}` before calling work complete."));
597    }
598
599    if analysis.build_systems.iter().any(|system| system == "Cargo") {
600        lines.push("Build with `cargo check` (preferred) or `cargo build --release`.".to_owned());
601        lines.push("Format via `cargo fmt` and lint with `cargo clippy` before committing.".to_owned());
602        lines.push("Run tests with `cargo nextest run` or `cargo test <name> -- --nocapture`.".to_owned());
603    }
604
605    if let Some(package_manager) = analysis.package_manager.map(PackageManager::command) {
606        lines.push(format!("Install JavaScript dependencies with `{package_manager} install`."));
607    }
608
609    if analysis.scripts.iter().any(|script| script == "run.sh") {
610        lines.push("Start interactive sessions with `./run.sh`.".to_owned());
611    }
612
613    if lines.is_empty() {
614        lines.push("Install dependencies and run the standard build before starting new work.".to_owned());
615    }
616
617    render_section("Quick start", lines).unwrap_or_else(|| {
618        "## Quick start\n\n- Install dependencies and run the standard build before starting new work.\n\n".to_owned()
619    })
620}
621
622fn build_architecture_section(analysis: &ProjectAnalysis, orientation_doc: Option<&str>) -> String {
623    let mut lines = Vec::new();
624
625    if let Some(summary) = analysis.grounded_project_summary.as_deref() {
626        lines.push(summary.to_owned());
627    }
628
629    if let Some(path) = orientation_doc {
630        lines.push(format!("Start with `{path}` when you need repo orientation or architectural context."));
631    }
632
633    lines.push(format!("Repository: {}.", analysis.project_name));
634
635    if !analysis.languages.is_empty() {
636        lines.push(format!("Primary languages: {}.", analysis.languages.join(", ")));
637    }
638
639    if !analysis.source_dirs.is_empty() {
640        let dirs = analysis.source_dirs.iter().map(|dir| format!("`{dir}/`")).collect::<Vec<_>>();
641        lines.push(format!("Key source directories: {}.", dirs.join(", ")));
642    }
643
644    if analysis.is_application {
645        lines.push("Application entrypoints live under the primary source directories.".to_owned());
646    } else if analysis.is_library {
647        lines.push("Library-style project; expect reusable crates and packages.".to_owned());
648    }
649
650    if analysis.has_ci_cd {
651        lines.push("CI workflows detected under `.github/workflows/`; match those expectations locally.".to_owned());
652    }
653
654    if analysis.has_docker {
655        lines.push("Docker assets are present; some integration flows may depend on container setup.".to_owned());
656    }
657
658    render_section("Architecture & layout", lines)
659        .unwrap_or_else(|| "## Architecture & layout\n\n- Review the repository layout before editing.\n\n".to_owned())
660}
661
662fn build_important_instructions_section(instruction: Option<&str>) -> Option<String> {
663    let instruction = instruction?.trim();
664    if instruction.is_empty() {
665        return None;
666    }
667    render_section("Important instructions", vec![instruction.to_owned()])
668}
669
670fn build_code_style_section(analysis: &ProjectAnalysis) -> String {
671    let mut lines = Vec::new();
672
673    for language in &analysis.languages {
674        match language.as_str() {
675            "Rust" => {
676                lines.push("Rust code uses 4-space indentation, snake_case functions, PascalCase types, and `anyhow::Result<T>` with `.with_context()` for fallible paths.".to_owned());
677                lines.push("Run `cargo fmt` before committing and avoid hardcoded configuration.".to_owned());
678            }
679            "JavaScript/TypeScript" => lines.push(
680                "Use the repository formatter and linter settings; match existing component and module patterns."
681                    .to_owned(),
682            ),
683            "Python" => lines.push(
684                "Follow PEP 8, prefer Black-compatible formatting, and add type hints when practical.".to_owned(),
685            ),
686            "Go" => lines.push("Use `gofmt`/`go vet` and keep exported APIs intentional.".to_owned()),
687            other => lines.push(format!(
688                "Match the surrounding {other} conventions and run the project formatter before pushing."
689            )),
690        }
691    }
692
693    if lines.is_empty() {
694        lines.push("Match the surrounding style and keep commits free of formatting noise.".to_owned());
695    }
696
697    render_section("Code style", lines).unwrap_or_else(|| {
698        "## Code style\n\n- Match the surrounding style and keep commits free of formatting noise.\n\n".to_owned()
699    })
700}
701
702fn build_testing_section(analysis: &ProjectAnalysis, verification_command: Option<&str>) -> String {
703    let mut lines = Vec::new();
704
705    if let Some(command) = verification_command {
706        lines.push(format!("Default verification command: `{command}`."));
707    }
708
709    if analysis.build_systems.iter().any(|system| system == "Cargo") {
710        lines.push("Rust suite: `cargo nextest run` for speed, or `cargo test` for targeted fallback.".to_owned());
711        lines.push("Run `cargo clippy --workspace --all-targets -- -D warnings` for lint coverage.".to_owned());
712    }
713
714    if let Some(package_manager) = analysis.package_manager.map(PackageManager::command) {
715        lines.push(format!(
716            "Run JavaScript/TypeScript checks with `{package_manager} test` or the repo's `check` script when present."
717        ));
718    }
719
720    if analysis.build_systems.iter().any(|system| system == "Go Modules") {
721        lines.push("Run `go test ./...` for Go coverage.".to_owned());
722    }
723
724    if analysis.has_ci_cd {
725        lines.push("Keep CI green by mirroring workflow steps locally before pushing.".to_owned());
726    }
727
728    if lines.is_empty() {
729        lines.push("Run the project's automated checks before submitting changes.".to_owned());
730    }
731
732    render_section("Testing", lines).unwrap_or_else(|| {
733        "## Testing\n\n- Run the project's automated checks before submitting changes.\n\n".to_owned()
734    })
735}
736
737fn build_performance_section() -> String {
738    render_section(
739        "Performance & simplicity",
740        vec![
741            "Do not guess at bottlenecks; measure before optimizing.".to_owned(),
742            "Prefer simple algorithms and data structures until workload data proves otherwise.".to_owned(),
743            "Keep performance changes surgical and behavior-preserving.".to_owned(),
744        ],
745    )
746    .unwrap_or_else(|| "## Performance & simplicity\n\n- Measure before optimizing.\n\n".to_owned())
747}
748
749fn build_pr_guidelines_section(analysis: &ProjectAnalysis) -> Option<String> {
750    let mut lines = Vec::new();
751
752    if analysis.commit_patterns.iter().any(|pattern| pattern == "Conventional Commits") {
753        lines.push("Use Conventional Commits (`type(scope): subject`) with short, descriptive summaries.".to_owned());
754    } else {
755        lines.push("Write descriptive, imperative commit messages.".to_owned());
756    }
757
758    lines.push("Reference issues with `Fixes #123` or `Closes #123` when applicable.".to_owned());
759    lines.push("Keep pull requests focused and include test evidence for non-trivial changes.".to_owned());
760
761    render_section("PR guidelines", lines)
762}
763
764fn build_additional_guidance_section(analysis: &ProjectAnalysis, orientation_doc: Option<&str>) -> Option<String> {
765    let mut lines = Vec::new();
766
767    if let Some(path) = orientation_doc {
768        lines.push(format!("Preferred orientation doc: `{path}`."));
769    }
770
771    if !analysis.documentation_files.is_empty() {
772        lines.push(format!("Repository docs spotted: {}.", analysis.documentation_files.join(", ")));
773    }
774
775    if !analysis.dependencies.is_empty() {
776        let highlights = analysis
777            .dependencies
778            .iter()
779            .map(|(ecosystem, deps)| format!("{ecosystem} ({})", deps.join(", ")))
780            .collect::<Vec<_>>();
781        lines.push(format!("Notable dependencies: {}.", highlights.join("; ")));
782    }
783
784    if analysis.scripts.iter().any(|script| script == "run.sh")
785        && analysis.scripts.iter().any(|script| script == "run-debug.sh")
786    {
787        lines.push("Use `./run.sh` for release runs and `./run-debug.sh` for debug sessions.".to_owned());
788    }
789
790    render_section("Additional guidance", lines)
791}
792
793fn render_section(title: &str, lines: Vec<String>) -> Option<String> {
794    if lines.is_empty() {
795        return None;
796    }
797
798    let mut section = String::new();
799    section.push_str("## ");
800    section.push_str(title);
801    section.push_str("\n\n");
802
803    for line in lines {
804        section.push_str("- ");
805        section.push_str(&line);
806        section.push('\n');
807    }
808    section.push('\n');
809    Some(section)
810}
811
812fn unique_preserving_order(values: &[String]) -> Vec<String> {
813    let mut seen = BTreeSet::new();
814    let mut unique = Vec::new();
815    for value in values {
816        if seen.insert(value.clone()) {
817            unique.push(value.clone());
818        }
819    }
820    unique
821}
822
823#[cfg(test)]
824mod tests;