nitpicker 0.11.1

Multi-reviewer code review using LLMs with parallel agents and debate mode
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
use clap::Parser;
use cli::{Args, Command, merged_context_files, merged_presets};
use eyre::{Result, WrapErr};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use tracing::field::Empty;
use tracing::{Instrument, info_span};

use nitpicker_agent::tools::floor_char_boundary;

mod cli;
mod context;
mod debate;
mod detect;
#[cfg(feature = "antigravity")]
mod gemini_proxy;
mod init;
mod output;
mod pr;
mod presets;
mod progress;
mod prompts;
mod proxy;
mod reflect;
mod review;
mod routing;
mod run;
mod settings;
mod telemetry;

/// Presets pick review rubrics; `ask`/`init`/`reflect` have none. Root-position `--preset`
/// parses fine before any subcommand, so without an explicit rejection it would be silently
/// discarded there (`pr` and the default review arms consume it).
fn presets_allowed(command: &Option<Command>) -> bool {
    match command {
        None | Some(Command::Pr(_)) => true,
        Some(Command::Ask { .. } | Command::Init { .. } | Command::Reflect { .. }) => false,
    }
}

fn fallback_allowed(command: &Option<Command>) -> bool {
    matches!(command, None | Some(Command::Ask { .. } | Command::Pr(_)))
}

/// Outcome of a run, mapped to the exit-code contract by [`finish`]: 0 = clean verdict,
/// 1 = hard failure (no verdict), 3 = degraded verdict (report printed, but at least one
/// reviewer or debate turn failed). 2 is deliberately unused — clap exits 2 on usage errors,
/// and the whole point is an unambiguous subprocess signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Exit {
    Clean,
    Degraded,
    /// The failure was already reported to the consumer (a `pr --json` error envelope), so
    /// nothing more is printed.
    Failed,
}

impl Exit {
    pub(crate) fn from_degraded(degraded: bool) -> Self {
        match degraded {
            true => Self::Degraded,
            false => Self::Clean,
        }
    }
}

fn main() -> ExitCode {
    let args = Args::parse();

    let verbose = args.common.verbose;
    let is_reflect = matches!(&args.command, Some(Command::Reflect { .. }));
    let default_level = if verbose || is_reflect {
        "info"
    } else {
        "warn"
    };
    let telemetry = telemetry::init(default_level);

    let runtime = match tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
    {
        Ok(runtime) => runtime,
        Err(err) => {
            eprintln!("Error: failed to start the async runtime: {err}");
            return ExitCode::from(1);
        }
    };
    let outcome = runtime.block_on(run(args));
    // the runtime goes first so no task is still producing spans while the exporter drains;
    // every guard inside `run` (checkout restore, PR lock) has already dropped with it
    drop(runtime);
    telemetry.shutdown();
    ExitCode::from(finish(outcome, &mut std::io::stdout()))
}

/// Map a run's outcome to its exit code, reporting what the consumer has not seen yet: a
/// degraded verdict gets its warning, an unreported error is rendered the way eyre's default
/// `main` handler would. The report on stdout is flushed explicitly so a piped consumer never
/// loses its tail; a flush failure is a hard failure, not a degraded verdict.
fn finish(outcome: Result<Exit>, stdout: &mut impl std::io::Write) -> u8 {
    match outcome {
        Ok(Exit::Clean) => 0,
        Ok(Exit::Failed) => 1,
        Ok(Exit::Degraded) => match stdout.flush() {
            Ok(()) => {
                eprintln!(
                    "warning: degraded verdict — a reviewer or debate turn failed (exit code 3)"
                );
                3
            }
            Err(err) => {
                eprintln!("error: failed to flush report to stdout: {err}");
                1
            }
        },
        Err(err) => {
            eprintln!("Error: {err:?}");
            1
        }
    }
}

/// The root span of every run; the orchestration spans below it are per-mode.
async fn run(args: Args) -> Result<Exit> {
    let command = match &args.command {
        None => "review",
        Some(Command::Init { .. }) => "init",
        Some(Command::Ask { .. }) => "ask",
        Some(Command::Pr(_)) => "pr",
        Some(Command::Reflect { .. }) => "reflect",
    };
    let span = info_span!(
        "nitpicker.run",
        otel.status_code = Empty,
        nitpicker.command = command,
        nitpicker.degraded = Empty,
        nitpicker.pr.number = Empty,
    );
    let outcome = dispatch(args).instrument(span.clone()).await;
    match &outcome {
        Ok(Exit::Clean) => {}
        Ok(Exit::Degraded) => {
            span.record("nitpicker.degraded", true);
        }
        Ok(Exit::Failed) | Err(_) => {
            span.record("otel.status_code", "ERROR");
        }
    }
    outcome
}

async fn dispatch(args: Args) -> Result<Exit> {
    if !presets_allowed(&args.command) && !args.presets.preset.is_empty() {
        eyre::bail!("--preset applies to review modes only (default review, --analyze, pr)");
    }
    if args.common.fallback && !fallback_allowed(&args.command) {
        eyre::bail!("--fallback applies to review and ask modes only");
    }

    // note: no json panic hook. reviewer work runs in tokio::spawn tasks whose
    // panics are caught as JoinError and folded into a degraded report (exit 3
    // for review/ask, status ok for pr); a process-wide hook would double-emit
    // there. a genuine top-level panic aborts non-zero with a stderr message,
    // which is an acceptable catastrophic-failure signal for the consumer.
    match args.command {
        Some(Command::Init { global, free }) => {
            // the global flags parse here too; `init` generates a config, so honoring --config
            // would be nonsense — reject it rather than silently ignore it
            if args.common.config.is_some() {
                eyre::bail!("--config has no effect on init, which generates a config file");
            }
            let path = init::init_config_path(global, &args.common.repo)?;
            if path.exists() {
                eyre::bail!("{} already exists", path.display());
            }
            init::run_init(path, free).await?;
            return Ok(Exit::Clean);
        }
        Some(Command::Ask {
            context,
            topic,
            no_debate,
            alloy,
            rounds,
            max_turns,
        }) => {
            let repo = resolve_repo_root(&args.common.repo)?;
            let mut config = settings::load_config(args.common.config.as_deref(), &repo)?;
            // CLI-only routing validation must precede free-model smoke completions.
            let (use_alloy, use_fallback) =
                settings::resolve_routing_modes(&config, alloy, args.common.fallback)?;
            settings::finalize_routing_config(&mut config, use_fallback).await?;
            let config = config;
            let topic = context::append_to_prompt(
                topic,
                &context::load_context_files(&merged_context_files(&args.context, &context))?,
            );
            let max_turns = config.max_turns(max_turns)?;

            if use_alloy && no_debate {
                eprintln!("warning: --alloy has no effect with --no-debate");
            }

            if !no_debate && config.default_debate() {
                if config.reviewer.len() < 2 {
                    eyre::bail!(
                        "debate mode requires at least 2 reviewers, found {} — add another reviewer or set debate = false in [defaults]",
                        config.reviewer.len()
                    );
                }
                let outcome = debate::run_debate(
                    &repo,
                    &topic,
                    &config,
                    debate::DebateOptions {
                        max_rounds: rounds,
                        max_turns,
                        verbose: args.common.verbose,
                        task: prompts::RunTask::Ask,
                        alloy: use_alloy,
                        fallback: use_fallback,
                        format: output::OutputFormat::Text,
                    },
                )
                .await?;
                println!("{}", outcome.report);
                if args.common.verbose {
                    eprintln!(
                        "\nTranscript saved to: {}",
                        outcome.transcript_path.display()
                    );
                }
                return Ok(Exit::from_degraded(outcome.degraded));
            }

            let outcome = review::run_review(
                &repo,
                &topic,
                &config,
                review::ReviewOptions {
                    max_turns,
                    verbose: args.common.verbose,
                    task: prompts::RunTask::Ask,
                    fallback: use_fallback,
                    format: output::OutputFormat::Text,
                },
            )
            .await?;
            println!("{}", outcome.report);
            return Ok(Exit::from_degraded(outcome.degraded));
        }
        Some(Command::Pr(pr_args)) => {
            let context_files = merged_context_files(&args.context, &pr_args.context);
            let preset_names = merged_presets(&args.presets, &pr_args.presets);
            // config loading happens inside run_pr so its failures honor --format json too
            return pr::run_pr(pr_args, args.common, context_files, preset_names).await;
        }
        Some(Command::Reflect {
            sessions_dir,
            n,
            dump: Some(out_dir),
        }) => {
            reflect::dump_sessions(sessions_dir, n, &out_dir)?;
            return Ok(Exit::Clean);
        }
        Some(Command::Reflect {
            sessions_dir,
            n,
            dump: None,
        }) => {
            let repo = resolve_repo_root(&args.common.repo)?;
            let config =
                settings::load_resolved_config(args.common.config.as_deref(), &repo).await?;
            reflect::run_reflect(reflect::ReflectArgs {
                sessions_dir,
                n,
                repo,
                config,
            })
            .await?;
            return Ok(Exit::Clean);
        }
        None => {}
    }

    let repo = resolve_repo_root(&args.common.repo)?;

    let mut config = settings::load_config(args.common.config.as_deref(), &repo)?;
    // Resolve presets and CLI-only routing validation before free-model resolution: pure usage
    // errors must fail before any network call (the resolver can run live smoke completions).
    let presets = presets::resolve(&args.presets.preset, &config)?;
    let (use_alloy, use_fallback) =
        settings::resolve_routing_modes(&config, args.alloy, args.common.fallback)?;
    settings::finalize_routing_config(&mut config, use_fallback).await?;
    let config = config;
    let max_turns = config.max_turns(args.max_turns)?;

    let scope = match args.analyze {
        Some(_) => prompts::ReviewScope::Static,
        None => prompts::ReviewScope::Diff,
    };
    let prompt = if let Some(path) = args.analyze {
        let path_opt = if path.as_os_str().is_empty() {
            None
        } else {
            Some(path.as_path())
        };
        build_analysis_prompt(path_opt, args.prompt.as_deref())
    } else {
        let base = detect_diff_context(&repo)?;
        match args.prompt {
            Some(p) => format!("{base}\n\nAdditional instructions: {p}"),
            None => base,
        }
    };
    let prompt = context::append_to_prompt(
        prompt,
        &context::load_context_files(&args.context.context_file)?,
    );

    if use_alloy && args.no_debate {
        eprintln!("warning: --alloy has no effect with --no-debate");
    }

    if !args.no_debate && config.default_debate() {
        if config.reviewer.len() < 2 {
            eyre::bail!(
                "debate mode requires at least 2 reviewers, found {} — add another reviewer or set debate = false in [defaults]",
                config.reviewer.len()
            );
        }
        let outcome = debate::run_debate(
            &repo,
            &prompt,
            &config,
            debate::DebateOptions {
                max_rounds: args.rounds,
                max_turns,
                verbose: args.common.verbose,
                task: prompts::RunTask::Review {
                    scope,
                    presets: &presets,
                },
                alloy: use_alloy,
                fallback: use_fallback,
                format: output::OutputFormat::Text,
            },
        )
        .await?;
        println!("{}", outcome.report);
        if args.common.verbose {
            eprintln!(
                "\nTranscript saved to: {}",
                outcome.transcript_path.display()
            );
        }
        Ok(Exit::from_degraded(outcome.degraded))
    } else {
        let outcome = review::run_review(
            &repo,
            &prompt,
            &config,
            review::ReviewOptions {
                max_turns,
                verbose: args.common.verbose,
                task: prompts::RunTask::Review {
                    scope,
                    presets: &presets,
                },
                fallback: use_fallback,
                format: output::OutputFormat::Text,
            },
        )
        .await?;
        println!("{}", outcome.report);
        Ok(Exit::from_degraded(outcome.degraded))
    }
}

/// Resolve the worktree containing `path` through Git itself. Linked worktrees and checked-out
/// submodules represent `.git` as a file, so its filesystem shape is not a repository invariant.
pub(crate) fn git_worktree_root(path: &Path) -> Option<PathBuf> {
    let output = std::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(path)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }

    let root = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
    root.canonicalize().ok()
}

fn resolve_repo_root(path: &Path) -> Result<PathBuf> {
    let canonical = path
        .canonicalize()
        .wrap_err("failed to canonicalize --repo path")?;
    git_worktree_root(&canonical)
        .ok_or_else(|| eyre::eyre!("--repo must point inside a Git worktree"))
}

// Describes only the target and optional user instructions — the investigation angles come
// from the resolved presets, not from a focus list baked in here.
fn build_analysis_prompt(path: Option<&Path>, custom_prompt: Option<&str>) -> String {
    let target = match path {
        Some(p) => format!("`{}`", p.display()),
        None => "the entire repository".to_string(),
    };
    let base = format!(
        "Analyze the following code for issues and improvement opportunities:\n\
         - Target: {}",
        target
    );
    match custom_prompt {
        Some(p) if !p.trim().is_empty() => {
            format!("{}\n\nAdditional instructions: {}", base, p)
        }
        _ => base,
    }
}

pub(crate) struct BaseBranch {
    pub(crate) name: String,
    pub(crate) revision: String,
}

const MAX_SNAPSHOT_FILES: usize = 500;
const MAX_SNAPSHOT_BYTES: usize = 64 * 1024;

pub fn detect_diff_context(repo: &Path) -> Result<String> {
    let branch = run_git(repo, &["rev-parse", "--abbrev-ref", "HEAD"])?;
    let branch = branch.trim();

    if branch == "HEAD" {
        eyre::bail!("detached HEAD state: checkout a branch before running nitpicker");
    }

    let base = detect_base_branch(repo);
    let head_sha = run_git(repo, &["rev-parse", "HEAD"])?.trim().to_string();
    let working_tree = run_git(repo, &["status", "--short"])?;
    let working_tree_files = nonempty_lines(&working_tree);
    let has_uncommitted = !working_tree_files.is_empty();

    let base_snapshot = match base.as_ref() {
        Some(base) => {
            let base_sha = run_git(repo, &["rev-parse", &base.revision])?
                .trim()
                .to_string();
            let merge_base = run_git_optional(repo, &["merge-base", &base_sha, &head_sha])?
                .map(|sha| sha.trim().to_string())
                .filter(|sha| !sha.is_empty());
            let comparison_base = merge_base.as_deref().unwrap_or(&base_sha);
            let committed = run_git(
                repo,
                &[
                    "diff",
                    "--name-status",
                    "-M",
                    comparison_base,
                    &head_sha,
                    "--",
                ],
            )?;
            let numstat = run_git(
                repo,
                &["diff", "--numstat", "-M", comparison_base, &head_sha, "--"],
            )?;
            Some((
                base,
                base_sha,
                merge_base,
                with_line_counts(nonempty_lines(&committed), &numstat),
            ))
        }
        None => None,
    };
    let has_committed_changes = base_snapshot
        .as_ref()
        .is_some_and(|(_, _, _, files)| !files.is_empty());

    if !has_uncommitted && !has_committed_changes {
        if let Some(base) = base.as_ref() {
            eyre::bail!(
                "no changes to review: no uncommitted changes and no committed changes vs {}",
                base.name
            );
        }
        eyre::bail!(
            "no changes to review: no uncommitted changes and no detectable base branch commits"
        );
    }

    let mut snapshot = format!(
        "Review the following changes. This review snapshot was captured once before reviewers \
fan out; treat its revisions and file maps as immutable orientation for this run.\n\n\
## Frozen review snapshot\n\
- Branch: `{branch}`\n\
- HEAD: `{head_sha}`\n"
    );

    match base_snapshot.as_ref() {
        Some((base, base_sha, merge_base, _)) => {
            let comparison_base = merge_base.as_deref().unwrap_or(base_sha);
            snapshot.push_str(&format!(
                "- Base: `{}` @ `{base_sha}`\n\
                 - Merge base: {}\n\
                 - Committed comparison: `git diff {comparison_base} {head_sha} --`\n",
                base.revision,
                merge_base
                    .as_deref()
                    .map(|sha| format!("`{sha}`"))
                    .unwrap_or_else(
                        || "unavailable; using a direct base/HEAD tree comparison".to_string()
                    )
            ));
        }
        None => {
            snapshot.push_str("- Base: not detected\n- Merge base: unavailable\n");
        }
    }

    snapshot.push_str(&format!(
        "- Working tree: {}\n\
         - Tracked working-tree comparison: `git diff {head_sha} --`\n\
         - Untracked files: included in the status map below\n",
        if has_uncommitted { "dirty" } else { "clean" }
    ));

    append_snapshot_file_sections(
        &mut snapshot,
        base_snapshot
            .as_ref()
            .map(|(_, _, _, committed_files)| committed_files.as_slice()),
        &working_tree_files,
    );

    if snapshot.len() > MAX_SNAPSHOT_BYTES {
        snapshot.truncate(floor_char_boundary(&snapshot, MAX_SNAPSHOT_BYTES));
    }

    Ok(snapshot)
}

fn nonempty_lines(output: &str) -> Vec<String> {
    output
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(str::to_string)
        .collect()
}

/// Appends `+added -deleted` to each name-status entry. Both listings come from the same pinned
/// comparison with identical rename detection, so git emits them in the same order; on any
/// count mismatch the plain name-status entries are kept rather than risk misattributed counts.
fn with_line_counts(name_status: Vec<String>, numstat: &str) -> Vec<String> {
    let counts = nonempty_lines(numstat);
    match counts.len() == name_status.len() {
        true => name_status
            .into_iter()
            .zip(counts)
            .map(
                |(entry, count)| match count.split('\t').collect::<Vec<_>>()[..] {
                    ["-", "-", ..] => format!("{entry}\tbinary"),
                    [added, deleted, ..] => format!("{entry}\t+{added} -{deleted}"),
                    _ => entry,
                },
            )
            .collect(),
        false => name_status,
    }
}

fn render_snapshot_files(files: &[String], budget: usize) -> String {
    if files.is_empty() {
        return "(none)\n".to_string();
    }

    let mut text = String::new();
    let mut included = 0;
    for file in files.iter().take(MAX_SNAPSHOT_FILES) {
        let line = format!("- `{file}`\n");
        let next_included = included + 1;
        let omitted = files.len().saturating_sub(next_included);
        let marker = snapshot_omission_marker(omitted);
        if text.len() + line.len() + marker.len() > budget {
            break;
        }
        text.push_str(&line);
        included = next_included;
    }

    let omitted = files.len().saturating_sub(included);
    let marker = snapshot_omission_marker(omitted);
    if text.len() + marker.len() <= budget {
        text.push_str(&marker);
    }
    text
}

fn snapshot_omission_marker(omitted: usize) -> String {
    match omitted {
        0 => String::new(),
        count => format!(
            "- … {count} additional files omitted from the prompt; inspect the pinned comparison if needed\n"
        ),
    }
}

fn append_snapshot_file_sections(
    output: &mut String,
    committed_files: Option<&[String]>,
    working_tree_files: &[String],
) {
    const COMMITTED_HEADING: &str =
        "\n### Committed changed files (name-status, +added -deleted lines)\n";
    const WORKING_TREE_HEADING: &str = "\n### Uncommitted changed files (`git status --short`)\n";
    const NO_BASE: &str = "(comparison unavailable: no base detected)\n";

    let fixed_len = COMMITTED_HEADING.len() + WORKING_TREE_HEADING.len();
    let content_budget = MAX_SNAPSHOT_BYTES
        .saturating_sub(output.len())
        .saturating_sub(fixed_len);
    let committed_budget = content_budget / 2;
    let working_tree_budget = content_budget.saturating_sub(committed_budget);

    let committed = committed_files
        .map(|files| render_snapshot_files(files, committed_budget))
        .unwrap_or_else(|| NO_BASE.to_string());
    let working_tree = render_snapshot_files(working_tree_files, working_tree_budget);

    output.push_str(COMMITTED_HEADING);
    output.push_str(&committed);
    output.push_str(WORKING_TREE_HEADING);
    output.push_str(&working_tree);
}

pub(crate) fn detect_base_branch(repo: &Path) -> Option<BaseBranch> {
    run_git(repo, &["symbolic-ref", "refs/remotes/origin/HEAD"])
        .ok()
        .and_then(|s| {
            s.trim()
                .strip_prefix("refs/remotes/origin/")
                .map(str::to_string)
        })
        .and_then(|branch| resolve_base_branch(repo, &branch))
        .or_else(|| {
            ["main", "master"]
                .into_iter()
                .find_map(|branch| resolve_base_branch(repo, branch))
        })
}

fn resolve_base_branch(repo: &Path, branch: &str) -> Option<BaseBranch> {
    let local = format!("refs/heads/{branch}");
    let remote = format!("refs/remotes/origin/{branch}");
    let has_local = run_git(repo, &["rev-parse", "--verify", &local]).is_ok();
    let has_remote = run_git(repo, &["rev-parse", "--verify", &remote]).is_ok();
    let use_remote = match (has_local, has_remote) {
        (false, false) => return None,
        (true, false) => false,
        (false, true) => true,
        (true, true) => {
            let behind = local_base_is_behind_remote(repo, &local, &remote);
            if behind {
                tracing::warn!(
                    "local {branch} is behind origin/{branch}; using origin/{branch} as the review base"
                );
            }
            behind
        }
    };
    Some(BaseBranch {
        name: branch.to_string(),
        revision: match use_remote {
            true => format!("origin/{branch}"),
            false => branch.to_string(),
        },
    })
}

/// A branch cut from `origin/main` while local `main` lags behind it has an older merge-base with
/// local `main`, so the "committed comparison" would include upstream commits that are not part
/// of the change. Prefer the candidate whose merge-base with HEAD is the newer one; equal or
/// diverged merge-bases keep the local ref. No network involved: only remote-tracking refs are
/// consulted.
fn local_base_is_behind_remote(repo: &Path, local: &str, remote: &str) -> bool {
    let merge_base = |candidate: &str| {
        run_git(repo, &["merge-base", "HEAD", candidate]).map(|sha| sha.trim().to_string())
    };
    match (merge_base(local), merge_base(remote)) {
        (Ok(local_base), Ok(remote_base)) if local_base != remote_base => run_git(
            repo,
            &["merge-base", "--is-ancestor", &local_base, &remote_base],
        )
        .is_ok(),
        _ => false,
    }
}

fn run_git(repo: &Path, args: &[&str]) -> Result<String> {
    let output = std::process::Command::new("git")
        .args(args)
        .current_dir(repo)
        .output()?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eyre::bail!("git {}: {}", args.join(" "), stderr.trim());
    }
    Ok(String::from_utf8(output.stdout)?)
}

/// Some Git plumbing uses exit 1 for a valid negative result. Preserve every other failure.
fn run_git_optional(repo: &Path, args: &[&str]) -> Result<Option<String>> {
    let output = std::process::Command::new("git")
        .args(args)
        .current_dir(repo)
        .output()?;
    match output.status.code() {
        Some(0) => Ok(Some(String::from_utf8(output.stdout)?)),
        Some(1) => Ok(None),
        _ => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            eyre::bail!("git {}: {}", args.join(" "), stderr.trim());
        }
    }
}

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

    struct FailingFlush;

    impl std::io::Write for FailingFlush {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Err(std::io::Error::other("closed pipe"))
        }
    }

    /// 0 / 1 / 3 is a subprocess contract; a degraded verdict whose report cannot be flushed is
    /// a hard failure, not a degraded one, and an already-reported failure adds no output.
    #[test]
    fn exit_codes_follow_the_contract() {
        assert_eq!(finish(Ok(Exit::Clean), &mut Vec::new()), 0);
        assert_eq!(finish(Ok(Exit::Degraded), &mut Vec::new()), 3);
        assert_eq!(finish(Ok(Exit::Failed), &mut Vec::new()), 1);
        assert_eq!(finish(Err(eyre::eyre!("boom")), &mut Vec::new()), 1);
        assert_eq!(finish(Ok(Exit::Degraded), &mut FailingFlush), 1);
        assert_eq!(finish(Ok(Exit::Clean), &mut FailingFlush), 0);
    }

    #[test]
    fn git_discovers_primary_and_linked_worktree_roots() {
        let dir = tempfile::tempdir().unwrap();
        let primary = dir.path().join("primary");
        std::fs::create_dir(&primary).unwrap();
        run_git(&primary, &["init", "-b", "main"]).unwrap();
        run_git(
            &primary,
            &[
                "-c",
                "user.name=Test",
                "-c",
                "user.email=test@example.com",
                "commit",
                "--allow-empty",
                "-m",
                "initial",
            ],
        )
        .unwrap();

        let linked = dir.path().join("linked");
        run_git(
            &primary,
            &["worktree", "add", "-b", "feature", linked.to_str().unwrap()],
        )
        .unwrap();

        let primary = primary.canonicalize().unwrap();
        let linked = linked.canonicalize().unwrap();
        assert!(primary.join(".git").is_dir());
        assert!(linked.join(".git").is_file());
        assert_eq!(git_worktree_root(&primary).as_deref(), Some(&*primary));
        assert_eq!(git_worktree_root(&linked).as_deref(), Some(&*linked));

        let nested = linked.join("nested");
        std::fs::create_dir(&nested).unwrap();
        assert_eq!(git_worktree_root(&nested).as_deref(), Some(&*linked));

        let fake = dir.path().join("fake");
        std::fs::create_dir(&fake).unwrap();
        std::fs::write(fake.join(".git"), "not a gitdir pointer").unwrap();
        assert!(git_worktree_root(&fake).is_none());
    }

    #[test]
    fn base_branch_prefers_origin_only_when_local_is_behind_it() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        let commit = |msg: &str| {
            run_git(
                repo,
                &[
                    "-c",
                    "user.name=Test",
                    "-c",
                    "user.email=test@example.com",
                    "commit",
                    "--allow-empty",
                    "-m",
                    msg,
                ],
            )
            .unwrap()
        };
        let sha = || {
            run_git(repo, &["rev-parse", "HEAD"])
                .unwrap()
                .trim()
                .to_string()
        };
        run_git(repo, &["init", "-b", "main"]).unwrap();
        commit("a");
        let a = sha();
        commit("b");
        let b = sha();
        run_git(repo, &["switch", "-c", "feature"]).unwrap();
        commit("c");
        let revision = |remote: Option<&str>| {
            match remote {
                Some(sha) => run_git(repo, &["update-ref", "refs/remotes/origin/main", sha]),
                None => run_git(repo, &["update-ref", "-d", "refs/remotes/origin/main"]),
            }
            .unwrap();
            resolve_base_branch(repo, "main").unwrap().revision
        };

        // feature was cut from b, but local main was never fast-forwarded past a
        run_git(repo, &["update-ref", "refs/heads/main", &a]).unwrap();
        assert_eq!(revision(Some(&b)), "origin/main");
        assert_eq!(revision(Some(&a)), "main");
        assert_eq!(revision(None), "main");

        // local main ahead of, or equal to, origin keeps the local ref
        run_git(repo, &["update-ref", "refs/heads/main", &b]).unwrap();
        assert_eq!(revision(Some(&a)), "main");
        assert_eq!(revision(Some(&b)), "main");
    }

    #[test]
    fn diff_context_is_a_frozen_revision_and_file_snapshot() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        run_git(repo, &["init", "-b", "main"]).unwrap();
        std::fs::write(repo.join("base.txt"), "base\n").unwrap();
        run_git(repo, &["add", "base.txt"]).unwrap();
        run_git(
            repo,
            &[
                "-c",
                "user.name=Test",
                "-c",
                "user.email=test@example.com",
                "commit",
                "-m",
                "initial",
            ],
        )
        .unwrap();
        let base_sha = run_git(repo, &["rev-parse", "HEAD"])
            .unwrap()
            .trim()
            .to_string();

        run_git(repo, &["switch", "-c", "feature"]).unwrap();
        std::fs::write(repo.join("committed.txt"), "committed\n").unwrap();
        run_git(repo, &["add", "committed.txt"]).unwrap();
        run_git(
            repo,
            &[
                "-c",
                "user.name=Test",
                "-c",
                "user.email=test@example.com",
                "commit",
                "-m",
                "feature",
            ],
        )
        .unwrap();
        let head_sha = run_git(repo, &["rev-parse", "HEAD"])
            .unwrap()
            .trim()
            .to_string();
        std::fs::write(repo.join("committed.txt"), "working tree\n").unwrap();
        std::fs::write(repo.join("untracked.txt"), "untracked\n").unwrap();

        let context = detect_diff_context(repo).unwrap();
        for expected in [
            "## Frozen review snapshot".to_string(),
            "- Branch: `feature`".to_string(),
            format!("- HEAD: `{head_sha}`"),
            format!("- Base: `main` @ `{base_sha}`"),
            format!("- Merge base: `{base_sha}`"),
            format!("git diff {base_sha} {head_sha} --"),
            "- Working tree: dirty".to_string(),
            "- `A\tcommitted.txt\t+1 -0`".to_string(),
            "- ` M committed.txt`".to_string(),
            "- `?? untracked.txt`".to_string(),
        ] {
            assert!(
                context.contains(&expected),
                "missing {expected:?}:\n{context}"
            );
        }
    }

    #[test]
    fn diff_context_falls_back_to_direct_tree_comparison_for_unrelated_histories() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        run_git(repo, &["init", "-b", "main"]).unwrap();
        std::fs::write(repo.join("base.txt"), "base\n").unwrap();
        run_git(repo, &["add", "base.txt"]).unwrap();
        run_git(
            repo,
            &[
                "-c",
                "user.name=Test",
                "-c",
                "user.email=test@example.com",
                "commit",
                "-m",
                "base",
            ],
        )
        .unwrap();

        run_git(repo, &["switch", "--orphan", "feature"]).unwrap();
        std::fs::write(repo.join("feature.txt"), "feature\n").unwrap();
        run_git(repo, &["add", "--all"]).unwrap();
        run_git(
            repo,
            &[
                "-c",
                "user.name=Test",
                "-c",
                "user.email=test@example.com",
                "commit",
                "-m",
                "feature",
            ],
        )
        .unwrap();

        assert!(run_git(repo, &["merge-base", "main", "HEAD"]).is_err());
        let context = detect_diff_context(repo).unwrap();
        assert!(context.len() <= MAX_SNAPSHOT_BYTES);
    }

    #[test]
    fn line_counts_annotate_in_order_and_fall_back_on_mismatch() {
        let entries = vec!["M\ta.rs".to_string(), "A\tlogo.png".to_string()];
        assert_eq!(
            with_line_counts(entries.clone(), "3\t1\ta.rs\n-\t-\tlogo.png\n"),
            vec!["M\ta.rs\t+3 -1", "A\tlogo.png\tbinary"]
        );
        assert_eq!(with_line_counts(entries.clone(), "3\t1\ta.rs\n"), entries);
    }

    #[test]
    fn snapshot_file_maps_share_a_fixed_rendered_byte_budget() {
        let files = (0..1_000)
            .map(|index| format!("{index}-{}", "x".repeat(4_000)))
            .collect::<Vec<_>>();
        let rendered = render_snapshot_files(&files, 16 * 1024);
        assert!(rendered.len() <= 16 * 1024);
        let rendered_files = rendered
            .lines()
            .filter(|line| line.starts_with("- `"))
            .count();
        assert!(rendered_files < files.len());
        let omitted = files.len() - rendered_files;
        assert!(
            rendered
                .lines()
                .last()
                .is_some_and(|marker| marker.contains(&omitted.to_string()))
        );

        let mut snapshot = String::new();
        append_snapshot_file_sections(&mut snapshot, Some(&files), &files);
        assert!(snapshot.len() <= MAX_SNAPSHOT_BYTES);
    }
}