1use crate::cli;
2use crate::config;
3use crate::engine::agents::truncate_str;
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
17const 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 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 return Ok(());
70 }
71
72 if !yes {
73 match prompt_confirmation()? {
74 UserChoice::No => {
75 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
91async 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
145async 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
193fn clean_llm_message(raw: &str) -> String {
195 let trimmed = raw.trim();
196
197 let without_open_fence = if let Some(rest) = trimmed.strip_prefix("```") {
199 match rest.find('\n') {
201 Some(i) => &rest[i + 1..],
202 None => rest,
203 }
204 } else {
205 trimmed
206 };
207
208 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
217fn truncate_diff(diff: &str, max_bytes: usize) -> (String, bool) {
219 if diff.len() <= max_bytes {
220 return (diff.to_string(), false);
221 }
222 (truncate_str(diff, max_bytes).to_string(), true)
223}
224
225fn 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 = git_output(&staged_args)?;
267 let unstaged = git_output(&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
276fn 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
304async fn execute(plans: &[CommitPlan]) -> anyhow::Result<()> {
306 let dir = env::current_dir()?;
307 if commit::Tool::detect(&dir).await != commit::Tool::Shipcheck {
308 return execute_plans(plans);
309 }
310
311 let message = plans
312 .iter()
313 .map(|p| p.message.as_str())
314 .collect::<Vec<_>>()
315 .join("\n\n");
316 match commit::commit_all(&dir, &message, "orch", commit::When::Tested).await? {
317 commit::Outcome::Committed { .. } => {
318 println!("committed through shipcheck");
319 Ok(())
320 }
321 commit::Outcome::Nothing { .. } => {
322 println!("nothing to commit");
323 Ok(())
324 }
325 commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
326 }
327}
328
329fn execute_plans(plans: &[CommitPlan]) -> anyhow::Result<()> {
330 git_reset_unstage_all()?;
331
332 for plan in plans {
333 let mut path_set: BTreeSet<String> = BTreeSet::new();
334 for file in &plan.files {
335 if let Some(old) = &file.old_path {
336 path_set.insert(old.clone());
337 }
338 path_set.insert(file.path.clone());
339 }
340
341 let mut cmd = Command::new("git");
342 cmd.arg("add").arg("-A").arg("--");
343 for path in path_set {
344 cmd.arg(path);
345 }
346 let add = cmd.output_with_context()?;
347 if !add.status.success() {
348 anyhow::bail!(
349 "failed to stage commit group: {}",
350 String::from_utf8_lossy(&add.stderr).trim()
351 );
352 }
353
354 let commit = Command::new("git")
355 .args(["commit", "-m", &plan.message])
356 .output_with_context()
357 .context("failed to run git commit")?;
358 if !commit.status.success() {
359 anyhow::bail!(
360 "git commit failed: {}",
361 String::from_utf8_lossy(&commit.stderr).trim()
362 );
363 }
364 }
365
366 Ok(())
367}
368
369enum UserChoice {
370 Yes,
371 No,
372 Edit,
373}
374
375fn prompt_confirmation() -> anyhow::Result<UserChoice> {
376 print!("\nCommit these changes? [y/n/e] ");
377 io::stdout().flush().ok();
378 let mut input = String::new();
379 io::stdin().read_line(&mut input)?;
380 let value = input.trim().to_ascii_lowercase();
381 Ok(match value.as_str() {
382 "y" | "yes" => UserChoice::Yes,
383 "e" | "edit" => UserChoice::Edit,
384 _ => UserChoice::No,
385 })
386}
387
388fn edit_messages(plans: &mut [CommitPlan]) -> anyhow::Result<()> {
389 println!("\nEdit commit messages (press enter to keep current message):");
390 for (i, plan) in plans.iter_mut().enumerate() {
391 println!("\n{}. {}", i + 1, plan.message);
392 print!("new message> ");
393 io::stdout().flush().ok();
394 let mut input = String::new();
395 io::stdin().read_line(&mut input)?;
396 let next = input.trim();
397 if !next.is_empty() {
398 plan.message = next.to_string();
399 }
400 }
401 Ok(())
402}
403
404fn print_plan_summary(plans: &[CommitPlan]) {
405 let file_count: usize = plans.iter().map(|p| p.files.len()).sum();
406 println!(
407 "\nProposed {} commits from {} changed files:\n",
408 plans.len(),
409 file_count
410 );
411 for (i, plan) in plans.iter().enumerate() {
412 println!(
413 "{}. {}",
414 i + 1,
415 plan.message.lines().next().unwrap_or("commit")
416 );
417 for file in &plan.files {
418 if let Some(old) = &file.old_path {
419 println!(" - {} -> {}", old, file.path);
420 } else {
421 println!(" - {}", file.path);
422 }
423 }
424 if plan.message.lines().count() > 1 {
425 for body_line in plan.message.lines().skip(1) {
426 println!(" {body_line}");
427 }
428 }
429 println!();
430 }
431}
432
433fn build_plans(files: Vec<ChangedFile>, diff_text: &str) -> Vec<CommitPlan> {
434 let hunks = parse_unified_diff_hunks(diff_text);
435 let mut hunk_counts: BTreeMap<&str, usize> = BTreeMap::new();
436 for file in &hunks {
437 hunk_counts.insert(file.path.as_str(), file.hunks.len());
438 }
439
440 let mut groups: BTreeMap<String, Vec<ChangedFile>> = BTreeMap::new();
441
442 for file in files {
443 let key = group_key(&file.path);
444 groups.entry(key).or_default().push(file);
445 }
446
447 let mut plans = Vec::new();
448 for (_, mut grouped_files) in groups {
449 grouped_files.sort_by(|a, b| a.path.cmp(&b.path));
450 let message = message_for_group(&grouped_files, &hunk_counts);
451 plans.push(CommitPlan {
452 message,
453 files: grouped_files,
454 });
455 }
456
457 plans.sort_by(|a, b| a.message.cmp(&b.message));
458 plans
459}
460
461fn group_key(path: &str) -> String {
462 if is_doc(path) {
463 return "docs".to_string();
464 }
465 if is_config(path) {
466 return "config".to_string();
467 }
468
469 if is_test(path) {
470 if let Some(module) = test_module(path) {
471 return format!("test:{module}");
472 }
473 return "test".to_string();
474 }
475
476 let dir = Path::new(path)
477 .parent()
478 .and_then(|p| p.to_str())
479 .unwrap_or("")
480 .to_string();
481
482 if dir.is_empty() {
483 "root".to_string()
484 } else {
485 let parts: Vec<&str> = dir.split('/').collect();
486 if parts.first().copied() == Some("src") && parts.len() > 1 {
487 format!("src:{}", parts[1])
488 } else {
489 format!("dir:{dir}")
490 }
491 }
492}
493
494fn message_for_group(files: &[ChangedFile], hunk_counts: &BTreeMap<&str, usize>) -> String {
495 let paths: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
496
497 let kind = if paths.iter().all(|p| is_doc(p)) {
498 "docs"
499 } else if paths.iter().all(|p| is_test(p)) {
500 "test"
501 } else if paths.iter().all(|p| is_config(p)) {
502 "chore"
503 } else if files.iter().any(|f| f.old_path.is_some()) {
504 "refactor"
505 } else {
506 "feat"
507 };
508
509 let scope = infer_scope(&paths);
510 let subject = if files.len() == 1 {
511 format!("update {}", paths[0])
512 } else {
513 format!("update {} files", scope.as_deref().unwrap_or("project"))
514 };
515
516 let header = if let Some(scope) = &scope {
517 format!("{kind}({scope}): {subject}")
518 } else {
519 format!("{kind}: {subject}")
520 };
521
522 let total_hunks: usize = files
523 .iter()
524 .map(|f| hunk_counts.get(f.path.as_str()).copied().unwrap_or(0))
525 .sum();
526
527 if total_hunks > 3 || files.len() > 2 {
528 let mut body = String::new();
529 body.push_str("\n\nIncludes:\n");
530 for file in files {
531 body.push_str("- ");
532 body.push_str(&file.path);
533 body.push('\n');
534 }
535 format!("{header}{body}")
536 } else {
537 header
538 }
539}
540
541fn infer_scope(paths: &[&str]) -> Option<String> {
542 let first = paths.first()?;
543 let parent = Path::new(first)
544 .parent()
545 .and_then(|p| p.file_name())
546 .and_then(|n| n.to_str())
547 .map(ToString::to_string);
548
549 if paths.iter().all(|p| {
550 Path::new(p)
551 .parent()
552 .and_then(|pp| pp.file_name())
553 .and_then(|n| n.to_str())
554 .is_some_and(|s| Some(s.to_string()) == parent)
555 }) {
556 parent
557 } else {
558 None
559 }
560}
561
562fn is_doc(path: &str) -> bool {
563 Path::new(path)
564 .extension()
565 .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
566 || path.starts_with("docs/")
567}
568
569fn is_test(path: &str) -> bool {
570 path.starts_with("tests/") || path.contains("_test.") || path.ends_with(".spec.ts")
571}
572
573fn test_module(path: &str) -> Option<String> {
574 let stem = Path::new(path).file_stem()?.to_str()?;
575 Some(stem.trim_end_matches("_test").to_string())
576}
577
578fn is_config(path: &str) -> bool {
579 matches!(
580 path,
581 "Cargo.toml"
582 | "Cargo.lock"
583 | "package.json"
584 | "bun.lockb"
585 | "bun.lock"
586 | "pnpm-lock.yaml"
587 | "package-lock.json"
588 ) || path.starts_with(".github/workflows/")
589}
590
591fn ensure_git_repo() -> anyhow::Result<()> {
592 let out = Command::new("git")
593 .args(["rev-parse", "--is-inside-work-tree"])
594 .output_with_context()?;
595 if !out.status.success() {
596 anyhow::bail!("not a git repository");
597 }
598 Ok(())
599}
600
601fn ensure_no_merge_conflicts() -> anyhow::Result<()> {
602 let out = git_output(["diff", "--name-only", "--diff-filter=U"])?;
603 if !out.trim().is_empty() {
604 anyhow::bail!("merge conflicts detected; resolve conflicts before committing");
605 }
606 Ok(())
607}
608
609fn has_changes() -> anyhow::Result<bool> {
610 let unstaged = Command::new("git")
611 .args(["diff", "--quiet"])
612 .status_with_context()?;
613 let staged = Command::new("git")
614 .args(["diff", "--cached", "--quiet"])
615 .status_with_context()?;
616 let untracked = git_output(["ls-files", "--others", "--exclude-standard"])?;
617
618 Ok(!unstaged.success() || !staged.success() || !untracked.trim().is_empty())
619}
620
621fn git_reset_unstage_all() -> anyhow::Result<()> {
622 let out = Command::new("git").args(["reset"]).output_with_context()?;
623 if !out.status.success() {
624 anyhow::bail!("git reset failed: {}", String::from_utf8_lossy(&out.stderr));
625 }
626 Ok(())
627}
628
629fn collect_all_changed_files() -> anyhow::Result<Vec<ChangedFile>> {
631 let mut seen = BTreeSet::new();
632 let mut files = Vec::new();
633
634 let staged = git_output(["diff", "--cached", "--name-status", "--find-renames"])?;
635 for cf in parse_name_status(&staged) {
636 if seen.insert(cf.path.clone()) {
637 files.push(cf);
638 }
639 }
640
641 let unstaged = git_output(["diff", "--name-status", "--find-renames"])?;
642 for cf in parse_name_status(&unstaged) {
643 if seen.insert(cf.path.clone()) {
644 files.push(cf);
645 }
646 }
647
648 let untracked = git_output(["ls-files", "--others", "--exclude-standard"])?;
649 for line in untracked.lines().map(str::trim).filter(|l| !l.is_empty()) {
650 if seen.insert(line.to_string()) {
651 files.push(ChangedFile {
652 path: line.to_string(),
653 old_path: None,
654 });
655 }
656 }
657
658 Ok(files)
659}
660
661fn parse_name_status(output: &str) -> Vec<ChangedFile> {
662 output
663 .lines()
664 .map(str::trim)
665 .filter(|l| !l.is_empty())
666 .filter_map(parse_name_status_line)
667 .collect()
668}
669
670fn parse_name_status_line(line: &str) -> Option<ChangedFile> {
671 let parts: Vec<&str> = line.split('\t').collect();
672 let status = parts.first()?;
673 if status.starts_with('R') || status.starts_with('C') {
674 if parts.len() >= 3 {
675 Some(ChangedFile {
676 path: parts[2].to_string(),
677 old_path: Some(parts[1].to_string()),
678 })
679 } else {
680 None
681 }
682 } else if parts.len() >= 2 {
683 Some(ChangedFile {
684 path: parts[1].to_string(),
685 old_path: None,
686 })
687 } else {
688 None
689 }
690}
691
692fn get_full_diff() -> anyhow::Result<String> {
694 let staged = git_output([
695 "diff",
696 "--cached",
697 "--no-color",
698 "--unified=0",
699 "--no-ext-diff",
700 "--find-renames",
701 ])?;
702 let unstaged = git_output([
703 "diff",
704 "--no-color",
705 "--unified=0",
706 "--no-ext-diff",
707 "--find-renames",
708 ])?;
709 Ok(format!("{staged}{unstaged}"))
710}
711
712#[cfg(test)]
713fn collect_changed_files() -> anyhow::Result<Vec<ChangedFile>> {
714 let name_status = git_output(["diff", "--cached", "--name-status", "--find-renames"])?;
715 Ok(parse_name_status(&name_status))
716}
717
718fn git_output<I, S>(args: I) -> anyhow::Result<String>
719where
720 I: IntoIterator<Item = S>,
721 S: AsRef<OsStr>,
722{
723 let args: Vec<S> = args.into_iter().collect();
724 let out = Command::new("git").args(&args).output_with_context()?;
725 if !out.status.success() {
726 let joined = args
727 .iter()
728 .map(|a| a.as_ref().to_string_lossy())
729 .collect::<Vec<_>>()
730 .join(" ");
731 anyhow::bail!("git {joined} failed");
732 }
733 Ok(String::from_utf8_lossy(&out.stdout).to_string())
734}
735
736#[cfg(test)]
737mod tests {
738 use super::{
739 ChangedFile, build_plans, collect_changed_files, git_output, parse_name_status_line, run,
740 };
741 use serial_test::serial;
742 use std::env;
743 use std::fs;
744 use std::process::Command;
745
746 fn init_temp_repo() -> tempfile::TempDir {
747 let dir = tempfile::tempdir().unwrap();
748 Command::new("git")
749 .arg("init")
750 .current_dir(dir.path())
751 .output()
752 .unwrap();
753 Command::new("git")
754 .args(["config", "user.email", "test@example.com"])
755 .current_dir(dir.path())
756 .output()
757 .unwrap();
758 Command::new("git")
759 .args(["config", "user.name", "Test User"])
760 .current_dir(dir.path())
761 .output()
762 .unwrap();
763 Command::new("git")
765 .args(["config", "commit.gpgsign", "false"])
766 .current_dir(dir.path())
767 .output()
768 .unwrap();
769 fs::write(dir.path().join("README.md"), "hello\n").unwrap();
770 Command::new("git")
771 .args(["add", "."])
772 .current_dir(dir.path())
773 .output()
774 .unwrap();
775 Command::new("git")
776 .args(["commit", "-m", "init"])
777 .current_dir(dir.path())
778 .output()
779 .unwrap();
780 dir
781 }
782
783 fn assert_file(file: &ChangedFile, path: &str, old_path: Option<&str>) {
784 assert_eq!(file.path, path);
785 assert_eq!(file.old_path.as_deref(), old_path);
786 }
787
788 #[test]
789 fn groups_docs_and_code_separately() {
790 let files = vec![
791 super::ChangedFile {
792 path: "README.md".to_string(),
793 old_path: None,
794 },
795 super::ChangedFile {
796 path: "src/main.rs".to_string(),
797 old_path: None,
798 },
799 ];
800
801 let plans = build_plans(files, "");
802 assert_eq!(plans.len(), 2);
803 }
804
805 #[tokio::test]
806 #[serial]
807 async fn dry_run_works_in_temp_repo() {
808 let dir = init_temp_repo();
809 env::set_current_dir(dir.path()).unwrap();
810 fs::write(dir.path().join("src.rs"), "fn main() {}\n").unwrap();
811
812 run(true, true, None, true).await.unwrap();
813
814 let log = git_output(["log", "--oneline", "-1"]).unwrap();
815 assert!(log.contains("init"));
816 }
817
818 #[tokio::test]
819 #[serial]
820 async fn commits_in_temp_repo_with_yes() {
821 let dir = init_temp_repo();
822 env::set_current_dir(dir.path()).unwrap();
823 fs::write(dir.path().join("notes.md"), "updated\n").unwrap();
824
825 run(false, true, None, true).await.unwrap();
826
827 let count = Command::new("git")
828 .args(["rev-list", "--count", "HEAD"])
829 .current_dir(dir.path())
830 .output()
831 .unwrap();
832 let count = String::from_utf8_lossy(&count.stdout)
833 .trim()
834 .parse::<u32>()
835 .unwrap();
836 assert!(count >= 2);
837 }
838
839 #[tokio::test]
840 #[serial]
841 async fn message_override_skips_llm_and_commits_once() {
842 let dir = init_temp_repo();
843 env::set_current_dir(dir.path()).unwrap();
844 fs::write(dir.path().join("a.txt"), "a\n").unwrap();
845 fs::write(dir.path().join("b.md"), "b\n").unwrap();
846
847 run(
849 false,
850 true,
851 Some("chore: forced override".to_string()),
852 false,
853 )
854 .await
855 .unwrap();
856
857 let log = git_output(["log", "--oneline", "-1"]).unwrap();
858 assert!(
859 log.contains("chore: forced override"),
860 "expected override message in HEAD, got: {log}"
861 );
862 }
863
864 #[test]
865 #[serial]
866 fn parses_name_status() {
867 let dir = init_temp_repo();
868 env::set_current_dir(dir.path()).unwrap();
869 fs::write(dir.path().join("x.txt"), "a\n").unwrap();
870 Command::new("git")
871 .args(["add", "-A"])
872 .current_dir(dir.path())
873 .output()
874 .unwrap();
875 let files = collect_changed_files().unwrap();
876 assert!(files.iter().any(|f| f.path == "x.txt"));
877 }
878
879 #[test]
880 fn parse_name_status_line_covers_git_status_codes() {
881 assert_file(
882 &parse_name_status_line("M\tsrc/a.rs").unwrap(),
883 "src/a.rs",
884 None,
885 );
886 assert_file(
887 &parse_name_status_line("A\tnew.txt").unwrap(),
888 "new.txt",
889 None,
890 );
891 assert_file(
892 &parse_name_status_line("D\told.txt").unwrap(),
893 "old.txt",
894 None,
895 );
896 assert_file(
897 &parse_name_status_line("R100\told.rs\tnew.rs").unwrap(),
898 "new.rs",
899 Some("old.rs"),
900 );
901 assert_file(
902 &parse_name_status_line("C75\tsrc\tdst").unwrap(),
903 "dst",
904 Some("src"),
905 );
906 assert!(parse_name_status_line("R100\tonly-old").is_none());
907 assert!(parse_name_status_line("C\tonly-old").is_none());
908 assert!(parse_name_status_line("M").is_none());
909 assert!(parse_name_status_line("").is_none());
910 }
911
912 #[test]
913 fn git_output_error_joins_the_failed_args() {
914 let err = git_output(["rev-parse", "--verify", "orch-refactor-missing-ref"])
915 .unwrap_err()
916 .to_string();
917 assert!(
918 err.contains("git rev-parse --verify orch-refactor-missing-ref failed"),
919 "{err}"
920 );
921 }
922
923 #[test]
924 fn git_output_error_joins_vec_args() {
925 let err = git_output([
926 "rev-parse".to_string(),
927 "--verify".to_string(),
928 "orch-refactor-missing-ref".to_string(),
929 ])
930 .unwrap_err()
931 .to_string();
932 assert!(
933 err.contains("git rev-parse --verify orch-refactor-missing-ref failed"),
934 "{err}"
935 );
936 }
937
938 #[test]
939 fn clean_llm_message_strips_fences_and_whitespace() {
940 let raw = "```\nfeat(cli): add --no-llm flag\n\nLet users opt out of LLM-drafted messages.\n```\n";
941 let cleaned = super::clean_llm_message(raw);
942 assert_eq!(
943 cleaned,
944 "feat(cli): add --no-llm flag\n\nLet users opt out of LLM-drafted messages."
945 );
946 }
947
948 #[test]
949 fn clean_llm_message_strips_language_tagged_fence() {
950 let raw = "```text\nfix(router): handle empty pool\n```";
951 let cleaned = super::clean_llm_message(raw);
952 assert_eq!(cleaned, "fix(router): handle empty pool");
953 }
954
955 #[test]
956 fn clean_llm_message_passes_plain_text_through() {
957 let cleaned = super::clean_llm_message(" docs: clarify usage \n\n");
958 assert_eq!(cleaned, "docs: clarify usage");
959 }
960
961 #[test]
962 fn truncate_diff_no_op_when_under_budget() {
963 let diff = "diff --git a/x b/x\n+hello\n";
964 let (out, truncated) = super::truncate_diff(diff, 1024);
965 assert!(!truncated);
966 assert_eq!(out, diff);
967 }
968
969 #[test]
970 fn truncate_diff_snaps_to_char_boundary() {
971 let diff = "héllo wörld"; let (out, truncated) = super::truncate_diff(diff, 5);
973 assert!(truncated);
974 assert!(out.chars().count() > 0);
976 assert!(diff.starts_with(&out));
977 }
978
979 #[test]
980 fn truncate_diff_keeps_input_at_exact_limit_and_cuts_inside_char() {
981 let (out, truncated) = super::truncate_diff("héllo", 6);
982 assert!(!truncated);
983 assert_eq!(out, "héllo");
984
985 let (out, truncated) = super::truncate_diff("héllo", 2);
986 assert!(truncated);
987 assert_eq!(out, "h");
988
989 let (out, truncated) = super::truncate_diff("é", 1);
990 assert!(truncated);
991 assert_eq!(out, "");
992 }
993
994 #[test]
995 #[serial]
996 fn diff_for_paths_includes_untracked_file_contents() {
997 let dir = init_temp_repo();
998 env::set_current_dir(dir.path()).unwrap();
999 fs::write(dir.path().join("brand_new.txt"), "alpha\nbeta\ngamma\n").unwrap();
1003
1004 let diff = super::diff_for_paths(&["brand_new.txt".to_string()]).unwrap();
1005 assert!(
1006 diff.contains("brand_new.txt"),
1007 "diff should reference the new file path, got: {diff}"
1008 );
1009 assert!(
1010 diff.contains("+alpha") && diff.contains("+beta") && diff.contains("+gamma"),
1011 "diff should include the new file's added lines, got: {diff}"
1012 );
1013 }
1014}