worktrunk 0.37.1

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
use anyhow::Context;
use color_print::cformat;
use shell_escape::escape;
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use worktrunk::config::CommitGenerationConfig;
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::shell_exec::{Cmd, SUBPROCESS_FULL_TARGET, ShellConfig};
use worktrunk::styling::{eprintln, warning_message};

use minijinja::Environment;

/// Characters that require shell wrapping when used in a command.
/// If a command contains any of these, it needs `sh -c '...'` to execute correctly.
const SHELL_METACHARACTERS: &[char] = &[
    '&', '|', ';', '<', '>', '$', '`', '\'', '"', '(', ')', '{', '}', '*', '?', '[', ']', '~', '!',
    '\\',
];

/// Format a reproduction command, only wrapping with `sh -c` if needed.
///
/// Simple commands like `llm -m haiku` are shown as-is.
/// Complex commands with shell syntax are wrapped: `sh -c 'complex && command'`
fn format_reproduction_command(base_cmd: &str, llm_command: &str) -> String {
    let needs_shell = llm_command.contains(SHELL_METACHARACTERS)
        || llm_command
            .split_whitespace()
            .next()
            .is_some_and(|first| first.contains('='));

    if needs_shell {
        format!(
            "{} | sh -c {}",
            base_cmd,
            escape(Cow::Borrowed(llm_command))
        )
    } else {
        format!("{} | {}", base_cmd, llm_command)
    }
}

/// Track whether template-file deprecation warning has been shown this session
static TEMPLATE_FILE_WARNING_SHOWN: AtomicBool = AtomicBool::new(false);

/// Maximum diff size in characters before filtering kicks in
const DIFF_SIZE_THRESHOLD: usize = 400_000;

/// Maximum lines per file after truncation
const MAX_LINES_PER_FILE: usize = 50;

/// Maximum number of files to include after truncation
const MAX_FILES: usize = 50;

/// Lock file patterns that are filtered out when diff is too large
const LOCK_FILE_PATTERNS: &[&str] = &[".lock", "-lock.json", "-lock.yaml", ".lock.hcl"];

/// Prepared diff output with optional filtering applied
pub(crate) struct PreparedDiff {
    /// The diff content (possibly filtered/truncated)
    pub(crate) diff: String,
    /// The diffstat output
    pub(crate) stat: String,
}

/// Check if a filename matches lock file patterns
fn is_lock_file(filename: &str) -> bool {
    LOCK_FILE_PATTERNS
        .iter()
        .any(|pattern| filename.ends_with(pattern))
}

/// Parse a diff into individual file sections
///
/// Returns Vec of (filename, diff_content) pairs
fn parse_diff_sections(diff: &str) -> Vec<(&str, &str)> {
    let mut sections = Vec::new();
    let mut current_file: Option<&str> = None;
    let mut section_start_byte = 0;
    let mut current_byte = 0;

    for line in diff.lines() {
        if line.starts_with("diff --git ") {
            // Save previous section
            if let Some(file) = current_file
                && current_byte > section_start_byte
            {
                sections.push((file, &diff[section_start_byte..current_byte]));
            }

            // Extract filename from "diff --git a/path b/path"
            current_file = line.split(" b/").nth(1);
            section_start_byte = current_byte;
        }
        current_byte += line.len() + 1; // +1 for newline
    }

    // Save final section
    if let Some(file) = current_file
        && section_start_byte < diff.len()
    {
        sections.push((file, &diff[section_start_byte..]));
    }

    sections
}

/// Truncate a diff section to max lines, keeping the header
fn truncate_diff_section(section: &str, max_lines: usize) -> String {
    let lines: Vec<&str> = section.lines().collect();
    if lines.len() <= max_lines {
        return section.to_string();
    }

    // Find where the actual diff content starts (after the @@ line)
    let header_end = lines.iter().position(|l| l.starts_with("@@")).unwrap_or(0);
    let header_lines = header_end + 1; // Include the first @@ line

    let content_lines = max_lines.saturating_sub(header_lines);
    let total_lines = header_lines + content_lines;

    let mut result: String = lines
        .iter()
        .take(total_lines)
        .map(|l| format!("{}\n", l))
        .collect();
    let omitted = lines.len() - total_lines;
    if omitted > 0 {
        result.push_str(&format!("\n... ({} lines omitted)\n", omitted));
    }

    result
}

/// Prepare diff for LLM consumption, applying filtering if needed
pub(crate) fn prepare_diff(diff: String, stat: String) -> PreparedDiff {
    // If under threshold, pass through unchanged
    if diff.len() < DIFF_SIZE_THRESHOLD {
        return PreparedDiff { diff, stat };
    }

    log::debug!(
        "Diff size ({} chars) exceeds threshold ({}), filtering",
        diff.len(),
        DIFF_SIZE_THRESHOLD
    );

    // Step 1: Filter out lock files
    let sections = parse_diff_sections(&diff);
    let filtered_sections: Vec<_> = sections
        .iter()
        .filter(|(filename, _)| !is_lock_file(filename))
        .collect();

    let lock_files_removed = sections.len() - filtered_sections.len();
    if lock_files_removed > 0 {
        log::debug!("Filtered out {} lock file(s)", lock_files_removed);
    }

    let filtered_diff: String = filtered_sections
        .iter()
        .map(|(_, content)| *content)
        .collect();

    // If filtering lock files brought us under threshold, we're done
    if filtered_diff.len() < DIFF_SIZE_THRESHOLD {
        return PreparedDiff {
            diff: filtered_diff,
            stat,
        };
    }

    // Step 2: Truncate each file and limit file count
    log::debug!(
        "Still too large ({} chars), truncating to {} lines/file, {} files max",
        filtered_diff.len(),
        MAX_LINES_PER_FILE,
        MAX_FILES
    );

    let truncated: String = filtered_sections
        .iter()
        .take(MAX_FILES)
        .map(|(_, content)| truncate_diff_section(content, MAX_LINES_PER_FILE))
        .collect();

    let files_omitted = filtered_sections.len().saturating_sub(MAX_FILES);
    let final_diff = if files_omitted > 0 {
        format!("{}\n... ({} files omitted)\n", truncated, files_omitted)
    } else {
        truncated
    };

    PreparedDiff {
        diff: final_diff,
        stat,
    }
}

/// Context data for building LLM prompts
///
/// All fields are available to both commit and squash templates.
/// Squash-specific fields (`commits`, `target_branch`) are empty/None for regular commits.
struct TemplateContext<'a> {
    /// The diff to describe (staged changes for commit, combined diff for squash)
    git_diff: &'a str,
    /// Diff statistics summary (output of git diff --stat)
    git_diff_stat: &'a str,
    /// Current branch name
    branch: &'a str,
    /// Recent commit subjects for style reference
    recent_commits: Option<&'a Vec<String>>,
    /// Repository name
    repo_name: &'a str,
    /// Commits being squashed (squash only)
    commits: &'a [String],
    /// Target branch for merge (squash only)
    target_branch: Option<&'a str>,
}

/// Default template for commit message prompts
///
/// Synced to dev/config.example.toml by `cargo test readme_sync`
const DEFAULT_TEMPLATE: &str = r#"<task>Write a commit message for the staged changes below.</task>

<format>
- Subject line under 50 chars
- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>

<style>
- Imperative mood: "Add feature" not "Added feature"
- Match recent commit style (conventional commits if used)
- Describe the change, not the intent or benefit
</style>

<diffstat>
{{ git_diff_stat }}
</diffstat>

<diff>
{{ git_diff }}
</diff>

<context>
Branch: {{ branch }}
{% if recent_commits %}<recent_commits>
{% for commit in recent_commits %}- {{ commit }}
{% endfor %}</recent_commits>{% endif %}
</context>
"#;

/// Default template for squash commit message prompts
///
/// Synced to dev/config.example.toml by `cargo test readme_sync`
const DEFAULT_SQUASH_TEMPLATE: &str = r#"<task>Write a commit message for the combined effect of these commits.</task>

<format>
- Subject line under 50 chars
- For material changes, add a blank line then a body paragraph explaining the change
- Output only the commit message, no quotes or code blocks
</format>

<style>
- Imperative mood: "Add feature" not "Added feature"
- Match the style of commits being squashed (conventional commits if used)
- Describe the change, not the intent or benefit
</style>

<commits branch="{{ branch }}" target="{{ target_branch }}">
{% for commit in commits %}- {{ commit }}
{% endfor %}</commits>

<diffstat>
{{ git_diff_stat }}
</diffstat>

<diff>
{{ git_diff }}
</diff>
"#;

/// Execute an LLM command with the given prompt via stdin.
///
/// The command is a shell string executed via the platform shell (sh on Unix,
/// Git Bash on Windows), allowing environment variables to be set inline
/// (e.g., `MAX_THINKING_TOKENS=0 claude -p ...`).
///
/// This is the canonical way to execute LLM commands in this codebase.
/// All LLM execution should go through this function to maintain consistency.
pub(crate) fn execute_llm_command(command: &str, prompt: &str) -> anyhow::Result<String> {
    // TODO(diff-pipe): Consider splitting the prompt template around
    // `{{ git_diff }}` and piping `git diff` directly into the LLM via
    // `Cmd::pipe_into` (preamble + epilogue through env vars). Avoids buffering
    // MB-scale diffs in our process memory and removes them from our logs
    // entirely. See conversation around PR #2136 for sketch.

    // Log the prompt to output.log alongside captured subprocess stdout —
    // SUBPROCESS_FULL_TARGET routes to output.log at `-vv`, never to stderr.
    log::debug!(target: SUBPROCESS_FULL_TARGET, "  Prompt (stdin):");
    for line in prompt.lines() {
        log::debug!(target: SUBPROCESS_FULL_TARGET, "    {}", line);
    }

    let shell = ShellConfig::get()?;
    // TODO(claude-code-nesting): Claude Code sets CLAUDECODE=1 and blocks nested
    // invocations, even non-interactive `claude -p`. Remove this env_remove if
    // Claude Code relaxes the check for non-interactive mode. If they don't fix
    // it, replace with a deprecation warning + config.new migration to have users
    // add `CLAUDECODE=` to their command string themselves.
    // https://github.com/anthropics/claude-code/issues/25803
    let output = Cmd::new(shell.executable.to_string_lossy())
        .args(&shell.args)
        .arg(command)
        .external("commit.generation")
        .stdin_bytes(prompt)
        .env_remove("CLAUDECODE")
        .run()
        .context("Failed to spawn LLM command")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stderr = stderr.trim();
        if stderr.is_empty() {
            // Fall back to stdout or exit code when stderr is empty
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stdout = stdout.trim();
            if stdout.is_empty() {
                anyhow::bail!(
                    "LLM command failed with exit code {}",
                    output.status.code().unwrap_or(-1)
                );
            } else {
                anyhow::bail!("{}", stdout);
            }
        } else {
            anyhow::bail!("{}", stderr);
        }
    }

    let message = String::from_utf8_lossy(&output.stdout).trim().to_owned();

    if message.is_empty() {
        return Err(worktrunk::git::GitError::Other {
            message: "LLM returned empty message".into(),
        }
        .into());
    }

    Ok(message)
}

/// Template type for selecting the appropriate template source
enum TemplateType {
    Commit,
    Squash,
}

/// Load template from inline, file, or default
fn load_template(
    inline: Option<&String>,
    file: Option<&String>,
    default: &str,
    file_type_name: &str,
) -> anyhow::Result<String> {
    match (inline, file) {
        (Some(inline), None) => Ok(inline.clone()),
        (None, Some(path)) => {
            // Show deprecation warning once per session
            if !TEMPLATE_FILE_WARNING_SHOWN.swap(true, Ordering::Relaxed) {
                eprintln!(
                    "{}",
                    warning_message(format!(
                        "{file_type_name} is deprecated and will be removed in a future release. Use inline template instead. To request this feature, comment on: https://github.com/max-sixty/worktrunk/issues/444"
                    ))
                );
            }

            let expanded_path = PathBuf::from(shellexpand::tilde(path).as_ref());
            std::fs::read_to_string(&expanded_path).map_err(|e| {
                anyhow::Error::from(worktrunk::git::GitError::Other {
                    message: cformat!(
                        "Failed to read {} <bold>{}</>: {}",
                        file_type_name,
                        format_path_for_display(&expanded_path),
                        e
                    ),
                })
            })
        }
        (None, None) => Ok(default.to_string()),
        (Some(_), Some(_)) => {
            unreachable!(
                "Config validation should prevent both {} options",
                file_type_name
            )
        }
    }
}

/// Build prompt from template using minijinja
///
/// Template variables available to both commit and squash templates:
/// - `git_diff`: The diff to describe
/// - `branch`: Current branch name
/// - `recent_commits`: Recent commit subjects for style reference
/// - `repo`: Repository directory name
///
/// Squash-specific variables (empty for regular commits):
/// - `commits`: Commits being squashed
/// - `target_branch`: Target branch for merge
fn build_prompt(
    config: &CommitGenerationConfig,
    template_type: TemplateType,
    context: &TemplateContext<'_>,
) -> anyhow::Result<String> {
    // Get template source based on type
    let (template, type_name) = match template_type {
        TemplateType::Commit => (
            load_template(
                config.template.as_ref(),
                config.template_file.as_ref(),
                DEFAULT_TEMPLATE,
                "template-file",
            )?,
            "Template",
        ),
        TemplateType::Squash => (
            load_template(
                config.squash_template.as_ref(),
                config.squash_template_file.as_ref(),
                DEFAULT_SQUASH_TEMPLATE,
                "squash-template-file",
            )?,
            "Squash template",
        ),
    };

    // Validate non-empty
    if template.trim().is_empty() {
        return Err(worktrunk::git::GitError::Other {
            message: format!("{} is empty", type_name),
        }
        .into());
    }

    // Render template with minijinja - all variables available to all templates
    let env = Environment::new();
    let tmpl = env.template_from_str(&template)?;

    // Reverse commits so they're in chronological order (oldest first)
    let commits_chronological: Vec<&String> = context.commits.iter().rev().collect();

    let rendered = tmpl.render(minijinja::context! {
        git_diff => context.git_diff,
        git_diff_stat => context.git_diff_stat,
        branch => context.branch,
        recent_commits => context.recent_commits.unwrap_or(&vec![]),
        repo => context.repo_name,
        commits => commits_chronological,
        target_branch => context.target_branch.unwrap_or(""),
    })?;

    Ok(rendered)
}

pub(crate) fn generate_commit_message(
    commit_generation_config: &CommitGenerationConfig,
) -> anyhow::Result<String> {
    // Check if commit generation is configured (non-empty command)
    if commit_generation_config.is_configured() {
        let command = commit_generation_config.command.as_ref().unwrap();
        // Commit generation is explicitly configured - fail if it doesn't work
        return try_generate_commit_message(command, commit_generation_config).map_err(|e| {
            worktrunk::git::GitError::LlmCommandFailed {
                command: command.clone(),
                error: e.to_string(),
                reproduction_command: Some(format_reproduction_command(
                    "wt step commit --show-prompt",
                    command,
                )),
            }
            .into()
        });
    }

    // Fallback: generate a descriptive commit message based on changed files
    let repo = Repository::current()?;
    // Use -z for NUL-separated output to handle filenames with spaces/newlines
    let file_list = repo.run_command(&["diff", "--staged", "--name-only", "-z"])?;
    let staged_files = file_list
        .split('\0')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .map(|path| {
            Path::new(path)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(path)
        })
        .collect::<Vec<_>>();

    let message = match staged_files.len() {
        0 => "WIP: Changes".to_string(),
        1 => format!("Changes to {}", staged_files[0]),
        2 => format!("Changes to {} & {}", staged_files[0], staged_files[1]),
        3 => format!(
            "Changes to {}, {} & {}",
            staged_files[0], staged_files[1], staged_files[2]
        ),
        n => format!("Changes to {} files", n),
    };

    Ok(message)
}

fn try_generate_commit_message(
    command: &str,
    config: &CommitGenerationConfig,
) -> anyhow::Result<String> {
    let prompt = build_commit_prompt(config)?;
    execute_llm_command(command, &prompt)
}

/// Build the commit prompt from staged changes.
///
/// Gathers the staged diff, branch name, repo name, and recent commits, then renders
/// the prompt template. Used by both normal commit generation and `--show-prompt`.
pub(crate) fn build_commit_prompt(config: &CommitGenerationConfig) -> anyhow::Result<String> {
    let repo = Repository::current()?;

    // Get staged diff and diffstat
    // Use -c flags to ensure consistent format regardless of user's git config
    // (diff.noprefix, diff.mnemonicPrefix, etc. could break our parsing)
    let diff_output = repo.run_command(&[
        "-c",
        "diff.noprefix=false",
        "-c",
        "diff.mnemonicPrefix=false",
        "--no-pager",
        "diff",
        "--staged",
    ])?;
    let diff_stat = repo.run_command(&["--no-pager", "diff", "--staged", "--stat"])?;

    // Prepare diff (may filter if too large)
    let prepared = prepare_diff(diff_output, diff_stat);

    // Get current branch and repo root
    let wt = repo.current_worktree();
    let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());
    let repo_root = wt.root()?;
    let repo_name = repo_root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("repo");

    let recent_commits = repo.recent_commit_subjects(None, 5);

    let context = TemplateContext {
        git_diff: &prepared.diff,
        git_diff_stat: &prepared.stat,
        branch: &current_branch,
        recent_commits: recent_commits.as_ref(),
        repo_name,
        commits: &[],
        target_branch: None,
    };
    build_prompt(config, TemplateType::Commit, &context)
}

pub(crate) fn generate_squash_message(
    target_branch: &str,
    merge_base: &str,
    subjects: &[String],
    current_branch: &str,
    repo_name: &str,
    commit_generation_config: &CommitGenerationConfig,
) -> anyhow::Result<String> {
    // Check if commit generation is configured (non-empty command)
    if commit_generation_config.is_configured() {
        let command = commit_generation_config.command.as_ref().unwrap();

        let prompt = build_squash_prompt(
            target_branch,
            merge_base,
            subjects,
            current_branch,
            repo_name,
            commit_generation_config,
        )?;

        return execute_llm_command(command, &prompt).map_err(|e| {
            worktrunk::git::GitError::LlmCommandFailed {
                command: command.clone(),
                error: e.to_string(),
                reproduction_command: Some(format_reproduction_command(
                    "wt step squash --show-prompt",
                    command,
                )),
            }
            .into()
        });
    }

    // Fallback: deterministic commit message (only when not configured)
    let mut commit_message = format!("Squash commits from {}\n\n", current_branch);
    commit_message.push_str("Combined commits:\n");
    for subject in subjects.iter().rev() {
        // Reverse so they're in chronological order
        commit_message.push_str(&format!("- {}\n", subject));
    }
    Ok(commit_message)
}

/// Build the squash prompt from commits being squashed.
///
/// Gathers the combined diff, commit subjects, branch names, and recent commits, then
/// renders the prompt template. Used by both normal squash generation and `--show-prompt`.
pub(crate) fn build_squash_prompt(
    target_branch: &str,
    merge_base: &str,
    subjects: &[String],
    current_branch: &str,
    repo_name: &str,
    config: &CommitGenerationConfig,
) -> anyhow::Result<String> {
    let repo = Repository::current()?;

    // Get the combined diff and diffstat for all commits being squashed
    // Use -c flags to ensure consistent format regardless of user's git config
    let diff_output = repo.run_command(&[
        "-c",
        "diff.noprefix=false",
        "-c",
        "diff.mnemonicPrefix=false",
        "--no-pager",
        "diff",
        merge_base,
        "HEAD",
    ])?;
    let diff_stat = repo.run_command(&["--no-pager", "diff", merge_base, "HEAD", "--stat"])?;

    // Prepare diff (may filter if too large)
    let prepared = prepare_diff(diff_output, diff_stat);

    let recent_commits = repo.recent_commit_subjects(Some(merge_base), 5);
    let context = TemplateContext {
        git_diff: &prepared.diff,
        git_diff_stat: &prepared.stat,
        branch: current_branch,
        recent_commits: recent_commits.as_ref(),
        repo_name,
        commits: subjects,
        target_branch: Some(target_branch),
    };
    build_prompt(config, TemplateType::Squash, &context)
}

/// Synthetic diff for testing commit generation
const SYNTHETIC_DIFF: &str = r#"diff --git a/src/main.rs b/src/main.rs
index abc1234..def5678 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -10,6 +10,10 @@ fn main() {
     println!("Hello, world!");
+
+    // Add new feature
+    let config = load_config();
+    process_data(&config);
 }
"#;

/// Synthetic diffstat for testing commit generation
const SYNTHETIC_DIFF_STAT: &str = " src/main.rs | 4 ++++
 1 file changed, 4 insertions(+)";

/// Test commit generation with a synthetic diff.
///
/// Returns Ok(message) if the LLM command succeeds, or an error describing
/// what went wrong (command not found, API error, empty response, etc.)
pub(crate) fn test_commit_generation(
    commit_generation_config: &CommitGenerationConfig,
) -> anyhow::Result<String> {
    if !commit_generation_config.is_configured() {
        anyhow::bail!(
            "Commit generation is not configured. Add [commit.generation] to the config."
        );
    }

    let command = commit_generation_config.command.as_ref().unwrap();

    // Build prompt with synthetic data
    let recent_commits = vec![
        "feat: Add user authentication".to_string(),
        "fix: Handle edge case in parser".to_string(),
        "docs: Update README".to_string(),
    ];
    let context = TemplateContext {
        git_diff: SYNTHETIC_DIFF,
        git_diff_stat: SYNTHETIC_DIFF_STAT,
        branch: "feature/example",
        recent_commits: Some(&recent_commits),
        repo_name: "test-repo",
        commits: &[],
        target_branch: None,
    };
    let prompt = build_prompt(commit_generation_config, TemplateType::Commit, &context)?;

    execute_llm_command(command, &prompt).map_err(|e| {
        worktrunk::git::GitError::LlmCommandFailed {
            command: command.clone(),
            error: e.to_string(),
            reproduction_command: None, // Already a test command
        }
        .into()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use insta::assert_snapshot;

    /// Helper to create a commit context (no squash-specific fields)
    fn commit_context<'a>(
        git_diff: &'a str,
        branch: &'a str,
        recent_commits: Option<&'a Vec<String>>,
        repo_name: &'a str,
    ) -> TemplateContext<'a> {
        TemplateContext {
            git_diff,
            git_diff_stat: "",
            branch,
            recent_commits,
            repo_name,
            commits: &[],
            target_branch: None,
        }
    }

    /// Helper to create a squash context (all fields)
    fn squash_context<'a>(
        git_diff: &'a str,
        branch: &'a str,
        recent_commits: Option<&'a Vec<String>>,
        repo_name: &'a str,
        commits: &'a [String],
        target_branch: &'a str,
    ) -> TemplateContext<'a> {
        TemplateContext {
            git_diff,
            git_diff_stat: "",
            branch,
            recent_commits,
            repo_name,
            commits,
            target_branch: Some(target_branch),
        }
    }

    #[test]
    fn test_build_commit_prompt_with_default_template() {
        let config = CommitGenerationConfig::default();

        // No recent commits
        let context = commit_context("diff content", "main", None, "myrepo");
        let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
        assert_snapshot!(prompt, @r#"
        <task>Write a commit message for the staged changes below.</task>

        <format>
        - Subject line under 50 chars
        - For material changes, add a blank line then a body paragraph explaining the change
        - Output only the commit message, no quotes or code blocks
        </format>

        <style>
        - Imperative mood: "Add feature" not "Added feature"
        - Match recent commit style (conventional commits if used)
        - Describe the change, not the intent or benefit
        </style>

        <diffstat>

        </diffstat>

        <diff>
        diff content
        </diff>

        <context>
        Branch: main

        </context>
        "#);

        // With recent commits
        let commits = vec!["feat: add feature".to_string(), "fix: bug".to_string()];
        let context = commit_context("diff", "main", Some(&commits), "repo");
        let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
        assert_snapshot!(prompt, @r#"
        <task>Write a commit message for the staged changes below.</task>

        <format>
        - Subject line under 50 chars
        - For material changes, add a blank line then a body paragraph explaining the change
        - Output only the commit message, no quotes or code blocks
        </format>

        <style>
        - Imperative mood: "Add feature" not "Added feature"
        - Match recent commit style (conventional commits if used)
        - Describe the change, not the intent or benefit
        </style>

        <diffstat>

        </diffstat>

        <diff>
        diff
        </diff>

        <context>
        Branch: main
        <recent_commits>
        - feat: add feature
        - fix: bug
        </recent_commits>
        </context>
        "#);

        // Empty recent commits list — should not render commit data section
        let commits = vec![];
        let context = commit_context("diff", "main", Some(&commits), "repo");
        let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
        assert_snapshot!(prompt, @r#"
        <task>Write a commit message for the staged changes below.</task>

        <format>
        - Subject line under 50 chars
        - For material changes, add a blank line then a body paragraph explaining the change
        - Output only the commit message, no quotes or code blocks
        </format>

        <style>
        - Imperative mood: "Add feature" not "Added feature"
        - Match recent commit style (conventional commits if used)
        - Describe the change, not the intent or benefit
        </style>

        <diffstat>

        </diffstat>

        <diff>
        diff
        </diff>

        <context>
        Branch: main

        </context>
        "#);
    }

    #[test]
    fn test_build_commit_prompt_with_custom_template() {
        let config = CommitGenerationConfig {
            command: None,
            template: Some("Branch: {{ branch }}\nDiff: {{ git_diff }}".to_string()),
            template_file: None,
            squash_template: None,
            squash_template_file: None,
        };
        let context = commit_context("my diff", "feature", None, "repo");
        let result = build_prompt(&config, TemplateType::Commit, &context);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Branch: feature\nDiff: my diff");
    }

    #[test]
    fn test_build_commit_prompt_malformed_jinja() {
        let config = CommitGenerationConfig {
            command: None,
            template: Some("{{ unclosed".to_string()),
            template_file: None,
            squash_template: None,
            squash_template_file: None,
        };
        let context = commit_context("diff", "main", None, "repo");
        let result = build_prompt(&config, TemplateType::Commit, &context);
        assert!(result.is_err());
    }

    #[test]
    fn test_build_commit_prompt_empty_template() {
        let config = CommitGenerationConfig {
            command: None,
            template: Some("   ".to_string()),
            template_file: None,
            squash_template: None,
            squash_template_file: None,
        };
        let context = commit_context("diff", "main", None, "repo");
        let result = build_prompt(&config, TemplateType::Commit, &context);
        assert_snapshot!(result.unwrap_err().to_string(), @"✗ Template is empty");
    }

    #[test]
    fn test_build_commit_prompt_with_all_variables() {
        let config = CommitGenerationConfig {
            command: None,
            template: Some(
                "Repo: {{ repo }}\nBranch: {{ branch }}\nDiff: {{ git_diff }}\n{% for c in recent_commits %}{{ c }}\n{% endfor %}"
                    .to_string(),
            ),
            template_file: None,
            squash_template: None,
            squash_template_file: None,
        };
        let commits = vec!["commit1".to_string(), "commit2".to_string()];
        let context = commit_context("my diff", "feature", Some(&commits), "myrepo");
        let result = build_prompt(&config, TemplateType::Commit, &context);
        assert!(result.is_ok());
        let prompt = result.unwrap();
        assert_eq!(
            prompt,
            "Repo: myrepo\nBranch: feature\nDiff: my diff\ncommit1\ncommit2\n"
        );
    }

    #[test]
    fn test_build_squash_prompt_with_default_template() {
        let config = CommitGenerationConfig::default();
        let commits = vec!["feat: A".to_string(), "fix: B".to_string()];
        let context = squash_context("diff content", "feature", None, "repo", &commits, "main");
        let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
        assert_snapshot!(prompt, @r#"
        <task>Write a commit message for the combined effect of these commits.</task>

        <format>
        - Subject line under 50 chars
        - For material changes, add a blank line then a body paragraph explaining the change
        - Output only the commit message, no quotes or code blocks
        </format>

        <style>
        - Imperative mood: "Add feature" not "Added feature"
        - Match the style of commits being squashed (conventional commits if used)
        - Describe the change, not the intent or benefit
        </style>

        <commits branch="feature" target="main">
        - fix: B
        - feat: A
        </commits>

        <diffstat>

        </diffstat>

        <diff>
        diff content
        </diff>
        "#);
    }

    #[test]
    fn test_build_squash_prompt_with_custom_template() {
        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: None,
            squash_template: Some(
                "Target: {{ target_branch }}\n{% for c in commits %}{{ c }}\n{% endfor %}"
                    .to_string(),
            ),
            squash_template_file: None,
        };
        let commits = vec!["A".to_string(), "B".to_string()];
        let context = squash_context("diff", "feature", None, "repo", &commits, "main");
        let result = build_prompt(&config, TemplateType::Squash, &context);
        assert!(result.is_ok());
        // Commits are reversed, so chronological order is B, A
        assert_eq!(result.unwrap(), "Target: main\nB\nA\n");
    }

    #[test]
    fn test_build_squash_prompt_empty_commits() {
        let config = CommitGenerationConfig::default();
        let commits: Vec<String> = vec![];
        let context = squash_context("diff", "feature", None, "repo", &commits, "main");
        let result = build_prompt(&config, TemplateType::Squash, &context);
        assert!(result.is_ok());
    }

    #[test]
    fn test_build_squash_prompt_malformed_jinja() {
        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: None,
            squash_template: Some("{% for x in commits %}{{ x }".to_string()),
            squash_template_file: None,
        };
        let commits: Vec<String> = vec![];
        let context = squash_context("diff", "feature", None, "repo", &commits, "main");
        let result = build_prompt(&config, TemplateType::Squash, &context);
        assert!(result.is_err());
    }

    #[test]
    fn test_build_squash_prompt_empty_template() {
        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: None,
            squash_template: Some("  \n  ".to_string()),
            squash_template_file: None,
        };
        let commits: Vec<String> = vec![];
        let context = squash_context("diff", "feature", None, "repo", &commits, "main");
        let result = build_prompt(&config, TemplateType::Squash, &context);
        assert_snapshot!(result.unwrap_err().to_string(), @"✗ Squash template is empty");
    }

    #[test]
    fn test_build_squash_prompt_with_all_variables() {
        // Test that squash templates now have access to ALL variables including git_diff and recent_commits
        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: None,
            squash_template: Some(
                "Repo: {{ repo }}\nBranch: {{ branch }}\nTarget: {{ target_branch }}\nDiff: {{ git_diff }}\n{% for c in commits %}{{ c }}\n{% endfor %}{% for r in recent_commits %}style: {{ r }}\n{% endfor %}"
                    .to_string(),
            ),
            squash_template_file: None,
        };
        let commits = vec!["A".to_string(), "B".to_string()];
        let recent = vec!["prev1".to_string(), "prev2".to_string()];
        let context = squash_context(
            "the diff",
            "feature",
            Some(&recent),
            "myrepo",
            &commits,
            "main",
        );
        let result = build_prompt(&config, TemplateType::Squash, &context);
        assert!(result.is_ok());
        let prompt = result.unwrap();
        assert_eq!(
            prompt,
            "Repo: myrepo\nBranch: feature\nTarget: main\nDiff: the diff\nB\nA\nstyle: prev1\nstyle: prev2\n"
        );
    }

    #[test]
    fn test_build_commit_prompt_with_sophisticated_jinja() {
        // Test advanced jinja features: filters, length, conditionals, whitespace control
        let config = CommitGenerationConfig {
            command: None,
            template: Some(
                r#"=== {{ repo | upper }} ===
Branch: {{ branch }}
{%- if recent_commits %}
Commits: {{ recent_commits | length }}
{%- for c in recent_commits %}
  - {{ loop.index }}. {{ c }}
{%- endfor %}
{%- else %}
No recent commits
{%- endif %}

Diff follows:
{{ git_diff }}"#
                    .to_string(),
            ),
            template_file: None,
            squash_template: None,
            squash_template_file: None,
        };

        // With commits — exercises if-branch, filters, loop.index, whitespace control
        let commits = vec![
            "feat: add auth".to_string(),
            "fix: bug".to_string(),
            "docs: update".to_string(),
        ];
        let context = commit_context("my diff content", "feature-x", Some(&commits), "myapp");
        let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
        assert_snapshot!(prompt, @"
        === MYAPP ===
        Branch: feature-x
        Commits: 3
          - 1. feat: add auth
          - 2. fix: bug
          - 3. docs: update

        Diff follows:
        my diff content
        ");

        // Without commits — exercises else-branch
        let context = commit_context("diff", "main", None, "test");
        let prompt = build_prompt(&config, TemplateType::Commit, &context).unwrap();
        assert_snapshot!(prompt, @"
        === TEST ===
        Branch: main
        No recent commits

        Diff follows:
        diff
        ");
    }

    #[test]
    fn test_build_squash_prompt_with_sophisticated_jinja() {
        // Test sophisticated jinja in squash templates
        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: None,
            squash_template: Some(
                r#"Squashing {{ commits | length }} commit(s) from {{ branch }} to {{ target_branch }}
{% if commits | length > 1 -%}
Multiple commits detected:
{%- for c in commits %}
  {{ loop.index }}/{{ loop.length }}: {{ c }}
{%- endfor %}
{%- else -%}
Single commit: {{ commits[0] }}
{%- endif %}"#
                    .to_string(),
            ),
            squash_template_file: None,
        };

        // Multiple commits — reversed for chronological order (C, B, A)
        let commits = vec![
            "commit A".to_string(),
            "commit B".to_string(),
            "commit C".to_string(),
        ];
        let context = squash_context("diff", "feature", None, "repo", &commits, "main");
        let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
        assert_snapshot!(prompt, @"
        Squashing 3 commit(s) from feature to main
        Multiple commits detected:
          1/3: commit C
          2/3: commit B
          3/3: commit A
        ");

        // Single commit — exercises else-branch
        let single_commit = vec!["solo commit".to_string()];
        let context = squash_context("diff", "feature", None, "repo", &single_commit, "main");
        let prompt = build_prompt(&config, TemplateType::Squash, &context).unwrap();
        assert_snapshot!(prompt, @"
        Squashing 1 commit(s) from feature to main
        Single commit: solo commit
        ");
    }

    #[test]
    fn test_build_commit_prompt_with_template_file() {
        let temp_dir = std::env::temp_dir();
        let template_path = temp_dir.join("test_commit_template.txt");
        std::fs::write(
            &template_path,
            "Branch: {{ branch }}\nRepo: {{ repo }}\nDiff: {{ git_diff }}",
        )
        .unwrap();

        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: Some(template_path.to_string_lossy().to_string()),
            squash_template: None,
            squash_template_file: None,
        };
        let context = commit_context("my diff", "feature", None, "myrepo");
        let result = build_prompt(&config, TemplateType::Commit, &context);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            "Branch: feature\nRepo: myrepo\nDiff: my diff"
        );

        // Cleanup
        std::fs::remove_file(&template_path).ok();
    }

    #[test]
    fn test_build_commit_prompt_with_missing_template_file() {
        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: Some("/nonexistent/path/template.txt".to_string()),
            squash_template: None,
            squash_template_file: None,
        };
        let context = commit_context("diff", "main", None, "repo");
        let result = build_prompt(&config, TemplateType::Commit, &context);
        // OS error text varies by platform, so use contains
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Failed to read template-file"), "{err}");
        assert!(err.contains("/nonexistent/path/template.txt"), "{err}");
    }

    #[test]
    fn test_build_squash_prompt_with_template_file() {
        let temp_dir = std::env::temp_dir();
        let template_path = temp_dir.join("test_squash_template.txt");
        std::fs::write(
            &template_path,
            "Target: {{ target_branch }}\nBranch: {{ branch }}\n{% for c in commits %}{{ c }}\n{% endfor %}",
        )
        .unwrap();

        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: None,
            squash_template: None,
            squash_template_file: Some(template_path.to_string_lossy().to_string()),
        };
        let commits = vec!["A".to_string(), "B".to_string()];
        let context = squash_context("diff", "feature", None, "repo", &commits, "main");
        let result = build_prompt(&config, TemplateType::Squash, &context);
        assert!(result.is_ok());
        // Commits are reversed for chronological order
        assert_eq!(result.unwrap(), "Target: main\nBranch: feature\nB\nA\n");

        // Cleanup
        std::fs::remove_file(&template_path).ok();
    }

    #[test]
    fn test_build_commit_prompt_with_tilde_expansion() {
        // This test verifies tilde expansion works - it should attempt to read
        // from the expanded home directory path
        let config = CommitGenerationConfig {
            command: None,
            template: None,
            template_file: Some("~/nonexistent_template_for_test.txt".to_string()),
            squash_template: None,
            squash_template_file: None,
        };
        let context = commit_context("diff", "main", None, "repo");
        let result = build_prompt(&config, TemplateType::Commit, &context);
        // Should fail because file doesn't exist
        // OS error text varies by platform, so use contains
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Failed to read template-file"), "{err}");
        assert!(err.contains("~/nonexistent_template_for_test.txt"), "{err}");
    }

    #[test]
    fn test_commit_template_can_access_squash_variables() {
        // Verify that commit templates can access squash-specific variables without errors
        // (they're empty/None for regular commits, but shouldn't cause template errors)
        let config = CommitGenerationConfig {
            command: None,
            template: Some(
                "Branch: {{ branch }}\nTarget: {{ target_branch }}\nCommits: {{ commits | length }}"
                    .to_string(),
            ),
            template_file: None,
            squash_template: None,
            squash_template_file: None,
        };
        let context = commit_context("diff", "feature", None, "repo");
        let result = build_prompt(&config, TemplateType::Commit, &context);
        assert!(result.is_ok());
        let prompt = result.unwrap();
        // Squash-specific variables are empty for regular commits
        assert_eq!(prompt, "Branch: feature\nTarget: \nCommits: 0");
    }

    // Tests for diff filtering

    #[test]
    fn test_is_lock_file() {
        // Matches
        assert!(is_lock_file("Cargo.lock"));
        assert!(is_lock_file("package-lock.json"));
        assert!(is_lock_file("pnpm-lock.yaml"));
        assert!(is_lock_file("yarn-lock.yaml"));
        assert!(is_lock_file(".terraform.lock.hcl"));
        assert!(is_lock_file("terraform.lock.hcl"));
        assert!(is_lock_file("path/to/Cargo.lock"));

        // Non-matches
        assert!(!is_lock_file("src/main.rs"));
        assert!(!is_lock_file("README.md"));
        assert!(!is_lock_file("config.toml"));
        assert!(!is_lock_file("lockfile.txt"));
        assert!(!is_lock_file("my.lock.rs")); // Not a standard lock pattern
    }

    #[test]
    fn test_parse_diff_sections() {
        // Empty input
        assert!(parse_diff_sections("").is_empty());

        // Single file
        let diff = "diff --git a/foo.rs b/foo.rs\nsome content\n";
        let sections = parse_diff_sections(diff);
        assert_eq!(sections.len(), 1);
        assert_eq!(sections[0].0, "foo.rs");

        // Multiple files
        let diff = r#"diff --git a/src/foo.rs b/src/foo.rs
index abc..def 100644
--- a/src/foo.rs
+++ b/src/foo.rs
@@ -1,3 +1,4 @@
 fn foo() {}
+fn bar() {}
diff --git a/Cargo.lock b/Cargo.lock
index 111..222 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1,100 +1,150 @@
 lots of lock content
"#;
        let sections = parse_diff_sections(diff);
        assert_eq!(sections.len(), 2);
        assert_eq!(sections[0].0, "src/foo.rs");
        assert_snapshot!(sections[0].1, @"
        diff --git a/src/foo.rs b/src/foo.rs
        index abc..def 100644
        --- a/src/foo.rs
        +++ b/src/foo.rs
        @@ -1,3 +1,4 @@
         fn foo() {}
        +fn bar() {}
        ");
        assert_eq!(sections[1].0, "Cargo.lock");
        assert_snapshot!(sections[1].1, @"
        diff --git a/Cargo.lock b/Cargo.lock
        index 111..222 100644
        --- a/Cargo.lock
        +++ b/Cargo.lock
        @@ -1,100 +1,150 @@
         lots of lock content
        ");
    }

    #[test]
    fn test_truncate_diff_section() {
        let section = r#"diff --git a/file.rs b/file.rs
index abc..def 100644
--- a/file.rs
+++ b/file.rs
@@ -1,10 +1,15 @@
 line 1
 line 2
 line 3
 line 4
 line 5
 line 6
 line 7
 line 8
 line 9
 line 10
"#;

        // Truncate to 8 lines (should keep header + first few content lines)
        let truncated = truncate_diff_section(section, 8);
        assert_snapshot!(truncated, @"
        diff --git a/file.rs b/file.rs
        index abc..def 100644
        --- a/file.rs
        +++ b/file.rs
        @@ -1,10 +1,15 @@
         line 1
         line 2
         line 3

        ... (7 lines omitted)
        ");
    }

    #[test]
    fn test_prepare_diff_small_diff_passes_through() {
        let diff = "small diff".to_string();
        let stat = "1 file changed".to_string();

        let prepared = prepare_diff(diff.clone(), stat.clone());
        assert_eq!(prepared.diff, diff);
        assert_eq!(prepared.stat, stat);
    }

    #[test]
    fn test_prepare_diff_filters_lock_files() {
        // Create a diff just over the threshold with a lock file
        let regular_content = "x".repeat(100_000);
        let lock_content = "y".repeat(350_000);

        let diff = format!(
            r#"diff --git a/src/main.rs b/src/main.rs
{}
diff --git a/Cargo.lock b/Cargo.lock
{}
"#,
            regular_content, lock_content
        );
        let stat = "2 files changed".to_string();

        let prepared = prepare_diff(diff, stat);

        // Lock file should be filtered out
        assert!(!prepared.diff.contains("Cargo.lock"));
        assert!(prepared.diff.contains("src/main.rs"));
    }

    #[test]
    fn test_prepare_diff_filters_then_truncates() {
        // Create many non-lock files that exceed threshold even after lock filtering
        let mut diff = String::new();
        for i in 0..100 {
            diff.push_str(&format!(
                "diff --git a/file{}.rs b/file{}.rs\n{}\n",
                i,
                i,
                "x".repeat(5000)
            ));
        }

        let stat = "100 files changed".to_string();
        let prepared = prepare_diff(diff, stat);

        // Should be truncated (max 50 files)
        assert!(prepared.diff.contains("files omitted"));
    }

    #[test]
    fn test_truncate_diff_section_short() {
        // Section shorter than max lines should pass through unchanged
        let section = "line1\nline2\nline3\n";
        let truncated = truncate_diff_section(section, 10);
        assert_eq!(truncated, section);
    }

    #[test]
    fn test_truncate_diff_section_no_header() {
        // Section without @@ marker
        let section = "line1\nline2\nline3\nline4\nline5\nline6\nline7\nline8\n";
        let truncated = truncate_diff_section(section, 3);
        assert_snapshot!(truncated, @"
        line1
        line2
        line3

        ... (5 lines omitted)
        ");
    }

    #[test]
    fn test_format_reproduction_command() {
        // Simple command — no wrapping needed
        let result = format_reproduction_command("git diff", "llm -m haiku");
        assert_snapshot!(result, @"git diff | llm -m haiku");

        // Env var assignment — needs shell wrapping
        let result = format_reproduction_command("git diff", "MAX_THINKING_TOKENS=0 claude -p");
        assert_snapshot!(result, @"git diff | sh -c 'MAX_THINKING_TOKENS=0 claude -p'");

        // Shell metacharacters — needs wrapping
        let result = format_reproduction_command("git diff", "cmd1 && cmd2");
        assert_snapshot!(result, @"git diff | sh -c 'cmd1 && cmd2'");
    }
}