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