Skip to main content

orch/cli/
commit.rs

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