Skip to main content

orch/cli/
commit.rs

1use crate::cli;
2use crate::config;
3use crate::engine::agents::truncate_at_char_boundary;
4use crate::engine::git::commit;
5use crate::engine::git::diff::parse_unified_diff_hunks;
6use crate::engine::service::control;
7use crate::sys::cmd::SyncCommandErrorContext;
8use anyhow::Context;
9use std::collections::{BTreeMap, BTreeSet};
10use std::env;
11use std::ffi::OsStr;
12use std::io::{self, Write};
13use std::iter;
14use std::path::Path;
15use std::process::Command;
16
17/// Default cap on diff bytes sent to the LLM per commit group.
18const DEFAULT_MAX_DIFF_BYTES: usize = 32 * 1024;
19
20#[derive(Debug, Clone)]
21struct ChangedFile {
22    path: String,
23    old_path: Option<String>,
24}
25
26#[derive(Debug, Clone)]
27struct CommitPlan {
28    message: String,
29    files: Vec<ChangedFile>,
30}
31
32pub async fn run(
33    dry_run: bool,
34    yes: bool,
35    message_override: Option<String>,
36    no_llm: bool,
37) -> anyhow::Result<()> {
38    ensure_git_repo()?;
39    ensure_no_merge_conflicts()?;
40
41    if !has_changes()? {
42        println!("nothing to commit");
43        return Ok(());
44    }
45
46    // Collect files and diff WITHOUT touching the index, preserving the user's staging state.
47    let files = collect_all_changed_files()?;
48    if files.is_empty() {
49        println!("nothing to commit");
50        return Ok(());
51    }
52
53    let diff_text = get_full_diff()?;
54
55    let mut plans = if let Some(message) = message_override {
56        vec![CommitPlan { message, files }]
57    } else {
58        let mut p = build_plans(files, &diff_text);
59        if !no_llm {
60            enrich_with_llm(&mut p).await;
61        }
62        p
63    };
64
65    print_plan_summary(&plans);
66
67    if dry_run {
68        // Index was never mutated — nothing to undo.
69        return Ok(());
70    }
71
72    if !yes {
73        match prompt_confirmation()? {
74            UserChoice::No => {
75                // Index was never mutated — nothing to undo.
76                println!("aborted");
77                return Ok(());
78            }
79            UserChoice::Edit => {
80                edit_messages(&mut plans)?;
81                execute(&plans).await?;
82                return Ok(());
83            }
84            UserChoice::Yes => {}
85        }
86    }
87
88    execute(&plans).await
89}
90
91/// Replace each plan's heuristic message with an LLM-drafted one.
92///
93/// On any error (no store, no agent, cooldowns, timeout) the heuristic
94/// message survives and a one-line warning is logged.
95async fn enrich_with_llm(plans: &mut [CommitPlan]) {
96    let store = match cli::init_store().await {
97        Ok(s) => s,
98        Err(e) => {
99            tracing::warn!(
100                error = %e,
101                "orch commit: could not open store for LLM message; using heuristic messages"
102            );
103            return;
104        }
105    };
106
107    let agent = match control::get_agent(&store).await {
108        Ok(a) => a,
109        Err(e) => {
110            tracing::warn!(error = %e, "orch commit: could not resolve agent; using heuristic messages");
111            return;
112        }
113    };
114    let model = match control::get_model(&store).await {
115        Ok(m) => m,
116        Err(e) => {
117            tracing::warn!(error = %e, "orch commit: could not resolve model; using heuristic messages");
118            return;
119        }
120    };
121
122    let max_bytes = resolve_max_diff_bytes();
123
124    for plan in plans.iter_mut() {
125        match draft_message_for_plan(&agent, &model, plan, max_bytes).await {
126            Ok(message) => plan.message = message,
127            Err(e) => tracing::warn!(
128                agent = %agent,
129                model = %model,
130                error = %e,
131                "orch commit: LLM draft failed, keeping heuristic message"
132            ),
133        }
134    }
135}
136
137fn resolve_max_diff_bytes() -> usize {
138    config::get("commit.max_diff_bytes")
139        .ok()
140        .and_then(|s| s.parse::<usize>().ok())
141        .filter(|n| *n > 0)
142        .unwrap_or(DEFAULT_MAX_DIFF_BYTES)
143}
144
145/// Call the agent once for this plan and return a cleaned commit message.
146async fn draft_message_for_plan(
147    agent: &str,
148    model: &str,
149    plan: &CommitPlan,
150    max_bytes: usize,
151) -> anyhow::Result<String> {
152    let paths: Vec<String> = plan
153        .files
154        .iter()
155        .flat_map(|f| iter::once(f.path.clone()).chain(f.old_path.clone()))
156        .collect();
157
158    let diff_text = diff_for_paths(&paths)?;
159    let (diff_for_prompt, truncated) = truncate_diff(&diff_text, max_bytes);
160
161    let file_list = plan
162        .files
163        .iter()
164        .map(|f| match &f.old_path {
165            Some(old) => format!("- {} -> {}", old, f.path),
166            None => format!("- {}", f.path),
167        })
168        .collect::<Vec<_>>()
169        .join("\n");
170
171    let truncated_note = if truncated {
172        format!(
173            "Note: the diff was truncated to ~{} KB to fit the budget. Base the message on the visible portion.",
174            max_bytes / 1024
175        )
176    } else {
177        String::new()
178    };
179
180    let prompt = include_str!("../../prompts/commit_message.md")
181        .replace("{{FILES}}", &file_list)
182        .replace("{{DIFF}}", &diff_for_prompt)
183        .replace("{{TRUNCATED_NOTE}}", &truncated_note);
184
185    let result = control::invoke_agent_unsandboxed(agent, model, "", &prompt).await?;
186    let cleaned = clean_llm_message(&result.text);
187    if cleaned.is_empty() {
188        anyhow::bail!("LLM returned an empty commit message");
189    }
190    Ok(cleaned)
191}
192
193/// Strip fences, leading/trailing whitespace, and obvious chatter from an LLM response.
194fn clean_llm_message(raw: &str) -> String {
195    let trimmed = raw.trim();
196
197    // Remove a leading triple-backtick fence if present (with or without a language tag).
198    let without_open_fence = if let Some(rest) = trimmed.strip_prefix("```") {
199        // Drop the rest of the opening line (language tag) up to the first newline.
200        match rest.find('\n') {
201            Some(i) => &rest[i + 1..],
202            None => rest,
203        }
204    } else {
205        trimmed
206    };
207
208    // Remove a trailing triple-backtick fence.
209    let without_close_fence = without_open_fence
210        .trim_end()
211        .strip_suffix("```")
212        .unwrap_or(without_open_fence);
213
214    without_close_fence.trim().to_string()
215}
216
217/// Truncate the diff at `max_bytes`, snapping to a UTF-8 character boundary.
218fn truncate_diff(diff: &str, max_bytes: usize) -> (String, bool) {
219    if diff.len() <= max_bytes {
220        return (diff.to_string(), false);
221    }
222    let cutoff = truncate_at_char_boundary(diff, max_bytes);
223    (diff[..cutoff].to_string(), true)
224}
225
226/// Get the combined staged + unstaged + untracked diff scoped to the given paths.
227///
228/// `git diff --cached` and `git diff` never include untracked files, so for any
229/// path returned by `git ls-files --others --exclude-standard` we synthesize a
230/// `new file` diff via `git diff --no-index /dev/null <path>`. Without this the
231/// LLM would see only the filename for brand-new files and fall back to
232/// path-only guessing — defeating the point of the LLM draft.
233///
234/// Uses default unified context (3 lines) so the LLM can see what changed
235/// in surrounding code, unlike `get_full_diff()` which uses --unified=0
236/// because it only feeds the hunk-counting heuristic.
237fn diff_for_paths(paths: &[String]) -> anyhow::Result<String> {
238    let unique: BTreeSet<String> = paths.iter().cloned().collect();
239
240    let untracked_list = git_output(["ls-files", "--others", "--exclude-standard"])?;
241    let untracked: BTreeSet<String> = untracked_list
242        .lines()
243        .map(str::trim)
244        .filter(|l| !l.is_empty())
245        .map(str::to_string)
246        .collect();
247
248    let mut staged_args: Vec<String> = vec![
249        "diff".into(),
250        "--cached".into(),
251        "--no-color".into(),
252        "--no-ext-diff".into(),
253        "--find-renames".into(),
254        "--".into(),
255    ];
256    staged_args.extend(unique.iter().cloned());
257
258    let mut unstaged_args: Vec<String> = vec![
259        "diff".into(),
260        "--no-color".into(),
261        "--no-ext-diff".into(),
262        "--find-renames".into(),
263        "--".into(),
264    ];
265    unstaged_args.extend(unique.iter().cloned());
266
267    let staged = git_output(&staged_args)?;
268    let unstaged = git_output(&unstaged_args)?;
269
270    let mut combined = format!("{staged}{unstaged}");
271    for path in unique.iter().filter(|p| untracked.contains(*p)) {
272        combined.push_str(&diff_for_untracked(path)?);
273    }
274    Ok(combined)
275}
276
277/// Produce a unified diff for an untracked file by diffing it against /dev/null.
278///
279/// `git diff --no-index` exits 1 when the files differ — that is the expected
280/// path here, since we are always comparing to an empty file. Treat exit 0 and
281/// 1 as success and surface anything else as an error.
282fn diff_for_untracked(path: &str) -> anyhow::Result<String> {
283    let out = Command::new("git")
284        .args([
285            "diff",
286            "--no-color",
287            "--no-ext-diff",
288            "--no-index",
289            "--",
290            "/dev/null",
291            path,
292        ])
293        .output_with_context()?;
294    let code = out.status.code();
295    if !matches!(code, Some(0 | 1)) {
296        anyhow::bail!(
297            "git diff --no-index -- /dev/null {path} failed (exit {:?}): {}",
298            code,
299            String::from_utf8_lossy(&out.stderr).trim()
300        );
301    }
302    Ok(String::from_utf8_lossy(&out.stdout).to_string())
303}
304
305/// shipcheck commits exactly the tree that passed, so in a shipcheck repository the groups become one commit
306async fn execute(plans: &[CommitPlan]) -> anyhow::Result<()> {
307    let dir = env::current_dir()?;
308    if commit::Tool::detect(&dir).await != commit::Tool::Shipcheck {
309        return execute_plans(plans);
310    }
311
312    let message = plans
313        .iter()
314        .map(|p| p.message.as_str())
315        .collect::<Vec<_>>()
316        .join("\n\n");
317    match commit::commit_all(&dir, &message, "orch", commit::When::Tested).await? {
318        commit::Outcome::Committed => {
319            println!("committed through shipcheck");
320            Ok(())
321        }
322        commit::Outcome::Nothing => {
323            println!("nothing to commit");
324            Ok(())
325        }
326        commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
327    }
328}
329
330fn execute_plans(plans: &[CommitPlan]) -> anyhow::Result<()> {
331    git_reset_unstage_all()?;
332
333    for plan in plans {
334        let mut path_set: BTreeSet<String> = BTreeSet::new();
335        for file in &plan.files {
336            if let Some(old) = &file.old_path {
337                path_set.insert(old.clone());
338            }
339            path_set.insert(file.path.clone());
340        }
341
342        let mut cmd = Command::new("git");
343        cmd.arg("add").arg("-A").arg("--");
344        for path in path_set {
345            cmd.arg(path);
346        }
347        let add = cmd.output_with_context()?;
348        if !add.status.success() {
349            anyhow::bail!(
350                "failed to stage commit group: {}",
351                String::from_utf8_lossy(&add.stderr).trim()
352            );
353        }
354
355        let commit = Command::new("git")
356            .args(["commit", "-m", &plan.message])
357            .output_with_context()
358            .context("failed to run git commit")?;
359        if !commit.status.success() {
360            anyhow::bail!(
361                "git commit failed: {}",
362                String::from_utf8_lossy(&commit.stderr).trim()
363            );
364        }
365    }
366
367    Ok(())
368}
369
370enum UserChoice {
371    Yes,
372    No,
373    Edit,
374}
375
376fn prompt_confirmation() -> anyhow::Result<UserChoice> {
377    print!("\nCommit these changes? [y/n/e] ");
378    io::stdout().flush().ok();
379    let mut input = String::new();
380    io::stdin().read_line(&mut input)?;
381    let value = input.trim().to_ascii_lowercase();
382    Ok(match value.as_str() {
383        "y" | "yes" => UserChoice::Yes,
384        "e" | "edit" => UserChoice::Edit,
385        _ => UserChoice::No,
386    })
387}
388
389fn edit_messages(plans: &mut [CommitPlan]) -> anyhow::Result<()> {
390    println!("\nEdit commit messages (press enter to keep current message):");
391    for (i, plan) in plans.iter_mut().enumerate() {
392        println!("\n{}. {}", i + 1, plan.message);
393        print!("new message> ");
394        io::stdout().flush().ok();
395        let mut input = String::new();
396        io::stdin().read_line(&mut input)?;
397        let next = input.trim();
398        if !next.is_empty() {
399            plan.message = next.to_string();
400        }
401    }
402    Ok(())
403}
404
405fn print_plan_summary(plans: &[CommitPlan]) {
406    let file_count: usize = plans.iter().map(|p| p.files.len()).sum();
407    println!(
408        "\nProposed {} commits from {} changed files:\n",
409        plans.len(),
410        file_count
411    );
412    for (i, plan) in plans.iter().enumerate() {
413        println!(
414            "{}. {}",
415            i + 1,
416            plan.message.lines().next().unwrap_or("commit")
417        );
418        for file in &plan.files {
419            if let Some(old) = &file.old_path {
420                println!("   - {} -> {}", old, file.path);
421            } else {
422                println!("   - {}", file.path);
423            }
424        }
425        if plan.message.lines().count() > 1 {
426            for body_line in plan.message.lines().skip(1) {
427                println!("   {body_line}");
428            }
429        }
430        println!();
431    }
432}
433
434fn build_plans(files: Vec<ChangedFile>, diff_text: &str) -> Vec<CommitPlan> {
435    let hunks = parse_unified_diff_hunks(diff_text);
436    let mut hunk_counts: BTreeMap<&str, usize> = BTreeMap::new();
437    for file in &hunks {
438        hunk_counts.insert(file.path.as_str(), file.hunks.len());
439    }
440
441    let mut groups: BTreeMap<String, Vec<ChangedFile>> = BTreeMap::new();
442
443    for file in files {
444        let key = group_key(&file.path);
445        groups.entry(key).or_default().push(file);
446    }
447
448    let mut plans = Vec::new();
449    for (_, mut grouped_files) in groups {
450        grouped_files.sort_by(|a, b| a.path.cmp(&b.path));
451        let message = message_for_group(&grouped_files, &hunk_counts);
452        plans.push(CommitPlan {
453            message,
454            files: grouped_files,
455        });
456    }
457
458    plans.sort_by(|a, b| a.message.cmp(&b.message));
459    plans
460}
461
462fn group_key(path: &str) -> String {
463    if is_doc(path) {
464        return "docs".to_string();
465    }
466    if is_config(path) {
467        return "config".to_string();
468    }
469
470    if is_test(path) {
471        if let Some(module) = test_module(path) {
472            return format!("test:{module}");
473        }
474        return "test".to_string();
475    }
476
477    let dir = Path::new(path)
478        .parent()
479        .and_then(|p| p.to_str())
480        .unwrap_or("")
481        .to_string();
482
483    if dir.is_empty() {
484        "root".to_string()
485    } else {
486        let parts: Vec<&str> = dir.split('/').collect();
487        if parts.first().copied() == Some("src") && parts.len() > 1 {
488            format!("src:{}", parts[1])
489        } else {
490            format!("dir:{dir}")
491        }
492    }
493}
494
495fn message_for_group(files: &[ChangedFile], hunk_counts: &BTreeMap<&str, usize>) -> String {
496    let paths: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
497
498    let kind = if paths.iter().all(|p| is_doc(p)) {
499        "docs"
500    } else if paths.iter().all(|p| is_test(p)) {
501        "test"
502    } else if paths.iter().all(|p| is_config(p)) {
503        "chore"
504    } else if files.iter().any(|f| f.old_path.is_some()) {
505        "refactor"
506    } else {
507        "feat"
508    };
509
510    let scope = infer_scope(&paths);
511    let subject = if files.len() == 1 {
512        format!("update {}", paths[0])
513    } else {
514        format!("update {} files", scope.as_deref().unwrap_or("project"))
515    };
516
517    let header = if let Some(scope) = &scope {
518        format!("{kind}({scope}): {subject}")
519    } else {
520        format!("{kind}: {subject}")
521    };
522
523    let total_hunks: usize = files
524        .iter()
525        .map(|f| hunk_counts.get(f.path.as_str()).copied().unwrap_or(0))
526        .sum();
527
528    if total_hunks > 3 || files.len() > 2 {
529        let mut body = String::new();
530        body.push_str("\n\nIncludes:\n");
531        for file in files {
532            body.push_str("- ");
533            body.push_str(&file.path);
534            body.push('\n');
535        }
536        format!("{header}{body}")
537    } else {
538        header
539    }
540}
541
542fn infer_scope(paths: &[&str]) -> Option<String> {
543    let first = paths.first()?;
544    let parent = Path::new(first)
545        .parent()
546        .and_then(|p| p.file_name())
547        .and_then(|n| n.to_str())
548        .map(ToString::to_string);
549
550    if paths.iter().all(|p| {
551        Path::new(p)
552            .parent()
553            .and_then(|pp| pp.file_name())
554            .and_then(|n| n.to_str())
555            .is_some_and(|s| Some(s.to_string()) == parent)
556    }) {
557        parent
558    } else {
559        None
560    }
561}
562
563fn is_doc(path: &str) -> bool {
564    Path::new(path)
565        .extension()
566        .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
567        || path.starts_with("docs/")
568}
569
570fn is_test(path: &str) -> bool {
571    path.starts_with("tests/") || path.contains("_test.") || path.ends_with(".spec.ts")
572}
573
574fn test_module(path: &str) -> Option<String> {
575    let stem = Path::new(path).file_stem()?.to_str()?;
576    Some(stem.trim_end_matches("_test").to_string())
577}
578
579fn is_config(path: &str) -> bool {
580    matches!(
581        path,
582        "Cargo.toml"
583            | "Cargo.lock"
584            | "package.json"
585            | "bun.lockb"
586            | "bun.lock"
587            | "pnpm-lock.yaml"
588            | "package-lock.json"
589    ) || path.starts_with(".github/workflows/")
590}
591
592fn ensure_git_repo() -> anyhow::Result<()> {
593    let out = Command::new("git")
594        .args(["rev-parse", "--is-inside-work-tree"])
595        .output_with_context()?;
596    if !out.status.success() {
597        anyhow::bail!("not a git repository");
598    }
599    Ok(())
600}
601
602fn ensure_no_merge_conflicts() -> anyhow::Result<()> {
603    let out = git_output(["diff", "--name-only", "--diff-filter=U"])?;
604    if !out.trim().is_empty() {
605        anyhow::bail!("merge conflicts detected; resolve conflicts before committing");
606    }
607    Ok(())
608}
609
610fn has_changes() -> anyhow::Result<bool> {
611    let unstaged = Command::new("git")
612        .args(["diff", "--quiet"])
613        .status_with_context()?;
614    let staged = Command::new("git")
615        .args(["diff", "--cached", "--quiet"])
616        .status_with_context()?;
617    let untracked = git_output(["ls-files", "--others", "--exclude-standard"])?;
618
619    Ok(!unstaged.success() || !staged.success() || !untracked.trim().is_empty())
620}
621
622fn git_reset_unstage_all() -> anyhow::Result<()> {
623    let out = Command::new("git").args(["reset"]).output_with_context()?;
624    if !out.status.success() {
625        anyhow::bail!("git reset failed: {}", String::from_utf8_lossy(&out.stderr));
626    }
627    Ok(())
628}
629
630/// Collect all changed files (staged + unstaged + untracked) without touching the index.
631fn collect_all_changed_files() -> anyhow::Result<Vec<ChangedFile>> {
632    let mut seen = BTreeSet::new();
633    let mut files = Vec::new();
634
635    let staged = git_output(["diff", "--cached", "--name-status", "--find-renames"])?;
636    for cf in parse_name_status(&staged) {
637        if seen.insert(cf.path.clone()) {
638            files.push(cf);
639        }
640    }
641
642    let unstaged = git_output(["diff", "--name-status", "--find-renames"])?;
643    for cf in parse_name_status(&unstaged) {
644        if seen.insert(cf.path.clone()) {
645            files.push(cf);
646        }
647    }
648
649    let untracked = git_output(["ls-files", "--others", "--exclude-standard"])?;
650    for line in untracked.lines().map(str::trim).filter(|l| !l.is_empty()) {
651        if seen.insert(line.to_string()) {
652            files.push(ChangedFile {
653                path: line.to_string(),
654                old_path: None,
655            });
656        }
657    }
658
659    Ok(files)
660}
661
662fn parse_name_status(output: &str) -> Vec<ChangedFile> {
663    output
664        .lines()
665        .map(str::trim)
666        .filter(|l| !l.is_empty())
667        .filter_map(parse_name_status_line)
668        .collect()
669}
670
671fn parse_name_status_line(line: &str) -> Option<ChangedFile> {
672    let parts: Vec<&str> = line.split('\t').collect();
673    let status = parts.first()?;
674    if status.starts_with('R') || status.starts_with('C') {
675        if parts.len() >= 3 {
676            Some(ChangedFile {
677                path: parts[2].to_string(),
678                old_path: Some(parts[1].to_string()),
679            })
680        } else {
681            None
682        }
683    } else if parts.len() >= 2 {
684        Some(ChangedFile {
685            path: parts[1].to_string(),
686            old_path: None,
687        })
688    } else {
689        None
690    }
691}
692
693/// Returns combined staged + unstaged diff for analysis without mutating the index.
694fn get_full_diff() -> anyhow::Result<String> {
695    let staged = git_output([
696        "diff",
697        "--cached",
698        "--no-color",
699        "--unified=0",
700        "--no-ext-diff",
701        "--find-renames",
702    ])?;
703    let unstaged = git_output([
704        "diff",
705        "--no-color",
706        "--unified=0",
707        "--no-ext-diff",
708        "--find-renames",
709    ])?;
710    Ok(format!("{staged}{unstaged}"))
711}
712
713#[cfg(test)]
714fn collect_changed_files() -> anyhow::Result<Vec<ChangedFile>> {
715    let name_status = git_output(["diff", "--cached", "--name-status", "--find-renames"])?;
716    Ok(parse_name_status(&name_status))
717}
718
719fn git_output<I, S>(args: I) -> anyhow::Result<String>
720where
721    I: IntoIterator<Item = S>,
722    S: AsRef<OsStr>,
723{
724    let args: Vec<S> = args.into_iter().collect();
725    let out = Command::new("git").args(&args).output_with_context()?;
726    if !out.status.success() {
727        let joined = args
728            .iter()
729            .map(|a| a.as_ref().to_string_lossy())
730            .collect::<Vec<_>>()
731            .join(" ");
732        anyhow::bail!("git {joined} failed");
733    }
734    Ok(String::from_utf8_lossy(&out.stdout).to_string())
735}
736
737#[cfg(test)]
738mod tests {
739    use super::{
740        ChangedFile, build_plans, collect_changed_files, git_output, parse_name_status_line, run,
741    };
742    use serial_test::serial;
743    use std::env;
744    use std::fs;
745    use std::process::Command;
746
747    fn init_temp_repo() -> tempfile::TempDir {
748        let dir = tempfile::tempdir().unwrap();
749        Command::new("git")
750            .arg("init")
751            .current_dir(dir.path())
752            .output()
753            .unwrap();
754        Command::new("git")
755            .args(["config", "user.email", "test@example.com"])
756            .current_dir(dir.path())
757            .output()
758            .unwrap();
759        Command::new("git")
760            .args(["config", "user.name", "Test User"])
761            .current_dir(dir.path())
762            .output()
763            .unwrap();
764        // The operator's global commit.gpgsign would call 1Password
765        Command::new("git")
766            .args(["config", "commit.gpgsign", "false"])
767            .current_dir(dir.path())
768            .output()
769            .unwrap();
770        fs::write(dir.path().join("README.md"), "hello\n").unwrap();
771        Command::new("git")
772            .args(["add", "."])
773            .current_dir(dir.path())
774            .output()
775            .unwrap();
776        Command::new("git")
777            .args(["commit", "-m", "init"])
778            .current_dir(dir.path())
779            .output()
780            .unwrap();
781        dir
782    }
783
784    fn assert_file(file: &ChangedFile, path: &str, old_path: Option<&str>) {
785        assert_eq!(file.path, path);
786        assert_eq!(file.old_path.as_deref(), old_path);
787    }
788
789    #[test]
790    fn groups_docs_and_code_separately() {
791        let files = vec![
792            super::ChangedFile {
793                path: "README.md".to_string(),
794                old_path: None,
795            },
796            super::ChangedFile {
797                path: "src/main.rs".to_string(),
798                old_path: None,
799            },
800        ];
801
802        let plans = build_plans(files, "");
803        assert_eq!(plans.len(), 2);
804    }
805
806    #[tokio::test]
807    #[serial]
808    async fn dry_run_works_in_temp_repo() {
809        let dir = init_temp_repo();
810        env::set_current_dir(dir.path()).unwrap();
811        fs::write(dir.path().join("src.rs"), "fn main() {}\n").unwrap();
812
813        run(true, true, None, true).await.unwrap();
814
815        let log = git_output(["log", "--oneline", "-1"]).unwrap();
816        assert!(log.contains("init"));
817    }
818
819    #[tokio::test]
820    #[serial]
821    async fn commits_in_temp_repo_with_yes() {
822        let dir = init_temp_repo();
823        env::set_current_dir(dir.path()).unwrap();
824        fs::write(dir.path().join("notes.md"), "updated\n").unwrap();
825
826        run(false, true, None, true).await.unwrap();
827
828        let count = Command::new("git")
829            .args(["rev-list", "--count", "HEAD"])
830            .current_dir(dir.path())
831            .output()
832            .unwrap();
833        let count = String::from_utf8_lossy(&count.stdout)
834            .trim()
835            .parse::<u32>()
836            .unwrap();
837        assert!(count >= 2);
838    }
839
840    #[tokio::test]
841    #[serial]
842    async fn message_override_skips_llm_and_commits_once() {
843        let dir = init_temp_repo();
844        env::set_current_dir(dir.path()).unwrap();
845        fs::write(dir.path().join("a.txt"), "a\n").unwrap();
846        fs::write(dir.path().join("b.md"), "b\n").unwrap();
847
848        // no_llm=false on purpose — the override must take priority over the LLM path.
849        run(
850            false,
851            true,
852            Some("chore: forced override".to_string()),
853            false,
854        )
855        .await
856        .unwrap();
857
858        let log = git_output(["log", "--oneline", "-1"]).unwrap();
859        assert!(
860            log.contains("chore: forced override"),
861            "expected override message in HEAD, got: {log}"
862        );
863    }
864
865    #[test]
866    #[serial]
867    fn parses_name_status() {
868        let dir = init_temp_repo();
869        env::set_current_dir(dir.path()).unwrap();
870        fs::write(dir.path().join("x.txt"), "a\n").unwrap();
871        Command::new("git")
872            .args(["add", "-A"])
873            .current_dir(dir.path())
874            .output()
875            .unwrap();
876        let files = collect_changed_files().unwrap();
877        assert!(files.iter().any(|f| f.path == "x.txt"));
878    }
879
880    #[test]
881    fn parse_name_status_line_covers_git_status_codes() {
882        assert_file(
883            &parse_name_status_line("M\tsrc/a.rs").unwrap(),
884            "src/a.rs",
885            None,
886        );
887        assert_file(
888            &parse_name_status_line("A\tnew.txt").unwrap(),
889            "new.txt",
890            None,
891        );
892        assert_file(
893            &parse_name_status_line("D\told.txt").unwrap(),
894            "old.txt",
895            None,
896        );
897        assert_file(
898            &parse_name_status_line("R100\told.rs\tnew.rs").unwrap(),
899            "new.rs",
900            Some("old.rs"),
901        );
902        assert_file(
903            &parse_name_status_line("C75\tsrc\tdst").unwrap(),
904            "dst",
905            Some("src"),
906        );
907        assert!(parse_name_status_line("R100\tonly-old").is_none());
908        assert!(parse_name_status_line("C\tonly-old").is_none());
909        assert!(parse_name_status_line("M").is_none());
910        assert!(parse_name_status_line("").is_none());
911    }
912
913    #[test]
914    fn git_output_error_joins_the_failed_args() {
915        let err = git_output(["rev-parse", "--verify", "orch-refactor-missing-ref"])
916            .unwrap_err()
917            .to_string();
918        assert!(
919            err.contains("git rev-parse --verify orch-refactor-missing-ref failed"),
920            "{err}"
921        );
922    }
923
924    #[test]
925    fn git_output_error_joins_vec_args() {
926        let err = git_output([
927            "rev-parse".to_string(),
928            "--verify".to_string(),
929            "orch-refactor-missing-ref".to_string(),
930        ])
931        .unwrap_err()
932        .to_string();
933        assert!(
934            err.contains("git rev-parse --verify orch-refactor-missing-ref failed"),
935            "{err}"
936        );
937    }
938
939    #[test]
940    fn clean_llm_message_strips_fences_and_whitespace() {
941        let raw = "```\nfeat(cli): add --no-llm flag\n\nLet users opt out of LLM-drafted messages.\n```\n";
942        let cleaned = super::clean_llm_message(raw);
943        assert_eq!(
944            cleaned,
945            "feat(cli): add --no-llm flag\n\nLet users opt out of LLM-drafted messages."
946        );
947    }
948
949    #[test]
950    fn clean_llm_message_strips_language_tagged_fence() {
951        let raw = "```text\nfix(router): handle empty pool\n```";
952        let cleaned = super::clean_llm_message(raw);
953        assert_eq!(cleaned, "fix(router): handle empty pool");
954    }
955
956    #[test]
957    fn clean_llm_message_passes_plain_text_through() {
958        let cleaned = super::clean_llm_message("  docs: clarify usage  \n\n");
959        assert_eq!(cleaned, "docs: clarify usage");
960    }
961
962    #[test]
963    fn truncate_diff_no_op_when_under_budget() {
964        let diff = "diff --git a/x b/x\n+hello\n";
965        let (out, truncated) = super::truncate_diff(diff, 1024);
966        assert!(!truncated);
967        assert_eq!(out, diff);
968    }
969
970    #[test]
971    fn truncate_diff_snaps_to_char_boundary() {
972        let diff = "héllo wörld"; // multi-byte chars in the middle
973        let (out, truncated) = super::truncate_diff(diff, 5);
974        assert!(truncated);
975        // out must be valid UTF-8 and never split a multi-byte char.
976        assert!(out.chars().count() > 0);
977        assert!(diff.starts_with(&out));
978    }
979
980    #[test]
981    fn truncate_diff_keeps_input_at_exact_limit_and_cuts_inside_char() {
982        let (out, truncated) = super::truncate_diff("héllo", 6);
983        assert!(!truncated);
984        assert_eq!(out, "héllo");
985
986        let (out, truncated) = super::truncate_diff("héllo", 2);
987        assert!(truncated);
988        assert_eq!(out, "h");
989
990        let (out, truncated) = super::truncate_diff("é", 1);
991        assert!(truncated);
992        assert_eq!(out, "");
993    }
994
995    #[test]
996    #[serial]
997    fn diff_for_paths_includes_untracked_file_contents() {
998        let dir = init_temp_repo();
999        env::set_current_dir(dir.path()).unwrap();
1000        // Brand-new file: never staged, never tracked. The LLM path must still
1001        // see its contents — otherwise the message would be drafted from the
1002        // filename alone, which is exactly the regression this guards against.
1003        fs::write(dir.path().join("brand_new.txt"), "alpha\nbeta\ngamma\n").unwrap();
1004
1005        let diff = super::diff_for_paths(&["brand_new.txt".to_string()]).unwrap();
1006        assert!(
1007            diff.contains("brand_new.txt"),
1008            "diff should reference the new file path, got: {diff}"
1009        );
1010        assert!(
1011            diff.contains("+alpha") && diff.contains("+beta") && diff.contains("+gamma"),
1012            "diff should include the new file's added lines, got: {diff}"
1013        );
1014    }
1015}