Skip to main content

omni_dev/cli/git/
check.rs

1//! Check command — validates commit messages against guidelines.
2
3use anyhow::{Context, Result};
4use clap::Parser;
5
6use crate::data::check::OutputFormat;
7
8/// Check command options - validates commit messages against guidelines.
9#[derive(Parser)]
10pub struct CheckCommand {
11    /// Commit range to check (e.g., HEAD~3..HEAD, abc123..def456).
12    /// Defaults to commits ahead of the default base branch
13    /// (origin/main, origin/master, main, or master).
14    #[arg(value_name = "COMMIT_RANGE")]
15    pub commit_range: Option<String>,
16
17    /// Path to custom context directory (defaults to .omni-dev/).
18    #[arg(long)]
19    pub context_dir: Option<std::path::PathBuf>,
20
21    /// Explicit path to guidelines file.
22    #[arg(long)]
23    pub guidelines: Option<std::path::PathBuf>,
24
25    /// Output format.
26    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Text)]
27    pub output: OutputFormat,
28
29    /// Deprecated: use `-o`/`--output` instead.
30    #[arg(long = "format", hide = true)]
31    pub format: Option<OutputFormat>,
32
33    /// Exits with error code if any issues found (including warnings).
34    #[arg(long)]
35    pub strict: bool,
36
37    /// Only shows errors/warnings, suppresses info-level output.
38    #[arg(long)]
39    pub quiet: bool,
40
41    /// Shows detailed analysis including passing commits.
42    #[arg(long)]
43    pub verbose: bool,
44
45    /// Includes passing commits in output (hidden by default).
46    #[arg(long)]
47    pub show_passing: bool,
48
49    /// Maximum number of concurrent AI requests (default: 4).
50    #[arg(long, default_value = "4")]
51    pub concurrency: usize,
52
53    /// Deprecated: use --concurrency instead.
54    #[arg(long, hide = true)]
55    pub batch_size: Option<usize>,
56
57    /// Disables the cross-commit coherence pass.
58    #[arg(long)]
59    pub no_coherence: bool,
60
61    /// Skips generating corrected message suggestions.
62    #[arg(long)]
63    pub no_suggestions: bool,
64
65    /// Offers to apply suggested messages when issues are found.
66    #[arg(long)]
67    pub twiddle: bool,
68}
69
70impl CheckCommand {
71    /// Executes the check command, validating commit messages against guidelines.
72    pub async fn execute(mut self, repo: Option<&std::path::Path>) -> Result<()> {
73        // Resolve the repo root once; every git, config, and scratch read below
74        // anchors to it (the CWD is the default when no path is injected).
75        let repo_root = match repo {
76            Some(p) => p.to_path_buf(),
77            None => std::env::current_dir().context("Failed to determine current directory")?,
78        };
79        let repo_root = repo_root.as_path();
80
81        // Resolve deprecated --batch-size into --concurrency
82        if let Some(bs) = self.batch_size {
83            eprintln!("warning: --batch-size is deprecated; use --concurrency instead");
84            self.concurrency = bs;
85        }
86
87        // Resolve deprecated --format into -o/--output
88        if let Some(format) = self.format.take() {
89            eprintln!("warning: --format is deprecated; use -o/--output instead");
90            self.output = format;
91        }
92        let output_format = self.output;
93
94        // Preflight check: validate AI credentials before any processing.
95        // Model/beta-header selection uses the global `--model`/`--beta-header`
96        // flags (propagated as OMNI_DEV_MODEL/OMNI_DEV_BETA_HEADER) and the
97        // per-backend env chain.
98        let ai_info = crate::utils::check_ai_command_prerequisites(None, repo_root)?;
99        if !self.quiet && output_format == OutputFormat::Text {
100            println!(
101                "✓ {} credentials verified (model: {})",
102                ai_info.provider, ai_info.model
103            );
104        }
105
106        if !self.quiet && output_format == OutputFormat::Text {
107            println!("🔍 Checking commit messages against guidelines...");
108        }
109
110        // 1. Generate repository view to get all commits
111        let mut repo_view = self.generate_repository_view(repo_root).await?;
112
113        // 2. Check for empty commit range (exit code 3)
114        if repo_view.commits.is_empty() {
115            eprintln!("error: no commits found in range");
116            std::process::exit(3);
117        }
118
119        if !self.quiet && output_format == OutputFormat::Text {
120            println!("📊 Found {} commits to check", repo_view.commits.len());
121        }
122
123        // 3. Load commit guidelines and scopes
124        let guidelines = self.load_guidelines(repo_root).await?;
125        let valid_scopes = self.load_scopes(repo_root);
126
127        // Refine detected scopes using file_patterns from scope definitions
128        for commit in &mut repo_view.commits {
129            commit.analysis.refine_scope(&valid_scopes);
130        }
131
132        if !self.quiet && output_format == OutputFormat::Text {
133            self.show_guidance_files_status(repo_root, &guidelines, &valid_scopes);
134        }
135
136        // 4. Initialize Claude client
137        let claude_client = crate::claude::create_default_claude_client(None, None).await?;
138
139        if self.verbose && output_format == OutputFormat::Text {
140            self.show_model_info(&claude_client)?;
141        }
142
143        // 5. Use parallel map-reduce for multiple commits, direct call for single
144        let report = if repo_view.commits.len() > 1 {
145            if !self.quiet && output_format == OutputFormat::Text {
146                println!(
147                    "🔄 Processing {} commits in parallel (concurrency: {})...",
148                    repo_view.commits.len(),
149                    self.concurrency
150                );
151            }
152            self.check_with_map_reduce(
153                &claude_client,
154                &repo_view,
155                guidelines.as_deref(),
156                &valid_scopes,
157            )
158            .await?
159        } else {
160            // Single commit — direct call
161            if !self.quiet && output_format == OutputFormat::Text {
162                println!("🤖 Analyzing commits with AI...");
163            }
164            claude_client
165                .check_commits_with_scopes(
166                    &repo_view,
167                    guidelines.as_deref(),
168                    &valid_scopes,
169                    !self.no_suggestions,
170                )
171                .await?
172        };
173
174        // 7. Output results
175        self.output_report(&report, output_format)?;
176
177        // 8. If --twiddle and there are errors with suggestions, offer to apply them
178        if should_offer_twiddle(self.twiddle, report.has_errors(), output_format) {
179            use std::io::IsTerminal;
180            let amendments = self.build_amendments_from_suggestions(&report, &repo_view);
181            if !amendments.is_empty()
182                && self
183                    .prompt_and_apply_suggestions(
184                        repo_root,
185                        amendments,
186                        std::io::stdin().is_terminal(),
187                        &mut std::io::BufReader::new(std::io::stdin()),
188                    )
189                    .await?
190            {
191                // Amendments applied — exit successfully
192                return Ok(());
193            }
194        }
195
196        // 9. Determine exit code
197        let exit_code = report.exit_code(self.strict);
198        if exit_code != 0 {
199            std::process::exit(exit_code);
200        }
201
202        Ok(())
203    }
204
205    /// Generates the repository view (reuses logic from TwiddleCommand).
206    async fn generate_repository_view(
207        &self,
208        repo_root: &std::path::Path,
209    ) -> Result<crate::data::RepositoryView> {
210        use crate::data::{
211            AiInfo, BranchInfo, FieldExplanation, FileStatusInfo, RepositoryView, VersionInfo,
212            WorkingDirectoryInfo,
213        };
214        use crate::git::{GitRepository, RemoteInfo};
215        use crate::utils::ai_scratch;
216
217        // Open git repository
218        let repo = GitRepository::open_at(repo_root)
219            .context("Failed to open git repository at the given path")?;
220
221        // Get current branch name
222        let current_branch = repo
223            .get_current_branch()
224            .unwrap_or_else(|_| "HEAD".to_string());
225
226        // Determine commit range
227        let commit_range = match &self.commit_range {
228            Some(range) => range.clone(),
229            None => super::default_commit_range(&repo)?,
230        };
231
232        // Get working directory status
233        let wd_status = repo.get_working_directory_status()?;
234        let working_directory = WorkingDirectoryInfo {
235            clean: wd_status.clean,
236            untracked_changes: wd_status
237                .untracked_changes
238                .into_iter()
239                .map(|fs| FileStatusInfo {
240                    status: fs.status,
241                    file: fs.file,
242                })
243                .collect(),
244        };
245
246        // Get remote information
247        let remotes = RemoteInfo::get_all_remotes(repo.repository())?;
248
249        // Parse commit range and get commits
250        let commits = repo.get_commits_in_range(&commit_range)?;
251
252        // Create version information
253        let versions = Some(VersionInfo {
254            omni_dev: env!("CARGO_PKG_VERSION").to_string(),
255        });
256
257        // Get AI scratch directory
258        let ai_scratch_path = ai_scratch::get_ai_scratch_dir_at(repo_root)
259            .context("Failed to determine AI scratch directory")?;
260        let ai_info = AiInfo {
261            scratch: ai_scratch_path.to_string_lossy().to_string(),
262        };
263
264        // Build repository view with branch info
265        let mut repo_view = RepositoryView {
266            versions,
267            explanation: FieldExplanation::default(),
268            working_directory,
269            remotes,
270            ai: ai_info,
271            branch_info: Some(BranchInfo {
272                branch: current_branch,
273            }),
274            pr_template: None,
275            pr_template_location: None,
276            branch_prs: None,
277            commits,
278        };
279
280        // Update field presence based on actual data
281        repo_view.update_field_presence();
282
283        Ok(repo_view)
284    }
285
286    /// Loads commit guidelines from file or context directory.
287    async fn load_guidelines(&self, repo_root: &std::path::Path) -> Result<Option<String>> {
288        // If explicit guidelines path is provided, use it
289        if let Some(guidelines_path) = &self.guidelines {
290            let content = std::fs::read_to_string(guidelines_path).with_context(|| {
291                format!(
292                    "Failed to read guidelines file: {}",
293                    guidelines_path.display()
294                )
295            })?;
296            return Ok(Some(content));
297        }
298
299        // Otherwise, use standard resolution chain
300        let context_dir =
301            crate::claude::context::resolve_context_dir_at(self.context_dir.as_deref(), repo_root);
302        crate::claude::context::load_config_content(&context_dir, "commit-guidelines.md")
303    }
304
305    /// Loads valid scopes from context directory with ecosystem defaults.
306    fn load_scopes(
307        &self,
308        repo_root: &std::path::Path,
309    ) -> Vec<crate::data::context::ScopeDefinition> {
310        let context_dir =
311            crate::claude::context::resolve_context_dir_at(self.context_dir.as_deref(), repo_root);
312        crate::claude::context::load_project_scopes(&context_dir, repo_root)
313    }
314
315    /// Shows diagnostic information about loaded guidance files.
316    fn show_guidance_files_status(
317        &self,
318        repo_root: &std::path::Path,
319        guidelines: &Option<String>,
320        valid_scopes: &[crate::data::context::ScopeDefinition],
321    ) {
322        use crate::claude::context::{
323            config_source_label, resolve_context_dir_with_source_at, ConfigSourceLabel,
324        };
325
326        let (context_dir, dir_source) =
327            resolve_context_dir_with_source_at(self.context_dir.as_deref(), repo_root);
328
329        println!("📋 Project guidance files status:");
330        println!("   📂 Config dir: {} ({dir_source})", context_dir.display());
331
332        // Check commit guidelines
333        let guidelines_source = if guidelines.is_some() {
334            match config_source_label(&context_dir, "commit-guidelines.md") {
335                ConfigSourceLabel::NotFound => "✅ (source unknown)".to_string(),
336                label => format!("✅ {label}"),
337            }
338        } else {
339            "⚪ Using defaults".to_string()
340        };
341        println!("   📝 Commit guidelines: {guidelines_source}");
342
343        // Check scopes
344        let scopes_count = valid_scopes.len();
345        let scopes_source = if scopes_count > 0 {
346            match config_source_label(&context_dir, "scopes.yaml") {
347                ConfigSourceLabel::NotFound => {
348                    format!("✅ (source unknown) ({scopes_count} scopes)")
349                }
350                label => format!("✅ {label} ({scopes_count} scopes)"),
351            }
352        } else {
353            "⚪ None found (any scope accepted)".to_string()
354        };
355        println!("   🎯 Valid scopes: {scopes_source}");
356
357        println!();
358    }
359
360    /// Checks commits in parallel using batched map-reduce pattern.
361    ///
362    /// Groups commits into token-budget-aware batches, processes batches
363    /// in parallel, then runs an optional coherence pass (skipped when
364    /// all commits fit in a single batch).
365    async fn check_with_map_reduce(
366        &self,
367        claude_client: &crate::claude::client::ClaudeClient,
368        full_repo_view: &crate::data::RepositoryView,
369        guidelines: Option<&str>,
370        valid_scopes: &[crate::data::context::ScopeDefinition],
371    ) -> Result<crate::data::check::CheckReport> {
372        use std::io::IsTerminal;
373        use std::sync::atomic::{AtomicUsize, Ordering};
374        use std::sync::Arc;
375
376        use crate::claude::batch;
377        use crate::claude::token_budget;
378        use crate::data::check::{CheckReport, CommitCheckResult};
379
380        let total_commits = full_repo_view.commits.len();
381
382        // Plan batches based on token budget
383        let metadata = claude_client.get_ai_client_metadata();
384        let system_prompt = crate::claude::prompts::generate_check_system_prompt_with_scopes(
385            guidelines,
386            valid_scopes,
387        );
388        let system_prompt_tokens = token_budget::estimate_tokens(&system_prompt);
389        let batch_plan =
390            batch::plan_batches(&full_repo_view.commits, &metadata, system_prompt_tokens);
391
392        if !self.quiet && batch_plan.batches.len() < total_commits {
393            println!(
394                "   📦 Grouped {} commits into {} batches by token budget",
395                total_commits,
396                batch_plan.batches.len()
397            );
398        }
399
400        let semaphore = Arc::new(tokio::sync::Semaphore::new(self.concurrency));
401        let completed = Arc::new(AtomicUsize::new(0));
402
403        // Map phase: check batches in parallel
404        let futs: Vec<_> = batch_plan
405            .batches
406            .iter()
407            .map(|batch| {
408                let sem = semaphore.clone();
409                let completed = completed.clone();
410                let batch_indices = &batch.commit_indices;
411
412                async move {
413                    let _permit = sem
414                        .acquire()
415                        .await
416                        .map_err(|e| anyhow::anyhow!("semaphore closed: {e}"))?;
417
418                    let batch_size = batch_indices.len();
419
420                    // Create view for this batch
421                    let batch_view = if batch_size == 1 {
422                        full_repo_view.single_commit_view(&full_repo_view.commits[batch_indices[0]])
423                    } else {
424                        let commits: Vec<_> = batch_indices
425                            .iter()
426                            .map(|&i| &full_repo_view.commits[i])
427                            .collect();
428                        full_repo_view.multi_commit_view(&commits)
429                    };
430
431                    let result = claude_client
432                        .check_commits_with_scopes(
433                            &batch_view,
434                            guidelines,
435                            valid_scopes,
436                            !self.no_suggestions,
437                        )
438                        .await;
439
440                    match result {
441                        Ok(report) => {
442                            let done =
443                                completed.fetch_add(batch_size, Ordering::Relaxed) + batch_size;
444                            if !self.quiet {
445                                println!("   ✅ {done}/{total_commits} commits checked");
446                            }
447
448                            let items: Vec<_> = report
449                                .commits
450                                .into_iter()
451                                .map(|r| {
452                                    let summary = r.summary.clone().unwrap_or_default();
453                                    (r, summary)
454                                })
455                                .collect();
456                            Ok::<_, anyhow::Error>((items, vec![]))
457                        }
458                        Err(e) if batch_size > 1 => {
459                            // Split-and-retry: fall back to individual commits
460                            eprintln!(
461                                "warning: batch of {batch_size} failed, retrying individually: {e}"
462                            );
463                            let mut items = Vec::new();
464                            let mut failed_indices = Vec::new();
465                            for &idx in batch_indices {
466                                let single_view =
467                                    full_repo_view.single_commit_view(&full_repo_view.commits[idx]);
468                                let single_result = claude_client
469                                    .check_commits_with_scopes(
470                                        &single_view,
471                                        guidelines,
472                                        valid_scopes,
473                                        !self.no_suggestions,
474                                    )
475                                    .await;
476                                match single_result {
477                                    Ok(report) => {
478                                        if let Some(r) = report.commits.into_iter().next() {
479                                            let summary = r.summary.clone().unwrap_or_default();
480                                            items.push((r, summary));
481                                        }
482                                        let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
483                                        if !self.quiet {
484                                            println!(
485                                                "   ✅ {done}/{total_commits} commits checked"
486                                            );
487                                        }
488                                    }
489                                    Err(e) => {
490                                        eprintln!("warning: failed to check commit: {e}");
491                                        failed_indices.push(idx);
492                                        if !self.quiet {
493                                            println!("   ❌ commit check failed");
494                                        }
495                                    }
496                                }
497                            }
498                            Ok((items, failed_indices))
499                        }
500                        Err(e) => {
501                            // Single-commit batch failed; record the index so the user can retry
502                            let idx = batch_indices[0];
503                            eprintln!("warning: failed to check commit: {e}");
504                            let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
505                            if !self.quiet {
506                                println!("   ❌ {done}/{total_commits} commits checked (failed)");
507                            }
508                            Ok((vec![], vec![idx]))
509                        }
510                    }
511                }
512            })
513            .collect();
514
515        let results = futures::future::join_all(futs).await;
516
517        // Flatten batch results
518        let mut successes: Vec<(CommitCheckResult, String)> = Vec::new();
519        let mut failed_indices: Vec<usize> = Vec::new();
520
521        for (result, batch) in results.into_iter().zip(&batch_plan.batches) {
522            match result {
523                Ok((items, failed)) => {
524                    successes.extend(items);
525                    failed_indices.extend(failed);
526                }
527                Err(e) => {
528                    eprintln!("warning: batch processing error: {e}");
529                    failed_indices.extend(&batch.commit_indices);
530                }
531            }
532        }
533
534        // Offer interactive retry for commits that failed
535        if !failed_indices.is_empty() && !self.quiet && std::io::stdin().is_terminal() {
536            self.run_interactive_retry_check(
537                &mut failed_indices,
538                full_repo_view,
539                claude_client,
540                guidelines,
541                valid_scopes,
542                &mut successes,
543                &mut std::io::BufReader::new(std::io::stdin()),
544            )
545            .await?;
546        } else if !failed_indices.is_empty() {
547            eprintln!(
548                "warning: {} commit(s) failed to check",
549                failed_indices.len()
550            );
551        }
552
553        if !failed_indices.is_empty() {
554            eprintln!(
555                "warning: {} commit(s) ultimately failed to check",
556                failed_indices.len()
557            );
558        }
559
560        if successes.is_empty() {
561            anyhow::bail!("All commits failed to check");
562        }
563
564        // Reduce phase: optional coherence pass
565        // Skip when all commits were in a single batch (AI already saw them together)
566        let single_batch = batch_plan.batches.len() <= 1;
567        if !self.no_coherence && !single_batch && successes.len() >= 2 {
568            if !self.quiet {
569                println!("🔗 Running cross-commit coherence pass...");
570            }
571            match claude_client
572                .refine_checks_coherence(&successes, full_repo_view)
573                .await
574            {
575                Ok(refined) => {
576                    if !self.quiet {
577                        println!("✅ All commits checked!");
578                    }
579                    return Ok(refined);
580                }
581                Err(e) => {
582                    eprintln!("warning: coherence pass failed, using individual results: {e}");
583                }
584            }
585        }
586
587        if !self.quiet {
588            println!("✅ All commits checked!");
589        }
590
591        let all_results: Vec<CommitCheckResult> = successes.into_iter().map(|(r, _)| r).collect();
592
593        Ok(CheckReport::new(all_results))
594    }
595
596    /// Outputs the check report in the specified format.
597    fn output_report(
598        &self,
599        report: &crate::data::check::CheckReport,
600        format: crate::data::check::OutputFormat,
601    ) -> Result<()> {
602        use crate::data::check::OutputFormat;
603
604        match format {
605            OutputFormat::Text => self.output_text_report(report),
606            OutputFormat::Json => {
607                let json = serde_json::to_string_pretty(report)
608                    .context("Failed to serialize report to JSON")?;
609                println!("{json}");
610                Ok(())
611            }
612            OutputFormat::Yaml => {
613                let yaml =
614                    crate::data::to_yaml(report).context("Failed to serialize report to YAML")?;
615                println!("{yaml}");
616                Ok(())
617            }
618        }
619    }
620
621    /// Outputs the text format report.
622    fn output_text_report(&self, report: &crate::data::check::CheckReport) -> Result<()> {
623        use crate::data::check::IssueSeverity;
624
625        println!();
626
627        for result in &report.commits {
628            if !should_display_commit(result.passes, self.show_passing) {
629                continue;
630            }
631
632            // Skip info-only commits in quiet mode
633            if self.quiet && !has_errors_or_warnings(&result.issues) {
634                continue;
635            }
636
637            let icon = super::formatting::determine_commit_icon(result.passes, &result.issues);
638            let short_hash = super::formatting::truncate_hash(&result.hash);
639            println!("{}", format_commit_line(icon, short_hash, &result.message));
640
641            // Print issues
642            for issue in &result.issues {
643                // Skip info issues in quiet mode
644                if self.quiet && issue.severity == IssueSeverity::Info {
645                    continue;
646                }
647
648                let severity_str = super::formatting::format_severity_label(issue.severity);
649                println!(
650                    "   {} [{}] {}",
651                    severity_str, issue.section, issue.explanation
652                );
653            }
654
655            // Print suggestion if available and not in quiet mode
656            if !self.quiet {
657                if let Some(suggestion) = &result.suggestion {
658                    println!();
659                    print!("{}", format_suggestion_text(suggestion, self.verbose));
660                }
661            }
662
663            println!();
664        }
665
666        // Print summary
667        println!("{}", format_summary_text(&report.summary));
668
669        Ok(())
670    }
671
672    /// Shows model information.
673    fn show_model_info(&self, client: &crate::claude::client::ClaudeClient) -> Result<()> {
674        use crate::claude::model_config::get_model_registry;
675
676        println!("🤖 AI Model Configuration:");
677
678        let metadata = client.get_ai_client_metadata();
679        // NOTE (#967): this `--verbose` diagnostic banner reads the process-wide
680        // model catalog (`get_model_registry` → CWD-relative project models.yaml),
681        // not a `--repo`-scoped catalog. It is informational only and does not
682        // affect the check verdict, so it is left CWD-scoped until the repo-aware
683        // `ModelRegistry::load_at` foundation lands (first used by `create pr`).
684        let registry = get_model_registry();
685
686        if let Some(spec) = registry.get_model_spec(&metadata.model) {
687            if metadata.model != spec.api_identifier {
688                println!(
689                    "   📡 Model: {} → \x1b[33m{}\x1b[0m",
690                    metadata.model, spec.api_identifier
691                );
692            } else {
693                println!("   📡 Model: \x1b[33m{}\x1b[0m", metadata.model);
694            }
695            println!("   🏷️  Provider: {}", spec.provider);
696        } else {
697            println!("   📡 Model: \x1b[33m{}\x1b[0m", metadata.model);
698            println!("   🏷️  Provider: {}", metadata.provider);
699        }
700
701        println!();
702        Ok(())
703    }
704
705    /// Builds amendments from check report suggestions for failing commits.
706    fn build_amendments_from_suggestions(
707        &self,
708        report: &crate::data::check::CheckReport,
709        repo_view: &crate::data::RepositoryView,
710    ) -> Vec<crate::data::amendments::Amendment> {
711        use crate::data::amendments::Amendment;
712
713        let candidate_hashes: Vec<String> =
714            repo_view.commits.iter().map(|c| c.hash.clone()).collect();
715
716        report
717            .commits
718            .iter()
719            .filter(|r| !r.passes)
720            .filter_map(|r| {
721                let suggestion = r.suggestion.as_ref()?;
722                let full_hash = super::formatting::resolve_short_hash(&r.hash, &candidate_hashes)?;
723                Some(Amendment::new(
724                    full_hash.to_string(),
725                    suggestion.message.clone(),
726                ))
727            })
728            .collect()
729    }
730
731    /// Prompts the user to apply suggested amendments and applies them if accepted.
732    /// Returns true if amendments were applied, false if user declined.
733    ///
734    /// `is_terminal` and `reader` are injected so tests can drive the function
735    /// without blocking on real stdin.
736    async fn prompt_and_apply_suggestions(
737        &self,
738        repo_root: &std::path::Path,
739        amendments: Vec<crate::data::amendments::Amendment>,
740        is_terminal: bool,
741        reader: &mut (dyn std::io::BufRead + Send),
742    ) -> Result<bool> {
743        use crate::data::amendments::AmendmentFile;
744        use crate::git::AmendmentHandler;
745        use std::io::{self, Write};
746
747        println!();
748        println!(
749            "🔧 {} commit(s) have issues with suggested fixes available.",
750            amendments.len()
751        );
752
753        if !is_terminal {
754            eprintln!("warning: stdin is not interactive, cannot prompt to apply suggested fixes");
755            return Ok(false);
756        }
757
758        loop {
759            print!("❓ [A]pply suggested fixes, or [Q]uit? [A/q] ");
760            io::stdout().flush()?;
761
762            let Some(input) = super::read_interactive_line(reader)? else {
763                eprintln!("warning: stdin closed, not applying suggested fixes");
764                return Ok(false);
765            };
766
767            match input.trim().to_lowercase().as_str() {
768                "a" | "apply" | "" => {
769                    let amendment_file = AmendmentFile { amendments };
770                    let temp_file = tempfile::NamedTempFile::new()
771                        .context("Failed to create temp file for amendments")?;
772                    amendment_file
773                        .save_to_file(temp_file.path())
774                        .context("Failed to save amendments")?;
775
776                    let handler = AmendmentHandler::new(repo_root)
777                        .context("Failed to initialize amendment handler")?;
778                    handler
779                        .apply_amendments(&temp_file.path().to_string_lossy())
780                        .context("Failed to apply amendments")?;
781
782                    println!("✅ Suggested fixes applied successfully!");
783                    return Ok(true);
784                }
785                "q" | "quit" => return Ok(false),
786                _ => {
787                    println!("Invalid choice. Please enter 'a' to apply or 'q' to quit.");
788                }
789            }
790        }
791    }
792}
793
794// --- Interactive retry helper ---
795
796impl CheckCommand {
797    /// Prompts the user to retry or skip failed commits, reading responses
798    /// from `reader` so tests can inject a [`std::io::Cursor`] instead of
799    /// blocking on stdin.
800    #[allow(clippy::too_many_arguments)]
801    async fn run_interactive_retry_check(
802        &self,
803        failed_indices: &mut Vec<usize>,
804        full_repo_view: &crate::data::RepositoryView,
805        claude_client: &crate::claude::client::ClaudeClient,
806        guidelines: Option<&str>,
807        valid_scopes: &[crate::data::context::ScopeDefinition],
808        successes: &mut Vec<(crate::data::check::CommitCheckResult, String)>,
809        reader: &mut (dyn std::io::BufRead + Send),
810    ) -> Result<()> {
811        use std::io::Write as _;
812        println!("\n⚠️  {} commit(s) failed to check:", failed_indices.len());
813        for &idx in failed_indices.iter() {
814            let commit = &full_repo_view.commits[idx];
815            let subject = commit
816                .original_message
817                .lines()
818                .next()
819                .unwrap_or("(no message)");
820            println!("  - {}: {}", &commit.hash[..8], subject);
821        }
822        loop {
823            print!("\n❓ [R]etry failed commits, or [S]kip? [R/s] ");
824            std::io::stdout().flush()?;
825            let Some(input) = super::read_interactive_line(reader)? else {
826                eprintln!("warning: stdin closed, skipping failed commit(s)");
827                break;
828            };
829            match input.trim().to_lowercase().as_str() {
830                "r" | "retry" | "" => {
831                    let mut still_failed = Vec::new();
832                    for &idx in failed_indices.iter() {
833                        let single_view =
834                            full_repo_view.single_commit_view(&full_repo_view.commits[idx]);
835                        match claude_client
836                            .check_commits_with_scopes(
837                                &single_view,
838                                guidelines,
839                                valid_scopes,
840                                !self.no_suggestions,
841                            )
842                            .await
843                        {
844                            Ok(report) => {
845                                if let Some(r) = report.commits.into_iter().next() {
846                                    let summary = r.summary.clone().unwrap_or_default();
847                                    successes.push((r, summary));
848                                }
849                            }
850                            Err(e) => {
851                                eprintln!("warning: still failed: {e}");
852                                still_failed.push(idx);
853                            }
854                        }
855                    }
856                    *failed_indices = still_failed;
857                    if failed_indices.is_empty() {
858                        println!("✅ All retried commits succeeded.");
859                        break;
860                    }
861                    println!("\n⚠️  {} commit(s) still failed:", failed_indices.len());
862                    for &idx in failed_indices.iter() {
863                        let commit = &full_repo_view.commits[idx];
864                        let subject = commit
865                            .original_message
866                            .lines()
867                            .next()
868                            .unwrap_or("(no message)");
869                        println!("  - {}: {}", &commit.hash[..8], subject);
870                    }
871                }
872                "s" | "skip" => {
873                    println!("Skipping {} failed commit(s).", failed_indices.len());
874                    break;
875                }
876                _ => println!("Please enter 'r' to retry or 's' to skip."),
877            }
878        }
879        Ok(())
880    }
881}
882
883/// Structured output from [`run_check`] for programmatic consumers (MCP).
884#[derive(Debug, Clone)]
885pub struct CheckOutcome {
886    /// YAML serialisation of the full [`crate::data::check::CheckReport`].
887    pub report_yaml: String,
888    /// `true` when any commit has an error-severity issue.
889    pub has_errors: bool,
890    /// `true` when any commit has a warning-severity issue.
891    pub has_warnings: bool,
892    /// Total commits in the range that were checked.
893    pub total_commits: usize,
894    /// Strict mode setting that produced `exit_code`.
895    pub strict: bool,
896    /// Exit code the CLI would use, honouring `strict`.
897    pub exit_code: i32,
898}
899
900/// Non-interactive core for `omni-dev git commit message check`.
901///
902/// Shared by the CLI (which prints the report and uses the exit code) and the
903/// MCP server (which returns the structured outcome to the caller). Always
904/// runs a single direct AI call — the MCP tool boundary never needs the
905/// map-reduce/interactive-retry flow from [`CheckCommand::execute`].
906///
907/// `repo_path` selects the repository to check (`None` defaults to the current
908/// working directory). It is resolved once here and threaded explicitly into
909/// [`run_check_with_client`], so context-discovery and AI-scratch paths anchor
910/// to the target repo without changing the process working directory.
911pub async fn run_check(
912    range: &str,
913    guidelines_path: Option<&std::path::Path>,
914    repo_path: Option<&std::path::Path>,
915    strict: bool,
916    model: Option<String>,
917) -> Result<CheckOutcome> {
918    let repo_root = match repo_path {
919        Some(p) => p.to_path_buf(),
920        None => std::env::current_dir().context("Failed to determine current directory")?,
921    };
922
923    // Preflight: validate AI credentials.
924    crate::utils::check_ai_command_prerequisites(model.as_deref(), &repo_root)?;
925
926    let claude_client = crate::claude::create_default_claude_client(model, None).await?;
927    run_check_with_client(range, guidelines_path, strict, &claude_client, &repo_root).await
928}
929
930/// Non-credential-gated inner core of [`run_check`] for unit tests.
931///
932/// Extracted so tests can inject a [`crate::claude::client::ClaudeClient`]
933/// backed by the in-crate mock AI client and exercise the full happy path
934/// without real credentials. `repo_root` selects the repository; callers run
935/// preflight themselves.
936pub(crate) async fn run_check_with_client(
937    range: &str,
938    guidelines_path: Option<&std::path::Path>,
939    strict: bool,
940    claude_client: &crate::claude::client::ClaudeClient,
941    repo_root: &std::path::Path,
942) -> Result<CheckOutcome> {
943    use crate::data::{
944        AiInfo, BranchInfo, FieldExplanation, FileStatusInfo, RepositoryView, VersionInfo,
945        WorkingDirectoryInfo,
946    };
947    use crate::git::{GitRepository, RemoteInfo};
948    use crate::utils::ai_scratch;
949
950    let repo = GitRepository::open_at(repo_root)
951        .context("Failed to open git repository at the given path")?;
952
953    let current_branch = repo
954        .get_current_branch()
955        .unwrap_or_else(|_| "HEAD".to_string());
956
957    let wd_status = repo.get_working_directory_status()?;
958    let working_directory = WorkingDirectoryInfo {
959        clean: wd_status.clean,
960        untracked_changes: wd_status
961            .untracked_changes
962            .into_iter()
963            .map(|fs| FileStatusInfo {
964                status: fs.status,
965                file: fs.file,
966            })
967            .collect(),
968    };
969
970    let remotes = RemoteInfo::get_all_remotes(repo.repository())?;
971    let commits = repo.get_commits_in_range(range)?;
972
973    if commits.is_empty() {
974        anyhow::bail!("no commits found in range: {range}");
975    }
976
977    let ai_scratch_path = ai_scratch::get_ai_scratch_dir_at(repo_root)
978        .context("Failed to determine AI scratch directory")?;
979    let ai_info = AiInfo {
980        scratch: ai_scratch_path.to_string_lossy().to_string(),
981    };
982
983    let mut repo_view = RepositoryView {
984        versions: Some(VersionInfo {
985            omni_dev: env!("CARGO_PKG_VERSION").to_string(),
986        }),
987        explanation: FieldExplanation::default(),
988        working_directory,
989        remotes,
990        ai: ai_info,
991        branch_info: Some(BranchInfo {
992            branch: current_branch,
993        }),
994        pr_template: None,
995        pr_template_location: None,
996        branch_prs: None,
997        commits,
998    };
999    repo_view.update_field_presence();
1000
1001    let guidelines = if let Some(path) = guidelines_path {
1002        Some(
1003            std::fs::read_to_string(path)
1004                .with_context(|| format!("Failed to read guidelines file: {}", path.display()))?,
1005        )
1006    } else {
1007        let context_dir = crate::claude::context::resolve_context_dir_at(None, repo_root);
1008        crate::claude::context::load_config_content(&context_dir, "commit-guidelines.md")?
1009    };
1010
1011    let context_dir = crate::claude::context::resolve_context_dir_at(None, repo_root);
1012    let valid_scopes = crate::claude::context::load_project_scopes(&context_dir, repo_root);
1013    for commit in &mut repo_view.commits {
1014        commit.analysis.refine_scope(&valid_scopes);
1015    }
1016
1017    let report = claude_client
1018        .check_commits_with_scopes(&repo_view, guidelines.as_deref(), &valid_scopes, true)
1019        .await?;
1020
1021    let report_yaml = crate::data::to_yaml(&report).context("Failed to serialise CheckReport")?;
1022    let has_errors = report.has_errors();
1023    let has_warnings = report.has_warnings();
1024    let exit_code = report.exit_code(strict);
1025    let total_commits = report.commits.len();
1026
1027    Ok(CheckOutcome {
1028        report_yaml,
1029        has_errors,
1030        has_warnings,
1031        total_commits,
1032        strict,
1033        exit_code,
1034    })
1035}
1036
1037#[cfg(test)]
1038#[allow(clippy::unwrap_used, clippy::expect_used)]
1039mod run_check_tests {
1040    use super::*;
1041    use crate::claude::client::ClaudeClient;
1042    use crate::claude::test_utils::ConfigurableMockAiClient;
1043    use git2::{Repository, Signature};
1044
1045    /// `run_check_with_client` opens the injected repo via `open_at` before any
1046    /// AI call, so an invalid path errors with a git/repository error and needs
1047    /// no credentials.
1048    #[tokio::test]
1049    async fn run_check_with_client_invalid_repo_path_errors() {
1050        let mock = ConfigurableMockAiClient::new(vec![]);
1051        let client = ClaudeClient::new(Box::new(mock));
1052        let err = run_check_with_client(
1053            "HEAD",
1054            None,
1055            false,
1056            &client,
1057            std::path::Path::new("/no/such/path/exists"),
1058        )
1059        .await
1060        .unwrap_err();
1061        let msg = format!("{err:#}");
1062        assert!(
1063            msg.to_lowercase().contains("git") || msg.to_lowercase().contains("repository"),
1064            "expected git/repository error, got: {msg}"
1065        );
1066    }
1067
1068    fn init_test_repo() -> tempfile::TempDir {
1069        let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
1070        std::fs::create_dir_all(&tmp_root).unwrap();
1071        let temp_dir = tempfile::tempdir_in(&tmp_root).unwrap();
1072        let repo = Repository::init(temp_dir.path()).unwrap();
1073        {
1074            let mut cfg = repo.config().unwrap();
1075            cfg.set_str("user.name", "Test").unwrap();
1076            cfg.set_str("user.email", "test@example.com").unwrap();
1077        }
1078        let signature = Signature::now("Test", "test@example.com").unwrap();
1079        std::fs::write(temp_dir.path().join("f.txt"), "c").unwrap();
1080        let mut idx = repo.index().unwrap();
1081        idx.add_path(std::path::Path::new("f.txt")).unwrap();
1082        idx.write().unwrap();
1083        let tree_id = idx.write_tree().unwrap();
1084        let tree = repo.find_tree(tree_id).unwrap();
1085        repo.commit(
1086            Some("HEAD"),
1087            &signature,
1088            &signature,
1089            "feat(cli): only",
1090            &tree,
1091            &[],
1092        )
1093        .unwrap();
1094        temp_dir
1095    }
1096
1097    fn passing_check_yaml(hash_prefix: &str) -> String {
1098        format!("checks:\n  - commit: {hash_prefix}\n    passes: true\n    issues: []\n")
1099    }
1100
1101    fn failing_check_yaml(hash_prefix: &str) -> String {
1102        format!(
1103            "checks:\n  - commit: {hash_prefix}\n    passes: false\n    issues:\n      - severity: error\n        section: subject\n        rule: format\n        explanation: bad\n"
1104        )
1105    }
1106
1107    #[tokio::test]
1108    async fn run_check_with_client_happy_path_passing() {
1109        let temp_dir = init_test_repo();
1110
1111        // Use a short hash prefix that resolves in the mini repo.
1112        let mock = ConfigurableMockAiClient::new(vec![Ok(passing_check_yaml("00000000"))]);
1113        let client = ClaudeClient::new(Box::new(mock));
1114
1115        let outcome = run_check_with_client("HEAD", None, false, &client, temp_dir.path())
1116            .await
1117            .unwrap();
1118        assert!(!outcome.has_errors);
1119        assert!(!outcome.has_warnings);
1120        assert_eq!(outcome.exit_code, 0);
1121        assert_eq!(outcome.total_commits, 1);
1122        assert!(outcome.report_yaml.contains("commits:"));
1123        assert!(!outcome.strict);
1124    }
1125
1126    #[tokio::test]
1127    async fn run_check_with_client_failing_commit_sets_error_exit_code() {
1128        let temp_dir = init_test_repo();
1129
1130        let mock = ConfigurableMockAiClient::new(vec![Ok(failing_check_yaml("00000000"))]);
1131        let client = ClaudeClient::new(Box::new(mock));
1132
1133        let outcome = run_check_with_client("HEAD", None, false, &client, temp_dir.path())
1134            .await
1135            .unwrap();
1136        assert!(outcome.has_errors);
1137        assert_eq!(outcome.exit_code, 1);
1138    }
1139
1140    #[tokio::test]
1141    async fn run_check_with_client_strict_does_not_affect_no_issues() {
1142        let temp_dir = init_test_repo();
1143
1144        let mock = ConfigurableMockAiClient::new(vec![Ok(passing_check_yaml("00000000"))]);
1145        let client = ClaudeClient::new(Box::new(mock));
1146
1147        let outcome = run_check_with_client("HEAD", None, true, &client, temp_dir.path())
1148            .await
1149            .unwrap();
1150        assert_eq!(outcome.exit_code, 0);
1151        assert!(outcome.strict);
1152    }
1153
1154    #[tokio::test]
1155    async fn run_check_with_client_explicit_guidelines_path() {
1156        let temp_dir = init_test_repo();
1157        let guidelines_path = temp_dir.path().join("guidelines.md");
1158        std::fs::write(&guidelines_path, "guideline body").unwrap();
1159
1160        let mock = ConfigurableMockAiClient::new(vec![Ok(passing_check_yaml("00000000"))]);
1161        let client = ClaudeClient::new(Box::new(mock));
1162
1163        let outcome = run_check_with_client(
1164            "HEAD",
1165            Some(&guidelines_path),
1166            false,
1167            &client,
1168            temp_dir.path(),
1169        )
1170        .await
1171        .unwrap();
1172        assert_eq!(outcome.exit_code, 0);
1173    }
1174
1175    #[tokio::test]
1176    async fn run_check_with_client_guidelines_path_missing_errors() {
1177        let temp_dir = init_test_repo();
1178        let missing = temp_dir.path().join("no-such.md");
1179
1180        let mock = ConfigurableMockAiClient::new(vec![Ok(passing_check_yaml("00000000"))]);
1181        let client = ClaudeClient::new(Box::new(mock));
1182        let err = run_check_with_client("HEAD", Some(&missing), false, &client, temp_dir.path())
1183            .await
1184            .unwrap_err();
1185        assert!(
1186            format!("{err:#}").contains("guidelines"),
1187            "expected guidelines read error"
1188        );
1189    }
1190
1191    #[tokio::test]
1192    async fn run_check_with_client_empty_range_bails() {
1193        let temp_dir = init_test_repo();
1194
1195        let mock = ConfigurableMockAiClient::new(vec![]);
1196        let client = ClaudeClient::new(Box::new(mock));
1197        // A range with no commits reachable → get_commits_in_range returns empty.
1198        let err = run_check_with_client("HEAD..HEAD", None, false, &client, temp_dir.path())
1199            .await
1200            .unwrap_err();
1201        assert!(format!("{err:#}").contains("no commits"));
1202    }
1203
1204    #[tokio::test]
1205    async fn run_check_with_client_ai_failure_propagates() {
1206        let temp_dir = init_test_repo();
1207
1208        // No responses → mock returns "no more mock responses" error; this
1209        // propagates after check_commits_with_scopes exhausts its retries.
1210        let mock = ConfigurableMockAiClient::new(vec![]);
1211        let client = ClaudeClient::new(Box::new(mock));
1212        let err = run_check_with_client("HEAD", None, false, &client, temp_dir.path())
1213            .await
1214            .unwrap_err();
1215        let _ = err; // any error is acceptable — the point is we didn't panic
1216    }
1217
1218    #[test]
1219    fn check_outcome_clone_and_debug() {
1220        // Cover derived impls.
1221        let outcome = CheckOutcome {
1222            report_yaml: "x".to_string(),
1223            has_errors: false,
1224            has_warnings: true,
1225            total_commits: 1,
1226            strict: true,
1227            exit_code: 2,
1228        };
1229        let cloned = outcome.clone();
1230        assert_eq!(format!("{outcome:?}"), format!("{cloned:?}"));
1231    }
1232
1233    /// "No silent mix" guard: default commit guidelines are loaded from the
1234    /// INJECTED repo's `.omni-dev/commit-guidelines.md`, not the process CWD.
1235    /// We write a distinctive marker into the temp repo's guidelines and assert
1236    /// it reaches the AI prompt.
1237    #[tokio::test]
1238    async fn run_check_with_client_loads_guidelines_from_injected_repo() {
1239        let temp_dir = init_test_repo();
1240        let omni_dir = temp_dir.path().join(".omni-dev");
1241        std::fs::create_dir_all(&omni_dir).unwrap();
1242        std::fs::write(
1243            omni_dir.join("commit-guidelines.md"),
1244            "# Project rules\n\nDISTINCTIVE_GUIDELINE_MARKER: always do the thing.\n",
1245        )
1246        .unwrap();
1247
1248        let mock = ConfigurableMockAiClient::new(vec![Ok(passing_check_yaml("00000000"))]);
1249        let prompts = mock.prompt_handle();
1250        let client = ClaudeClient::new(Box::new(mock));
1251
1252        let _ = run_check_with_client("HEAD", None, false, &client, temp_dir.path())
1253            .await
1254            .unwrap();
1255
1256        let recorded = prompts.prompts();
1257        assert!(!recorded.is_empty(), "expected at least one AI call");
1258        assert!(
1259            recorded.iter().any(|(s, u)| {
1260                s.contains("DISTINCTIVE_GUIDELINE_MARKER")
1261                    || u.contains("DISTINCTIVE_GUIDELINE_MARKER")
1262            }),
1263            "guidelines from the injected repo must reach the prompt: {recorded:?}"
1264        );
1265    }
1266}
1267
1268// --- Extracted pure functions ---
1269
1270/// Returns whether a commit should be displayed based on its pass status.
1271fn should_display_commit(passes: bool, show_passing: bool) -> bool {
1272    !passes || show_passing
1273}
1274
1275/// Returns whether any issues have Error or Warning severity.
1276fn has_errors_or_warnings(issues: &[crate::data::check::CommitIssue]) -> bool {
1277    use crate::data::check::IssueSeverity;
1278    issues
1279        .iter()
1280        .any(|i| matches!(i.severity, IssueSeverity::Error | IssueSeverity::Warning))
1281}
1282
1283/// Returns whether the twiddle (auto-fix) flow should be offered.
1284fn should_offer_twiddle(
1285    twiddle_flag: bool,
1286    has_errors: bool,
1287    format: crate::data::check::OutputFormat,
1288) -> bool {
1289    twiddle_flag && has_errors && format == crate::data::check::OutputFormat::Text
1290}
1291
1292/// Formats a commit suggestion as indented text.
1293fn format_suggestion_text(
1294    suggestion: &crate::data::check::CommitSuggestion,
1295    verbose: bool,
1296) -> String {
1297    let mut output = String::new();
1298    output.push_str("   Suggested message:\n");
1299    for line in suggestion.message.lines() {
1300        output.push_str(&format!("      {line}\n"));
1301    }
1302    if verbose {
1303        output.push('\n');
1304        output.push_str("   Why this is better:\n");
1305        for line in suggestion.explanation.lines() {
1306            output.push_str(&format!("   {line}\n"));
1307        }
1308    }
1309    output
1310}
1311
1312/// Formats the summary section of a check report.
1313fn format_summary_text(summary: &crate::data::check::CheckSummary) -> String {
1314    format!(
1315        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\
1316         Summary: {} commits checked\n\
1317         \x20 {} errors, {} warnings\n\
1318         \x20 {} passed, {} with issues",
1319        summary.total_commits,
1320        summary.error_count,
1321        summary.warning_count,
1322        summary.passing_commits,
1323        summary.failing_commits,
1324    )
1325}
1326
1327/// Formats a single commit line for text output.
1328fn format_commit_line(icon: &str, short_hash: &str, message: &str) -> String {
1329    format!("{icon} {short_hash} - \"{message}\"")
1330}
1331
1332#[cfg(test)]
1333#[allow(clippy::unwrap_used, clippy::expect_used)]
1334mod tests {
1335    use super::*;
1336    use crate::data::check::{
1337        CheckSummary, CommitIssue, CommitSuggestion, IssueSeverity, OutputFormat,
1338    };
1339
1340    // --- should_display_commit ---
1341
1342    #[test]
1343    fn display_commit_passing_hidden() {
1344        assert!(!should_display_commit(true, false));
1345    }
1346
1347    #[test]
1348    fn display_commit_passing_shown() {
1349        assert!(should_display_commit(true, true));
1350    }
1351
1352    #[test]
1353    fn display_commit_failing() {
1354        assert!(should_display_commit(false, false));
1355        assert!(should_display_commit(false, true));
1356    }
1357
1358    // --- has_errors_or_warnings ---
1359
1360    #[test]
1361    fn errors_or_warnings_with_error() {
1362        let issues = vec![CommitIssue {
1363            severity: IssueSeverity::Error,
1364            section: "subject".to_string(),
1365            rule: "length".to_string(),
1366            explanation: "too long".to_string(),
1367        }];
1368        assert!(has_errors_or_warnings(&issues));
1369    }
1370
1371    #[test]
1372    fn errors_or_warnings_with_warning() {
1373        let issues = vec![CommitIssue {
1374            severity: IssueSeverity::Warning,
1375            section: "body".to_string(),
1376            rule: "style".to_string(),
1377            explanation: "minor issue".to_string(),
1378        }];
1379        assert!(has_errors_or_warnings(&issues));
1380    }
1381
1382    #[test]
1383    fn errors_or_warnings_info_only() {
1384        let issues = vec![CommitIssue {
1385            severity: IssueSeverity::Info,
1386            section: "body".to_string(),
1387            rule: "suggestion".to_string(),
1388            explanation: "consider adding more detail".to_string(),
1389        }];
1390        assert!(!has_errors_or_warnings(&issues));
1391    }
1392
1393    #[test]
1394    fn errors_or_warnings_empty() {
1395        assert!(!has_errors_or_warnings(&[]));
1396    }
1397
1398    // --- should_offer_twiddle ---
1399
1400    #[test]
1401    fn offer_twiddle_all_conditions_met() {
1402        assert!(should_offer_twiddle(true, true, OutputFormat::Text));
1403    }
1404
1405    #[test]
1406    fn offer_twiddle_flag_off() {
1407        assert!(!should_offer_twiddle(false, true, OutputFormat::Text));
1408    }
1409
1410    #[test]
1411    fn offer_twiddle_no_errors() {
1412        assert!(!should_offer_twiddle(true, false, OutputFormat::Text));
1413    }
1414
1415    #[test]
1416    fn offer_twiddle_json_format() {
1417        assert!(!should_offer_twiddle(true, true, OutputFormat::Json));
1418    }
1419
1420    // --- format_suggestion_text ---
1421
1422    #[test]
1423    fn suggestion_text_basic() {
1424        let suggestion = CommitSuggestion {
1425            message: "feat(cli): add new flag".to_string(),
1426            explanation: "uses conventional format".to_string(),
1427        };
1428        let result = format_suggestion_text(&suggestion, false);
1429        assert!(result.contains("Suggested message:"));
1430        assert!(result.contains("feat(cli): add new flag"));
1431        assert!(!result.contains("Why this is better"));
1432    }
1433
1434    #[test]
1435    fn suggestion_text_verbose() {
1436        let suggestion = CommitSuggestion {
1437            message: "fix: resolve crash".to_string(),
1438            explanation: "clear description of fix".to_string(),
1439        };
1440        let result = format_suggestion_text(&suggestion, true);
1441        assert!(result.contains("Suggested message:"));
1442        assert!(result.contains("fix: resolve crash"));
1443        assert!(result.contains("Why this is better:"));
1444        assert!(result.contains("clear description of fix"));
1445    }
1446
1447    // --- format_summary_text ---
1448
1449    #[test]
1450    fn summary_text_formatting() {
1451        let summary = CheckSummary {
1452            total_commits: 5,
1453            passing_commits: 3,
1454            failing_commits: 2,
1455            error_count: 1,
1456            warning_count: 4,
1457            info_count: 0,
1458        };
1459        let result = format_summary_text(&summary);
1460        assert!(result.contains("5 commits checked"));
1461        assert!(result.contains("1 errors, 4 warnings"));
1462        assert!(result.contains("3 passed, 2 with issues"));
1463    }
1464
1465    // --- format_commit_line ---
1466
1467    #[test]
1468    fn commit_line_formatting() {
1469        let line = format_commit_line("✅", "abc1234", "feat: add feature");
1470        assert_eq!(line, "✅ abc1234 - \"feat: add feature\"");
1471    }
1472
1473    // --- check_with_map_reduce (error path coverage) ---
1474
1475    fn make_check_cmd(quiet: bool) -> CheckCommand {
1476        CheckCommand {
1477            commit_range: None,
1478            context_dir: None,
1479            guidelines: None,
1480            output: OutputFormat::Text,
1481            format: None,
1482            strict: false,
1483            quiet,
1484            verbose: false,
1485            show_passing: false,
1486            concurrency: 4,
1487            batch_size: None,
1488            no_coherence: true,
1489            no_suggestions: false,
1490            twiddle: false,
1491        }
1492    }
1493
1494    #[tokio::test]
1495    async fn execute_folds_deprecated_format_flag() {
1496        // A non-git temp dir makes preflight bail immediately after the
1497        // deprecated `--format` fold runs (no AI credentials or network needed).
1498        let dir = tempfile::tempdir().unwrap();
1499        let mut cmd = make_check_cmd(true);
1500        cmd.format = Some(OutputFormat::Json);
1501        let result = cmd.execute(Some(dir.path())).await;
1502        assert!(result.is_err());
1503    }
1504
1505    fn make_check_commit(hash: &str) -> (crate::git::CommitInfo, tempfile::NamedTempFile) {
1506        use crate::git::commit::FileChanges;
1507        use crate::git::{CommitAnalysis, CommitInfo};
1508        let tmp = tempfile::NamedTempFile::new().unwrap();
1509        let commit = CommitInfo {
1510            hash: hash.to_string(),
1511            author: "Test <test@test.com>".to_string(),
1512            date: chrono::Utc::now().fixed_offset(),
1513            original_message: format!("feat: commit {hash}"),
1514            in_main_branches: vec![],
1515            analysis: CommitAnalysis {
1516                detected_type: "feat".to_string(),
1517                detected_scope: String::new(),
1518                proposed_message: format!("feat: commit {hash}"),
1519                file_changes: FileChanges {
1520                    total_files: 0,
1521                    files_added: 0,
1522                    files_deleted: 0,
1523                    file_list: vec![],
1524                },
1525                diff_summary: String::new(),
1526                diff_file: tmp.path().to_string_lossy().to_string(),
1527                file_diffs: Vec::new(),
1528            },
1529        };
1530        (commit, tmp)
1531    }
1532
1533    fn make_check_repo_view(commits: Vec<crate::git::CommitInfo>) -> crate::data::RepositoryView {
1534        use crate::data::{AiInfo, FieldExplanation, RepositoryView, WorkingDirectoryInfo};
1535        RepositoryView {
1536            versions: None,
1537            explanation: FieldExplanation::default(),
1538            working_directory: WorkingDirectoryInfo {
1539                clean: true,
1540                untracked_changes: vec![],
1541            },
1542            remotes: vec![],
1543            ai: AiInfo {
1544                scratch: String::new(),
1545            },
1546            branch_info: None,
1547            pr_template: None,
1548            pr_template_location: None,
1549            branch_prs: None,
1550            commits,
1551        }
1552    }
1553
1554    fn check_yaml(hash: &str) -> String {
1555        format!("checks:\n  - commit: {hash}\n    passes: true\n    issues: []\n")
1556    }
1557
1558    fn make_client(responses: Vec<anyhow::Result<String>>) -> crate::claude::client::ClaudeClient {
1559        crate::claude::client::ClaudeClient::new(Box::new(
1560            crate::claude::test_utils::ConfigurableMockAiClient::new(responses),
1561        ))
1562    }
1563
1564    // check_commits_with_retry uses max_retries=2 (3 total attempts), so a
1565    // batch or individual commit needs 3 consecutive Err responses to fail.
1566    fn errs(n: usize) -> Vec<anyhow::Result<String>> {
1567        (0..n)
1568            .map(|_| Err(anyhow::anyhow!("mock failure")))
1569            .collect()
1570    }
1571
1572    #[tokio::test]
1573    async fn check_with_map_reduce_single_commit_fails_returns_err() {
1574        // A single-commit batch that exhausts all retries records the index in
1575        // failed_indices and returns Ok(([], [idx])). With successes empty the
1576        // method bails, so the overall result is Err.
1577        let (commit, _tmp) = make_check_commit("abc00000");
1578        let cmd = make_check_cmd(true);
1579        let repo_view = make_check_repo_view(vec![commit]);
1580        let client = make_client(errs(3));
1581        let result = cmd
1582            .check_with_map_reduce(&client, &repo_view, None, &[])
1583            .await;
1584        assert!(result.is_err(), "empty successes should bail");
1585    }
1586
1587    #[tokio::test]
1588    async fn check_with_map_reduce_single_commit_succeeds() {
1589        // Happy path: one commit, one successful batch response.
1590        let (commit, _tmp) = make_check_commit("abc00000");
1591        let cmd = make_check_cmd(true);
1592        let repo_view = make_check_repo_view(vec![commit]);
1593        let client = make_client(vec![Ok(check_yaml("abc00000"))]);
1594        let result = cmd
1595            .check_with_map_reduce(&client, &repo_view, None, &[])
1596            .await;
1597        assert!(result.is_ok());
1598        assert_eq!(result.unwrap().commits.len(), 1);
1599    }
1600
1601    #[tokio::test]
1602    async fn check_with_map_reduce_batch_fails_split_retry_both_succeed() {
1603        // Two commits fit into one batch. The batch fails (3 retries exhausted),
1604        // triggering split-and-retry. Both individual commits then succeed.
1605        let (c1, _t1) = make_check_commit("abc00000");
1606        let (c2, _t2) = make_check_commit("def00000");
1607        let cmd = make_check_cmd(true);
1608        let repo_view = make_check_repo_view(vec![c1, c2]);
1609        let mut responses = errs(3); // batch failure
1610        responses.push(Ok(check_yaml("abc00000"))); // abc individual
1611        responses.push(Ok(check_yaml("def00000"))); // def individual
1612        let client = make_client(responses);
1613        let result = cmd
1614            .check_with_map_reduce(&client, &repo_view, None, &[])
1615            .await;
1616        assert!(result.is_ok());
1617        assert_eq!(result.unwrap().commits.len(), 2);
1618    }
1619
1620    #[tokio::test]
1621    async fn check_with_map_reduce_batch_fails_split_one_individual_fails_quiet() {
1622        // Batch fails → split-and-retry. abc succeeds; def exhausts its retries
1623        // and is recorded in failed_indices. In quiet mode the method returns
1624        // Ok with partial results rather than bailing (successes is non-empty).
1625        let (c1, _t1) = make_check_commit("abc00000");
1626        let (c2, _t2) = make_check_commit("def00000");
1627        let cmd = make_check_cmd(true);
1628        let repo_view = make_check_repo_view(vec![c1, c2]);
1629        let mut responses = errs(3); // batch failure
1630        responses.push(Ok(check_yaml("abc00000"))); // abc individual succeeds
1631        responses.extend(errs(3)); // def individual exhausts retries
1632        let client = make_client(responses);
1633        let result = cmd
1634            .check_with_map_reduce(&client, &repo_view, None, &[])
1635            .await;
1636        // abc succeeded, so successes is non-empty and the method returns Ok
1637        assert!(result.is_ok());
1638        assert_eq!(result.unwrap().commits.len(), 1);
1639    }
1640
1641    #[tokio::test]
1642    async fn check_with_map_reduce_all_fail_in_split_retry_returns_err() {
1643        // Batch fails → split-and-retry. Both individual commits also fail.
1644        // successes stays empty so the method bails.
1645        let (c1, _t1) = make_check_commit("abc00000");
1646        let (c2, _t2) = make_check_commit("def00000");
1647        let cmd = make_check_cmd(true);
1648        let repo_view = make_check_repo_view(vec![c1, c2]);
1649        let mut responses = errs(3); // batch failure
1650        responses.extend(errs(3)); // abc individual exhausts retries
1651        responses.extend(errs(3)); // def individual exhausts retries
1652        let client = make_client(responses);
1653        let result = cmd
1654            .check_with_map_reduce(&client, &repo_view, None, &[])
1655            .await;
1656        assert!(result.is_err(), "no successes should bail");
1657    }
1658
1659    // Non-quiet variants: cover the `if !self.quiet { println!(...) }` branches
1660    // that are skipped when quiet=true. With quiet=false and all commits
1661    // ultimately succeeding, failed_indices stays empty so the interactive
1662    // stdin loop is never entered.
1663
1664    #[tokio::test]
1665    async fn check_with_map_reduce_non_quiet_single_commit_succeeds() {
1666        // quiet=false covers the "✅ All commits checked!" and multi-batch
1667        // grouping print paths. Two commits in one batch → batches(1) < total(2)
1668        // triggers the "📦 Grouped..." message.
1669        let (c1, _t1) = make_check_commit("abc00000");
1670        let (c2, _t2) = make_check_commit("def00000");
1671        let cmd = make_check_cmd(false);
1672        let repo_view = make_check_repo_view(vec![c1, c2]);
1673        let mut responses = errs(3); // batch failure → split-and-retry
1674        responses.push(Ok(check_yaml("abc00000")));
1675        responses.push(Ok(check_yaml("def00000")));
1676        let client = make_client(responses);
1677        let result = cmd
1678            .check_with_map_reduce(&client, &repo_view, None, &[])
1679            .await;
1680        assert!(result.is_ok());
1681        assert_eq!(result.unwrap().commits.len(), 2);
1682    }
1683
1684    // --- run_interactive_retry_check ---
1685
1686    #[tokio::test]
1687    async fn interactive_retry_skip_immediately() {
1688        // "s" input → loop exits without calling the AI client at all.
1689        let (commit, _tmp) = make_check_commit("abc00000");
1690        let cmd = make_check_cmd(false);
1691        let repo_view = make_check_repo_view(vec![commit]);
1692        let client = make_client(vec![]); // no responses needed
1693        let mut failed = vec![0usize];
1694        let mut successes = vec![];
1695        let mut stdin = std::io::Cursor::new(b"s\n" as &[u8]);
1696        cmd.run_interactive_retry_check(
1697            &mut failed,
1698            &repo_view,
1699            &client,
1700            None,
1701            &[],
1702            &mut successes,
1703            &mut stdin,
1704        )
1705        .await
1706        .unwrap();
1707        assert_eq!(
1708            failed,
1709            vec![0],
1710            "skip should leave failed_indices unchanged"
1711        );
1712        assert!(successes.is_empty());
1713    }
1714
1715    #[tokio::test]
1716    async fn interactive_retry_retry_succeeds() {
1717        // "r" input → retries the failed commit, which succeeds.
1718        let (commit, _tmp) = make_check_commit("abc00000");
1719        let cmd = make_check_cmd(false);
1720        let repo_view = make_check_repo_view(vec![commit]);
1721        let client = make_client(vec![Ok(check_yaml("abc00000"))]);
1722        let mut failed = vec![0usize];
1723        let mut successes = vec![];
1724        let mut stdin = std::io::Cursor::new(b"r\n" as &[u8]);
1725        cmd.run_interactive_retry_check(
1726            &mut failed,
1727            &repo_view,
1728            &client,
1729            None,
1730            &[],
1731            &mut successes,
1732            &mut stdin,
1733        )
1734        .await
1735        .unwrap();
1736        assert!(
1737            failed.is_empty(),
1738            "retry succeeded → failed_indices cleared"
1739        );
1740        assert_eq!(successes.len(), 1);
1741    }
1742
1743    #[tokio::test]
1744    async fn interactive_retry_default_input_retries() {
1745        // Empty input (just Enter) is treated as "r" (retry).
1746        let (commit, _tmp) = make_check_commit("abc00000");
1747        let cmd = make_check_cmd(false);
1748        let repo_view = make_check_repo_view(vec![commit]);
1749        let client = make_client(vec![Ok(check_yaml("abc00000"))]);
1750        let mut failed = vec![0usize];
1751        let mut successes = vec![];
1752        let mut stdin = std::io::Cursor::new(b"\n" as &[u8]);
1753        cmd.run_interactive_retry_check(
1754            &mut failed,
1755            &repo_view,
1756            &client,
1757            None,
1758            &[],
1759            &mut successes,
1760            &mut stdin,
1761        )
1762        .await
1763        .unwrap();
1764        assert!(failed.is_empty());
1765        assert_eq!(successes.len(), 1);
1766    }
1767
1768    #[tokio::test]
1769    async fn interactive_retry_still_fails_then_skip() {
1770        // "r" → retry fails → still in failed_indices → "s" → skip.
1771        let (commit, _tmp) = make_check_commit("abc00000");
1772        let cmd = make_check_cmd(false);
1773        let repo_view = make_check_repo_view(vec![commit]);
1774        // Retry fails (3 attempts), then skip.
1775        let responses = errs(3);
1776        let client = make_client(responses);
1777        let mut failed = vec![0usize];
1778        let mut successes = vec![];
1779        let mut stdin = std::io::Cursor::new(b"r\ns\n" as &[u8]);
1780        cmd.run_interactive_retry_check(
1781            &mut failed,
1782            &repo_view,
1783            &client,
1784            None,
1785            &[],
1786            &mut successes,
1787            &mut stdin,
1788        )
1789        .await
1790        .unwrap();
1791        assert_eq!(failed, vec![0], "commit still failed after retry");
1792        assert!(successes.is_empty());
1793    }
1794
1795    #[tokio::test]
1796    async fn interactive_retry_invalid_input_then_skip() {
1797        // Unrecognised input → "please enter r or s" message → "s" exits.
1798        let (commit, _tmp) = make_check_commit("abc00000");
1799        let cmd = make_check_cmd(false);
1800        let repo_view = make_check_repo_view(vec![commit]);
1801        let client = make_client(vec![]);
1802        let mut failed = vec![0usize];
1803        let mut successes = vec![];
1804        let mut stdin = std::io::Cursor::new(b"x\ns\n" as &[u8]);
1805        cmd.run_interactive_retry_check(
1806            &mut failed,
1807            &repo_view,
1808            &client,
1809            None,
1810            &[],
1811            &mut successes,
1812            &mut stdin,
1813        )
1814        .await
1815        .unwrap();
1816        assert_eq!(failed, vec![0]);
1817        assert!(successes.is_empty());
1818    }
1819
1820    #[tokio::test]
1821    async fn interactive_retry_eof_breaks_immediately() {
1822        // EOF (empty reader) → read_line returns Ok(0) → loop breaks without
1823        // calling the AI client. failed_indices stays unchanged.
1824        let (commit, _tmp) = make_check_commit("abc00000");
1825        let cmd = make_check_cmd(false);
1826        let repo_view = make_check_repo_view(vec![commit]);
1827        let client = make_client(vec![]); // no responses consumed
1828        let mut failed = vec![0usize];
1829        let mut successes = vec![];
1830        let mut stdin = std::io::Cursor::new(b"" as &[u8]);
1831        cmd.run_interactive_retry_check(
1832            &mut failed,
1833            &repo_view,
1834            &client,
1835            None,
1836            &[],
1837            &mut successes,
1838            &mut stdin,
1839        )
1840        .await
1841        .unwrap();
1842        assert_eq!(failed, vec![0], "EOF should leave failed_indices unchanged");
1843        assert!(successes.is_empty());
1844    }
1845
1846    // --- prompt_and_apply_suggestions ---
1847
1848    fn make_amendment() -> crate::data::amendments::Amendment {
1849        crate::data::amendments::Amendment {
1850            commit: "abc0000000000000000000000000000000000001".to_string(),
1851            message: "feat: improved commit message".to_string(),
1852            summary: String::new(),
1853        }
1854    }
1855
1856    #[tokio::test]
1857    async fn prompt_and_apply_suggestions_non_terminal_returns_false() {
1858        // is_terminal=false → non-interactive warning, returns Ok(false) immediately.
1859        let cmd = make_check_cmd(false);
1860        let mut reader = std::io::Cursor::new(b"" as &[u8]);
1861        let result = cmd
1862            .prompt_and_apply_suggestions(
1863                std::path::Path::new("."),
1864                vec![make_amendment()],
1865                false,
1866                &mut reader,
1867            )
1868            .await
1869            .unwrap();
1870        assert!(!result, "non-terminal should return false");
1871    }
1872
1873    #[tokio::test]
1874    async fn prompt_and_apply_suggestions_eof_returns_false() {
1875        // is_terminal=true, EOF reader → read_line returns 0, returns Ok(false).
1876        let cmd = make_check_cmd(false);
1877        let mut reader = std::io::Cursor::new(b"" as &[u8]);
1878        let result = cmd
1879            .prompt_and_apply_suggestions(
1880                std::path::Path::new("."),
1881                vec![make_amendment()],
1882                true,
1883                &mut reader,
1884            )
1885            .await
1886            .unwrap();
1887        assert!(!result, "EOF should return false");
1888    }
1889
1890    #[tokio::test]
1891    async fn prompt_and_apply_suggestions_quit_returns_false() {
1892        // is_terminal=true, "q\n" → user quits, returns Ok(false).
1893        let cmd = make_check_cmd(false);
1894        let mut reader = std::io::Cursor::new(b"q\n" as &[u8]);
1895        let result = cmd
1896            .prompt_and_apply_suggestions(
1897                std::path::Path::new("."),
1898                vec![make_amendment()],
1899                true,
1900                &mut reader,
1901            )
1902            .await
1903            .unwrap();
1904        assert!(!result, "quit should return false");
1905    }
1906
1907    #[tokio::test]
1908    async fn prompt_and_apply_suggestions_invalid_then_quit_returns_false() {
1909        // is_terminal=true, invalid input then "q\n" → prints error, then user quits.
1910        let cmd = make_check_cmd(false);
1911        let mut reader = std::io::Cursor::new(b"x\nq\n" as &[u8]);
1912        let result = cmd
1913            .prompt_and_apply_suggestions(
1914                std::path::Path::new("."),
1915                vec![make_amendment()],
1916                true,
1917                &mut reader,
1918            )
1919            .await
1920            .unwrap();
1921        assert!(!result, "invalid then quit should return false");
1922    }
1923}