nitpicker 0.9.5

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
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
use crate::debate;
use crate::prompts::{ReviewScope, RunTask};
use crate::review;
use eyre::{Result, WrapErr};
use nitpicker_agent::config::Config;
use serde::Deserialize;
use sha2::Digest;
use std::path::{Path, PathBuf};
use std::process::Command;

fn lock_path(repo: &Path) -> PathBuf {
    // Linked worktrees have different roots but share refs and remote-tracking state. Key the
    // process lock by Git's common directory so every worktree of one repository serializes those
    // mutations together.
    let identity = git_common_dir(repo)
        .or_else(|| repo.canonicalize().ok())
        .unwrap_or_else(|| repo.to_path_buf());
    let hash = sha2::Sha256::digest(identity.as_os_str().as_encoded_bytes());
    let hash_hex: String = hash.iter().map(|b| format!("{b:02x}")).collect();
    std::env::temp_dir().join(format!("nitpicker-pr-review-{hash_hex}.lock"))
}

fn git_common_dir(repo: &Path) -> Option<PathBuf> {
    let output = Command::new("git")
        .args(["rev-parse", "--git-common-dir"])
        .current_dir(repo)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }

    let path = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
    let path = if path.is_absolute() {
        path
    } else {
        repo.join(path)
    };
    path.canonicalize().ok()
}

struct PrLock {
    // unix: an open fd holding an advisory `flock` for the process lifetime (the lock is the fd, not
    // the file's existence). non-unix: the exclusively-created lock file's path, removed on drop.
    #[cfg(unix)]
    _file: std::fs::File,
    #[cfg(not(unix))]
    path: PathBuf,
}

impl PrLock {
    #[cfg(unix)]
    fn acquire(repo: &Path) -> Result<Self> {
        use std::os::unix::io::AsRawFd;
        let path = lock_path(repo);
        // Advisory `flock(LOCK_EX|LOCK_NB)` held for the process lifetime. The kernel releases it
        // when the fd closes — normal return, `?`, or crash — so there is no stale-pid bookkeeping
        // and no TOCTOU window between a staleness check and an exclusive create (the previous
        // pid-file scheme had both, letting two racers each delete and recreate the lock). The lock
        // file lives at a fixed per-repo path and is never unlinked: unlinking it would let a racing
        // process create a *new* inode and lock that independently. (Advisory flock is unreliable
        // over NFS; PR review runs against a local working tree, so this is acceptable.)
        let file = std::fs::OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .truncate(false)
            .open(&path)
            .wrap_err("failed to open PR review lock file")?;
        let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
        if rc != 0 {
            let err = std::io::Error::last_os_error();
            match err.raw_os_error() {
                Some(code) if code == libc::EWOULDBLOCK => eyre::bail!(
                    "Another PR review is already running for this repo (lock file: {}). Wait for it to finish.",
                    path.display()
                ),
                _ => return Err(err).wrap_err("failed to acquire PR review lock"),
            }
        }
        Ok(Self { _file: file })
    }

    #[cfg(not(unix))]
    fn acquire(repo: &Path) -> Result<Self> {
        // No flock: fall back to exclusive create. A crashed run leaves a lock the user must remove
        // by hand (no crash-release), but nitpicker targets unix in practice.
        let path = lock_path(repo);
        match std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&path)
        {
            Ok(_) => Ok(Self { path }),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => eyre::bail!(
                "Another PR review is already running for this repo (lock file: {}). Remove it if it crashed.",
                path.display()
            ),
            Err(e) => Err(e).wrap_err("failed to create lock file"),
        }
    }
}

impl Drop for PrLock {
    fn drop(&mut self) {
        // unix: dropping `_file` closes the fd and releases the flock; the lock file is left in
        // place by design. non-unix: remove the exclusive-create lock file.
        #[cfg(not(unix))]
        let _ = std::fs::remove_file(&self.path);
    }
}

#[derive(Debug, clap::Args)]
pub struct PrArgs {
    /// Full GitHub PR URL (https://github.com/owner/repo/pull/N)
    pub url: Option<String>,
    #[command(flatten)]
    pub context: crate::ContextFileArgs,
    #[command(flatten)]
    pub presets: crate::PresetArgs,
    #[arg(long)]
    pub prompt: Option<String>,
    #[arg(long)]
    pub no_debate: bool,
    #[arg(long)]
    pub alloy: bool,
    #[arg(long, default_value = "5")]
    pub rounds: usize,
    #[arg(long, value_parser = crate::parse_positive_usize)]
    pub max_turns: Option<usize>,
    /// Skip posting review as a PR comment
    #[arg(long)]
    pub no_comment: bool,
    /// Always review in a fresh temp clone, even if the current repo matches the PR's origin
    #[arg(long)]
    pub clone: bool,
    /// Emit a single machine-readable JSON object on stdout (for embedding); human output goes to stderr
    #[arg(long)]
    pub json: bool,
}

impl PrArgs {
    fn output_format(&self) -> crate::output::OutputFormat {
        match self.json {
            true => crate::output::OutputFormat::Json,
            false => crate::output::OutputFormat::Text,
        }
    }
}

#[derive(Deserialize)]
struct PrMeta {
    title: String,
    body: String,
    #[serde(rename = "headRefOid")]
    head_ref_oid: String,
    /// The PR's target branch — the trust anchor `pr` mode reads `nitpicker.toml` from.
    #[serde(rename = "baseRefName")]
    base_ref_name: String,
}

#[derive(Deserialize)]
struct PrComment {
    // A comment from a deleted/ghost GitHub account has `author: null`; keep it optional so one
    // such comment doesn't fail the whole comments-list deserialize and abort the run.
    author: Option<PrCommentAuthor>,
    body: String,
}

#[derive(Deserialize)]
struct PrCommentAuthor {
    login: String,
}

pub fn check_gh() -> Result<()> {
    let status = Command::new("gh").arg("--version").output();
    match status {
        Ok(o) if o.status.success() => Ok(()),
        _ => eyre::bail!(
            "`gh` CLI not found or not working. Install it from https://cli.github.com/ and run `gh auth login`."
        ),
    }
}

fn fetch_pr_meta(url: Option<&str>, repo: &Path) -> Result<PrMeta> {
    let mut cmd = Command::new("gh");
    cmd.args(["pr", "view", "--json", "title,body,headRefOid,baseRefName"])
        .current_dir(repo);
    if let Some(u) = url {
        cmd.arg(u);
    }
    let out = cmd.output().wrap_err("failed to run gh pr view")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!("gh pr view failed: {}", stderr.trim());
    }
    serde_json::from_slice(&out.stdout).wrap_err("failed to parse gh pr view output")
}

fn fetch_pr_comments(url: Option<&str>, repo: &Path) -> Result<Vec<PrComment>> {
    let mut cmd = Command::new("gh");
    cmd.args(["pr", "view", "--json", "comments"])
        .current_dir(repo);
    if let Some(u) = url {
        cmd.arg(u);
    }
    let out = cmd
        .output()
        .wrap_err("failed to run gh pr view --json comments")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!("gh pr view comments failed: {}", stderr.trim());
    }
    #[derive(Deserialize)]
    struct CommentsWrapper {
        comments: Vec<PrComment>,
    }
    let wrapper: CommentsWrapper =
        serde_json::from_slice(&out.stdout).wrap_err("failed to parse gh pr comments output")?;
    Ok(wrapper.comments)
}

pub fn parse_pr_url(url: &str) -> Result<(String, u32)> {
    // expects https://github.com/owner/repo/pull/N
    let url_obj = url::Url::parse(url).wrap_err("invalid URL")?;
    match url_obj.host_str() {
        Some("github.com") => {}
        Some(host) => eyre::bail!("only GitHub PRs are supported (got host: {host})"),
        None => eyre::bail!("URL has no host"),
    }
    let segments: Vec<&str> = url_obj
        .path_segments()
        .ok_or_else(|| eyre::eyre!("URL has no path"))?
        .filter(|s| !s.is_empty())
        .collect();
    match segments.as_slice() {
        [owner, repo, "pull", n, ..] => {
            let pr_number: u32 = n
                .parse()
                .wrap_err_with(|| format!("PR number `{n}` is not a valid integer"))?;
            Ok((format!("{owner}/{repo}"), pr_number))
        }
        _ => eyre::bail!("expected a URL like https://github.com/owner/repo/pull/N, got: {url}"),
    }
}

/// Extracts `owner/repo` from a git remote URL (https or ssh).
fn slug_from_remote_url(url: &str) -> Option<String> {
    let url = url.trim().trim_end_matches(".git");
    if url.contains("://") {
        // https://github.com/owner/repo
        let parsed = url::Url::parse(url).ok()?;
        let path = parsed.path().trim_start_matches('/');
        let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        if parts.len() >= 2 {
            return Some(format!("{}/{}", parts[0], parts[1]));
        }
    } else if let Some(colon) = url.find(':') {
        // git@github.com:owner/repo or hostname:owner/repo (custom ~/.ssh/config alias)
        let after = &url[colon + 1..];
        let parts: Vec<&str> = after.split('/').filter(|s| !s.is_empty()).collect();
        if parts.len() >= 2 {
            return Some(format!("{}/{}", parts[0], parts[1]));
        }
    }
    None
}

fn get_origin_slug(repo: &Path) -> Option<String> {
    let out = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(repo)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    slug_from_remote_url(&String::from_utf8_lossy(&out.stdout))
}

fn get_head_commit(repo: &Path) -> Result<String> {
    let out = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(repo)
        .output()
        .wrap_err("failed to get HEAD commit")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!("git rev-parse HEAD failed: {}", stderr.trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// Where HEAD pointed before nitpicker checked out the PR branch, so it can be restored on exit.
enum HeadState {
    Branch(String),
    Detached(String),
}

fn get_head_state(repo: &Path) -> Result<HeadState> {
    // symbolic-ref succeeds for attached HEAD, fails for detached
    let out = Command::new("git")
        .args(["symbolic-ref", "-q", "--short", "HEAD"])
        .current_dir(repo)
        .output()
        .wrap_err("failed to get current branch")?;
    if out.status.success() {
        return Ok(HeadState::Branch(
            String::from_utf8_lossy(&out.stdout).trim().to_string(),
        ));
    }
    // detached HEAD — capture the commit so restore can re-detach onto it
    let out = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(repo)
        .output()
        .wrap_err("failed to get current commit")?;
    if !out.status.success() {
        eyre::bail!("failed to get current branch or commit");
    }
    Ok(HeadState::Detached(
        String::from_utf8_lossy(&out.stdout).trim().to_string(),
    ))
}

fn restore_head(repo: &Path, head: &HeadState) {
    // a detached HEAD must be restored with `switch --detach`: `git switch -- <sha>` refuses a bare
    // commit ("a branch is expected, got commit"), which would silently strand the user on
    // nitpicker's PR branch.
    let (args, recover): (Vec<&str>, String) = match head {
        HeadState::Branch(b) => (vec!["switch", "--", b], format!("git switch -- {b}")),
        HeadState::Detached(sha) => (
            vec!["switch", "--detach", sha],
            format!("git switch --detach {sha}"),
        ),
    };
    let result = Command::new("git").args(&args).current_dir(repo).output();
    let detail = match result {
        Ok(out) if out.status.success() => return,
        Ok(out) => String::from_utf8_lossy(&out.stderr).trim().to_string(),
        Err(e) => e.to_string(),
    };
    eprintln!(
        "warning: could not restore HEAD in {repo}; run `{recover}` to recover ({detail})",
        repo = repo.display(),
    );
}

/// Restores the user's original HEAD when dropped, so a panic or early error anywhere in the review
/// path (not just a clean return) can't strand them on nitpicker's PR branch.
struct BranchRestoreGuard {
    repo: PathBuf,
    head: HeadState,
}

impl Drop for BranchRestoreGuard {
    fn drop(&mut self) {
        restore_head(&self.repo, &self.head);
    }
}

fn assert_clean_working_tree(repo: &Path) -> Result<()> {
    let out = Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(repo)
        .output()
        .wrap_err("failed to run git status")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!("git status failed: {}", stderr.trim());
    }
    let porcelain = String::from_utf8_lossy(&out.stdout);
    if !porcelain.trim().is_empty() {
        eyre::bail!(
            "working tree has uncommitted changes; commit or stash before running `nitpicker pr` against a different PR:\n{}",
            porcelain.trim_end()
        );
    }
    Ok(())
}

/// Refreshes remote-tracking branches so `detect_base_branch` doesn't operate on stale state.
/// Fatal: if origin can't be fetched, the diff base would be stale and the review unreliable.
fn refresh_remote_branches(repo: &Path) -> Result<()> {
    let out = Command::new("git")
        .args(["fetch", "origin", "--prune"])
        .current_dir(repo)
        .output()
        .wrap_err("failed to refresh remote branches")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!(
            "git fetch origin failed: {}\nReview would run against a stale base branch. Fix the remote or pass `--clone` to review in a fresh temp clone.",
            stderr.trim()
        );
    }
    Ok(())
}

/// Fetches the PR head and checks it out as a local branch `nitpicker/pr-{pr_number}`.
/// Uses a namespaced name to avoid colliding with or deleting any user-owned branch.
/// Always fetches so the review is always against the actual PR head, not stale local state.
fn checkout_pr_branch(repo: &Path, pr_number: u32) -> Result<()> {
    assert_clean_working_tree(repo)?;

    // Fetch into a private named ref instead of relying on the shared `.git/FETCH_HEAD`, which any
    // other fetch in the repo (IDE autofetch, a shell prompt plugin, cron) could rewrite between the
    // fetch and the checkout — silently pointing the review branch at unrelated code. The leading
    // `+` forces the update so a force-pushed PR head still lands. The ref is reused (force-updated)
    // each run, so it is namespace litter at worst, never stale.
    let fetch_ref = format!("refs/nitpicker/pr-{pr_number}-head");
    let refspec = format!("+refs/pull/{pr_number}/head:{fetch_ref}");
    let out = Command::new("git")
        .args(["fetch", "origin", &refspec])
        .current_dir(repo)
        .output()
        .wrap_err("failed to fetch PR branch")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!("git fetch failed: {}", stderr.trim());
    }

    // namespaced branch — safe to delete, will never match a user branch
    let branch = format!("nitpicker/pr-{pr_number}");

    if matches!(get_head_state(repo), Ok(HeadState::Branch(b)) if b == branch) {
        // already on our tracking branch — fast-forward only
        let out = Command::new("git")
            .args(["merge", "--ff-only", &fetch_ref])
            .current_dir(repo)
            .output()
            .wrap_err("failed to fast-forward PR branch")?;
        if !out.status.success() {
            let stderr = String::from_utf8_lossy(&out.stderr);
            eyre::bail!("could not fast-forward to PR head: {}", stderr.trim());
        }
        return Ok(());
    }

    // delete stale local branch if present (safe: it's our namespace, not a user branch)
    let _ = Command::new("git")
        .args(["branch", "-D", &branch])
        .current_dir(repo)
        .output();

    let out = Command::new("git")
        .args(["switch", "-c", &branch, "--no-track", &fetch_ref])
        .current_dir(repo)
        .output()
        .wrap_err("failed to checkout PR branch")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!("git switch failed: {}", stderr.trim());
    }
    Ok(())
}

fn clone_pr(repo_slug: &str, pr_number: u32, dir: &Path) -> Result<()> {
    let clone_url = format!("https://github.com/{repo_slug}.git");
    // partial clone: full commit/tree history (so merge-base with the PR is always reachable),
    // blobs fetched lazily on demand. Avoids the shallow-depth merge-base gap.
    let out = Command::new("git")
        .args(["clone", "--filter=blob:none", &clone_url, "."])
        .current_dir(dir)
        .output()
        .wrap_err("failed to run git clone")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!("git clone failed: {}", stderr.trim());
    }
    checkout_pr_branch(dir, pr_number)
}

/// Create the working directory for a temporary clone under a stable repository basename.
///
/// The parent remains the unique `TempDir` that owns cleanup, while the child makes user-facing
/// path-derived surfaces (notably the terminal title) identify the repository instead of a random
/// temporary-directory suffix.
fn create_temp_clone_repo_dir(temp_root: &Path, repo_slug: &str) -> Result<PathBuf> {
    let repo_name = repo_slug
        .rsplit('/')
        .next()
        .filter(|name| !name.is_empty() && *name != "." && *name != ".." && !name.contains('\\'))
        .ok_or_else(|| eyre::eyre!("invalid GitHub repository slug: {repo_slug}"))?;
    let path = temp_root.join(repo_name);
    std::fs::create_dir(&path).wrap_err_with(|| {
        format!(
            "failed to create temporary clone directory {}",
            path.display()
        )
    })?;
    // Canonicalize so the workspace root matches the canonical paths the tools resolve files to
    // (on macOS the temp dir lives under /var → /private/var).
    path.canonicalize()
        .wrap_err("failed to canonicalize temporary clone directory")
}

fn post_comment(url: Option<&str>, repo: &Path, body: &str) -> Result<()> {
    let mut cmd = Command::new("gh");
    cmd.args(["pr", "comment", "--body", body])
        .current_dir(repo);
    if let Some(u) = url {
        cmd.arg(u);
    }
    let out = cmd.output().wrap_err("failed to run gh pr comment")?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        eyre::bail!("gh pr comment failed: {}", stderr.trim());
    }
    Ok(())
}

fn build_pr_prompt(
    meta: &PrMeta,
    comments: &[PrComment],
    diff_context: &str,
    extra: Option<&str>,
) -> String {
    let mut parts = vec![format!("## PR: {}", meta.title)];
    if !meta.body.trim().is_empty() {
        parts.push(meta.body.trim().to_string());
    }
    if !comments.is_empty() {
        let mut comments_section = String::from("## PR Comments\n");
        for comment in comments {
            let login = comment
                .author
                .as_ref()
                .map(|a| a.login.as_str())
                .unwrap_or("[deleted]");
            comments_section.push_str(&format!("**{}**: {}\n\n", login, comment.body));
        }
        parts.push(comments_section);
    }
    parts.push(diff_context.to_string());
    if let Some(p) = extra {
        if !p.trim().is_empty() {
            parts.push(format!("Additional instructions: {p}"));
        }
    }
    parts.join("\n\n")
}

enum PrFlow {
    /// no URL — review current branch against its PR, no checkout needed
    CurrentBranch { repo: PathBuf },
    /// URL points to a PR in the user's own repo and `--clone` was not set
    InPlace {
        repo: PathBuf,
        url: String,
        pr_number: u32,
    },
    /// URL points elsewhere, or `--clone` forces a fresh clone
    TempClone {
        url: String,
        slug: String,
        pr_number: u32,
    },
}

impl PrFlow {
    fn user_repo(&self) -> Option<&Path> {
        match self {
            Self::CurrentBranch { repo } | Self::InPlace { repo, .. } => Some(repo),
            Self::TempClone { .. } => None,
        }
    }
}

/// Returns the run's degraded flag; the caller maps it to exit code 3 — after this
/// function returns, so the checkout-restore/lock guards inside have already dropped
/// (`process::exit` skips destructors).
pub async fn run_pr(
    args: PrArgs,
    common: crate::CommonArgs,
    context_files: Vec<PathBuf>,
    preset_names: Vec<String>,
) -> Result<bool> {
    let start = std::time::Instant::now();
    let format = args.output_format();
    // in json mode every failure (incl. config loading) must still leave a
    // parseable object on stdout and exit non-zero; text mode keeps the
    // eyre-to-stderr behavior.
    match run_pr_inner(args, common, context_files, preset_names, start).await {
        Ok(degraded) => Ok(degraded),
        Err(e) => match format {
            crate::output::OutputFormat::Text => Err(e),
            crate::output::OutputFormat::Json => {
                let env = crate::output::PrReviewOutput::error(
                    format!("{e:#}"),
                    start.elapsed().as_millis() as u64,
                );
                let _ = crate::output::emit_json(&env);
                std::process::exit(1);
            }
        },
    }
}

async fn run_pr_inner(
    args: PrArgs,
    common: crate::CommonArgs,
    context_files: Vec<PathBuf>,
    preset_names: Vec<String>,
    start: std::time::Instant,
) -> Result<bool> {
    check_gh()?;

    let prepared = prepare_pr(&args, &common.repo)?;

    // Config loads AFTER prep because its repo-level source is the PR base branch blob —
    // the base ref comes from the PR metadata, and the checkout must already have happened
    // for the working tree to even be the head. Guards restore state if this errors.
    let mut config = load_pr_config(common.config.as_deref(), &prepared)?;
    // Resolve presets and CLI-only routing validation before free-model resolution: pure usage
    // errors must fail before its smoke calls, and stay inside run_pr_inner for the JSON contract.
    let presets = crate::presets::resolve(&preset_names, &config)?;
    let (alloy, fallback) = crate::resolve_routing_modes(&config, args.alloy, common.fallback)?;
    let execution = PrReviewExecution {
        verbose: common.verbose,
        alloy,
        fallback,
    };
    crate::finalize_routing_config(&mut config, fallback).await?;
    let config = config;

    // `prepared` drops at the end of this scope, after the review completes: HEAD is restored
    // (panic- and early-error-safe), then the temp dir removed, while the lock is still held —
    // see the field order on `PreparedPr`.
    run_review_inner(
        &prepared,
        &args,
        &context_files,
        &presets,
        &config,
        execution,
        start,
    )
    .await
}

#[derive(Clone, Copy)]
struct PrReviewExecution {
    verbose: bool,
    alloy: bool,
    fallback: bool,
}

/// `pr` mode never reads `nitpicker.toml` from the working tree: the tree holds the PR
/// head — target-controlled content that could redirect `base_url` (key exfiltration) or
/// override preset rubrics (prompt injection into the trusted rubric slot). Repo-level
/// config comes from the PR base branch blob instead, falling back to the global config;
/// an explicit `--config` path stays trusted and unchanged.
fn load_pr_config(explicit: Option<&Path>, prepared: &PreparedPr) -> Result<Config> {
    if explicit.is_some() {
        return crate::load_config(explicit, &prepared.repo);
    }
    // `origin/<base>` is only a trust anchor if `origin` is the GitHub repo the PR metadata
    // came from. The in-place flow selects on the owner/repo slug alone, so an unrelated
    // remote with a matching path (`https://attacker.example/owner/repo`) would otherwise
    // supply the "base branch" policy.
    let base_blob = match origin_is_github(&prepared.repo) {
        true => read_base_branch_config(&prepared.repo, &prepared.meta.base_ref_name),
        false => {
            tracing::warn!(
                "`origin` is not a github.com remote; ignoring its nitpicker.toml and using \
                 the global config"
            );
            None
        }
    };
    let (repo_config, warning) = choose_repo_config(
        base_blob,
        head_config_state(&prepared.repo, &prepared.meta.base_ref_name),
    );
    if let Some(warning) = warning {
        tracing::warn!("{warning}");
    }
    match repo_config {
        Some(content) => {
            let config: Config = toml::from_str(&content)
                .map_err(|e| eyre::eyre!("invalid nitpicker.toml on the PR base branch: {e}"))?;
            config.validate_structure()?;
            Ok(config)
        }
        None => crate::load_global_config(),
    }
}

/// Whether `origin` is the GitHub repository the PR metadata and `refs/pull/*` come from.
/// Slug matching ignores the remote entirely, so this is what makes `origin/<base>`
/// trustworthy as repo policy.
fn origin_is_github(repo: &Path) -> bool {
    let out = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(repo)
        .output();
    let url = match out {
        Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_string(),
        _ => return false,
    };
    is_trusted_github_remote(&url)
}

/// An *authenticated GitHub transport* — host alone is not enough. `file://github.com/…`
/// parses with host `github.com` while git reads a local, attacker-writable repository, and
/// `git://`/`http://` reach the network unauthenticated. Only `https`, `ssh`, and git's
/// scp-like form qualify.
fn is_trusted_github_remote(url: &str) -> bool {
    let url = url.trim();
    // `<transport>::<address>` is remote-helper syntax: git runs `git-remote-<transport>`
    // and never reads it as scp-form, so `github.com::<address>` would otherwise look like
    // the host `github.com` here while git fetches from somewhere else entirely.
    if url.contains("::") {
        return false;
    }
    let host = match url.contains("://") {
        true => match url::Url::parse(url) {
            Ok(parsed) => match parsed.scheme() {
                "https" | "ssh" => parsed.host_str().map(str::to_string),
                _ => None,
            },
            Err(_) => None,
        },
        false => remote_host(url),
    };
    host.is_some_and(|host| host.eq_ignore_ascii_case("github.com"))
}

/// Host of a git remote URL, for both URL forms git accepts (`scheme://host/path` and the
/// scp-like `[user@]host:path`).
fn remote_host(url: &str) -> Option<String> {
    let url = url.trim();
    match url.contains("://") {
        true => url::Url::parse(url)
            .ok()
            .and_then(|parsed| parsed.host_str().map(str::to_string)),
        false => {
            // git only reads `[user@]host:path` as a remote when the colon precedes any
            // slash — otherwise it is a local path, which has no host at all.
            let colon = url.find(':')?;
            if url[..colon].contains('/') {
                return None;
            }
            let host = url[..colon].rsplit('@').next()?;
            match host.is_empty() {
                true => None,
                false => Some(host.to_string()),
            }
        }
    }
}

/// `git show origin/<base>:nitpicker.toml` from the reviewed repo. A missing file is normal
/// (silent); an *unresolvable base ref* means repo policy could not be consulted at all, so
/// it warns rather than silently degrading to the global config.
fn read_base_branch_config(repo: &Path, base_ref: &str) -> Option<String> {
    if base_ref.is_empty() {
        return None;
    }
    let out = Command::new("git")
        .args(["show", &format!("origin/{base_ref}:nitpicker.toml")])
        .current_dir(repo)
        .output()
        .ok()?;
    match out.status.success() {
        true => String::from_utf8(out.stdout).ok(),
        false => {
            match git_object_id(repo, &format!("origin/{base_ref}")) {
                Some(_) => tracing::debug!(
                    base = base_ref,
                    "no nitpicker.toml on the PR base branch; using the global config"
                ),
                None => tracing::warn!(
                    base = base_ref,
                    "cannot resolve `origin/{base_ref}`, so the base branch's nitpicker.toml \
                     could not be read; using the global config"
                ),
            }
            None
        }
    }
}

/// The checked-out head's `nitpicker.toml` relative to the base branch's, compared by git
/// object id. Deliberately never reads the file from the working tree: that path is
/// target-controlled, and an unbounded read of a PR-supplied symlink (`/dev/zero`) would
/// hang or exhaust memory before the review even starts.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum HeadConfig {
    Absent,
    SameAsBase,
    Diverges,
}

fn head_config_state(repo: &Path, base_ref: &str) -> HeadConfig {
    let head = git_object_id(repo, "HEAD:nitpicker.toml");
    let base = git_object_id(repo, &format!("origin/{base_ref}:nitpicker.toml"));
    match (head, base) {
        (None, _) => HeadConfig::Absent,
        (Some(head), Some(base)) if head == base => HeadConfig::SameAsBase,
        (Some(_), _) => HeadConfig::Diverges,
    }
}

fn git_object_id(repo: &Path, revspec: &str) -> Option<String> {
    let out = Command::new("git")
        .args(["rev-parse", "--verify", "--quiet", revspec])
        .current_dir(repo)
        .output()
        .ok()?;
    match out.status.success() {
        true => Some(String::from_utf8_lossy(&out.stdout).trim().to_string()),
        false => None,
    }
}

/// Which repo-level config text `pr` mode uses, and what to tell the user about the
/// checked-out copy. Returns `(config_toml, warning)`; `None` config falls back to global.
fn choose_repo_config(
    base_blob: Option<String>,
    head: HeadConfig,
) -> (Option<String>, Option<&'static str>) {
    match (base_blob, head) {
        (Some(blob), HeadConfig::Diverges) => (
            Some(blob),
            Some(
                "checked-out nitpicker.toml differs from the PR base branch; using the base \
                 version — files on a PR head are target-controlled",
            ),
        ),
        (Some(blob), _) => (Some(blob), None),
        (None, HeadConfig::Absent) => (None, None),
        (None, _) => (
            None,
            Some(
                "ignoring nitpicker.toml from the checked-out PR head (absent on the PR base \
                 branch); using the global config",
            ),
        ),
    }
}

/// Everything the prep phase (flow resolution → lock → checkout/clone → metadata) hands to the
/// review phase. The guard field order is load-bearing: struct fields drop in DECLARATION
/// order, so restore-guard → tempdir → lock reproduces the prep locals' reverse-drop order —
/// HEAD is restored, then the temp dir removed, while the lock is still held.
struct PreparedPr {
    repo: PathBuf,
    url_for_gh: Option<String>,
    pr_number: Option<u32>,
    meta: PrMeta,
    comments: Vec<PrComment>,
    // set when we switch branches in the user's own repo; its Drop restores HEAD on the way out
    // (including on panic/early-error), so it must outlive the whole review
    _restore_guard: Option<BranchRestoreGuard>,
    _tmpdir_guard: Option<tempfile::TempDir>,
    _lock: Option<PrLock>,
}

fn prepare_pr(args: &PrArgs, repo_arg: &Path) -> Result<PreparedPr> {
    let repo_arg = repo_arg
        .canonicalize()
        .wrap_err("failed to canonicalize --repo path")?;
    let user_repo = crate::git_worktree_root(&repo_arg);

    let flow = match args.url.as_deref() {
        None => PrFlow::CurrentBranch {
            repo: user_repo
                .ok_or_else(|| eyre::eyre!("--repo must point inside a Git worktree"))?,
        },
        Some(u) => {
            let (slug, pr_number) = parse_pr_url(u)?;
            match user_repo.filter(|repo| {
                !args.clone && get_origin_slug(repo).as_deref() == Some(slug.as_str())
            }) {
                Some(repo) => PrFlow::InPlace {
                    repo,
                    url: u.to_string(),
                    pr_number,
                },
                None => PrFlow::TempClone {
                    url: u.to_string(),
                    slug,
                    pr_number,
                },
            }
        }
    };

    // Acquire the lock BEFORE any git mutation when we'll touch the user's working tree.
    // Temp clones use a fresh, unique temp dir per process, so concurrent runs don't conflict.
    let _lock = flow.user_repo().map(PrLock::acquire).transpose()?;

    let _tmpdir_guard: Option<tempfile::TempDir>;
    // set when we switch branches in the user's own repo; its Drop restores HEAD on the way out
    // (including on panic/early-error), so it must outlive the whole review below
    let _restore_guard: Option<BranchRestoreGuard>;

    // pr number is not part of PrMeta; carry it out of the flow for the json envelope
    let (repo, url_for_gh, meta, pr_number): (PathBuf, Option<String>, PrMeta, Option<u32>) =
        match flow {
            PrFlow::InPlace {
                repo: user_repo,
                url,
                pr_number,
            } => {
                // fetch meta first — a failure here leaves the branch untouched
                let meta = fetch_pr_meta(Some(&url), &user_repo)?;
                // refresh remote-tracking branches so the diff is computed against an up-to-date base
                refresh_remote_branches(&user_repo)?;
                // Skip the fetch+checkout dance only when HEAD already points at the PR head AND we
                // are on a real branch with a clean tree. Otherwise fall through to checkout:
                //   - a detached HEAD at the PR head must still get a named branch (else
                //     `detect_diff_context` bails) and a restore guard to re-detach afterwards;
                //   - a dirty tree must be rejected by `assert_clean_working_tree`, never reviewed —
                //     skipping would feed local uncommitted WIP into the review and the PR comment.
                let head_matches = get_head_commit(&user_repo)
                    .ok()
                    .is_some_and(|sha| sha == meta.head_ref_oid);
                let head = get_head_state(&user_repo)?;
                let can_skip = head_matches && matches!(head, HeadState::Branch(_));
                match can_skip {
                    true => {
                        assert_clean_working_tree(&user_repo)?;
                        _restore_guard = None;
                    }
                    false => {
                        checkout_pr_branch(&user_repo, pr_number).inspect_err(|_e| {
                            restore_head(&user_repo, &head);
                        })?;
                        _restore_guard = Some(BranchRestoreGuard {
                            repo: user_repo.clone(),
                            head,
                        });
                    }
                }
                _tmpdir_guard = None;
                (user_repo, Some(url), meta, Some(pr_number))
            }
            PrFlow::TempClone {
                url,
                slug,
                pr_number,
            } => {
                let cwd = std::env::current_dir().wrap_err("failed to get current directory")?;
                let meta = fetch_pr_meta(Some(&url), &cwd)?;
                let tmpdir = tempfile::TempDir::new().wrap_err("failed to create temp dir")?;
                let path = create_temp_clone_repo_dir(tmpdir.path(), &slug)?;
                clone_pr(&slug, pr_number, &path)?;
                _tmpdir_guard = Some(tmpdir);
                _restore_guard = None;
                (path, Some(url), meta, Some(pr_number))
            }
            PrFlow::CurrentBranch { repo: user_repo } => {
                let meta = fetch_pr_meta(None, &user_repo)?;
                // refresh remote-tracking branches so the diff is computed against an up-to-date base
                refresh_remote_branches(&user_repo)?;
                _tmpdir_guard = None;
                _restore_guard = None;
                (user_repo, None, meta, None)
            }
        };

    // if anything from here on fails (e.g. the comments fetch), the locals above drop in
    // reverse declaration order — HEAD restored, temp dir removed, lock released last — the
    // same teardown the returned struct encodes in its field order
    let comments = fetch_pr_comments(url_for_gh.as_deref(), &repo)?;

    Ok(PreparedPr {
        repo,
        url_for_gh,
        pr_number,
        meta,
        comments,
        _restore_guard,
        _tmpdir_guard,
        _lock,
    })
}

async fn run_review_inner(
    prepared: &PreparedPr,
    args: &PrArgs,
    context_files: &[PathBuf],
    presets: &[crate::presets::ReviewPreset],
    config: &Config,
    execution: PrReviewExecution,
    start: std::time::Instant,
) -> Result<bool> {
    use crate::output::{OutputFormat, PrInfo, PrReviewOutput, ReviewMode, Status};

    let repo = prepared.repo.as_path();
    let url_for_gh = prepared.url_for_gh.as_deref();
    let pr_number = prepared.pr_number;
    let meta = &prepared.meta;
    let comments: &[PrComment] = &prepared.comments;
    let PrReviewExecution {
        verbose,
        alloy: use_alloy,
        fallback: use_fallback,
    } = execution;

    const FOOTER: &str =
        "\n\n---\n🔍 Reviewed by [nitpicker](https://github.com/arsenyinfo/nitpicker)";

    let format = args.output_format();
    let diff_context = crate::detect_diff_context(repo)?;
    let full_prompt = crate::context::append_to_prompt(
        build_pr_prompt(meta, comments, &diff_context, args.prompt.as_deref()),
        &crate::context::load_context_files(context_files)?,
    );
    let max_turns = config.max_turns(args.max_turns)?;

    if use_alloy && args.no_debate {
        eprintln!("warning: --alloy has no effect with --no-debate");
    }
    let debate = !args.no_debate && config.default_debate();
    let (report, transcript_path, usage, degraded, coverage) = if debate {
        let outcome = debate::run_debate(
            repo,
            &full_prompt,
            config,
            debate::DebateOptions {
                max_rounds: args.rounds,
                max_turns,
                verbose,
                task: RunTask::Review {
                    scope: ReviewScope::Diff,
                    presets,
                },
                alloy: use_alloy,
                fallback: use_fallback,
                format,
            },
        )
        .await?;
        (
            outcome.report,
            outcome.transcript_path,
            outcome.usage,
            outcome.degraded,
            outcome.coverage,
        )
    } else {
        let outcome = review::run_review(
            repo,
            &full_prompt,
            config,
            review::ReviewOptions {
                max_turns,
                verbose,
                task: RunTask::Review {
                    scope: ReviewScope::Diff,
                    presets,
                },
                fallback: use_fallback,
                format,
            },
        )
        .await?;
        (
            outcome.report,
            std::path::PathBuf::new(),
            outcome.usage,
            outcome.degraded,
            outcome.coverage,
        )
    };

    match format {
        OutputFormat::Text => {
            println!("{report}");
            if !args.no_comment {
                post_comment(url_for_gh, repo, &format!("{report}{FOOTER}"))?;
            }
            if verbose && !transcript_path.as_os_str().is_empty() {
                eprintln!("\nTranscript saved to: {}", transcript_path.display());
            }
        }
        OutputFormat::Json => {
            // post the comment before emitting so its outcome is reflected in the
            // envelope rather than arriving after a success-looking object. a
            // posting failure is non-fatal here — the report itself succeeded.
            let comment_posted = match args.no_comment {
                true => false,
                false => match post_comment(url_for_gh, repo, &format!("{report}{FOOTER}")) {
                    Ok(()) => true,
                    Err(e) => {
                        tracing::warn!("failed to post PR comment: {e:#}");
                        false
                    }
                },
            };
            let envelope = PrReviewOutput {
                schema_version: crate::output::SCHEMA_VERSION,
                status: Status::Ok,
                pr: Some(PrInfo {
                    url: url_for_gh.map(str::to_string),
                    number: pr_number,
                    title: meta.title.clone(),
                    // report the commit actually reviewed (HEAD), not the oid from `gh pr view`,
                    // which can be stale if the PR was force-pushed between metadata fetch and
                    // checkout. Fall back to the metadata oid if HEAD can't be resolved.
                    head_sha: get_head_commit(repo).unwrap_or_else(|_| meta.head_ref_oid.clone()),
                }),
                mode: Some(match debate {
                    true => ReviewMode::Debate,
                    false => ReviewMode::Parallel,
                }),
                models: Some(crate::output::Models {
                    reviewers: config.reviewer.iter().map(|r| r.model.clone()).collect(),
                    aggregator: config.aggregator.model.clone(),
                }),
                presets: Some(presets.iter().map(|p| p.name.clone()).collect()),
                degraded: Some(degraded),
                coverage,
                report_markdown: Some(report),
                usage: Some(usage),
                comment_posted,
                duration_ms: start.elapsed().as_millis() as u64,
                error: None,
            };
            crate::output::emit_json(&envelope)?;
        }
    }

    Ok(degraded)
}

#[cfg(test)]
mod tests {
    use super::{
        BranchRestoreGuard, HeadConfig, HeadState, PrComment, choose_repo_config,
        create_temp_clone_repo_dir, get_head_state, head_config_state, is_trusted_github_remote,
        lock_path, read_base_branch_config, remote_host,
    };
    use std::path::Path;
    use std::process::Command;

    /// The working tree is the PR head, so its nitpicker.toml never wins: the base blob is
    /// used when present (warning iff the head copy diverges), and a head-only copy is
    /// ignored with a warning rather than trusted.
    #[test]
    fn repo_config_source_prefers_base_blob_and_never_the_head() {
        let s = |v: &str| Some(v.to_string());

        let (cfg, warn) = choose_repo_config(s("base"), HeadConfig::SameAsBase);
        assert_eq!(cfg.as_deref(), Some("base"));
        assert!(warn.is_none());

        let (cfg, warn) = choose_repo_config(s("base"), HeadConfig::Diverges);
        assert_eq!(cfg.as_deref(), Some("base"));
        assert!(warn.is_some());

        let (cfg, warn) = choose_repo_config(s("base"), HeadConfig::Absent);
        assert_eq!(cfg.as_deref(), Some("base"));
        assert!(warn.is_none());

        let (cfg, warn) = choose_repo_config(None, HeadConfig::Diverges);
        assert!(cfg.is_none());
        assert!(warn.is_some());

        let (cfg, warn) = choose_repo_config(None, HeadConfig::Absent);
        assert!(cfg.is_none());
        assert!(warn.is_none());
    }

    /// Only github.com counts: the in-place flow matches on the owner/repo slug alone, so a
    /// same-slug remote on another host must not be trusted as the PR's base branch.
    #[test]
    fn remote_host_is_extracted_from_both_url_forms() {
        for (url, expected) in [
            ("https://github.com/owner/repo.git", Some("github.com")),
            ("git@github.com:owner/repo.git", Some("github.com")),
            ("ssh://git@github.com/owner/repo", Some("github.com")),
            (
                "https://attacker.example/owner/repo.git",
                Some("attacker.example"),
            ),
            (
                "git@attacker.example:owner/repo.git",
                Some("attacker.example"),
            ),
            ("/local/path/repo", None),
            // why the scheme gate below exists: a file:// URL carries a host component, so
            // host matching alone would accept a local repository as "github.com"
            (
                "file://github.com/victim/repo/../../../tmp/attacker",
                Some("github.com"),
            ),
        ] {
            assert_eq!(remote_host(url).as_deref(), expected, "url: {url}");
        }
    }

    /// The host is necessary but not sufficient: only an authenticated GitHub transport
    /// makes `origin/<base>` a trust anchor. `file://github.com/…` parses with the right
    /// host yet reads a local (attacker-writable) repository, and `git://`/`http://` are
    /// unauthenticated.
    #[test]
    fn only_authenticated_github_transports_are_trusted() {
        for url in [
            "https://github.com/owner/repo.git",
            "ssh://git@github.com/owner/repo",
            "git@github.com:owner/repo.git",
        ] {
            assert!(is_trusted_github_remote(url), "must trust: {url}");
        }
        for url in [
            "file://github.com/victim/repo/../../../tmp/attacker-repo",
            "git://github.com/owner/repo",
            "http://github.com/owner/repo",
            "https://attacker.example/owner/repo.git",
            "git@attacker.example:owner/repo.git",
            // remote-helper syntax: git runs `git-remote-github.com` and fetches from the
            // address, so this is not the host github.com no matter how it reads
            "github.com::attacker-address",
            "github.com::https://attacker.example/owner/repo",
            "/local/path/repo",
            "",
        ] {
            assert!(!is_trusted_github_remote(url), "must reject: {url}");
        }
    }

    /// The base config is read from the remote-tracking ref, never the working tree.
    #[test]
    fn base_config_reads_the_ref_blob() {
        let (_dir, repo) = repo_with_base_config();
        assert_eq!(
            read_base_branch_config(&repo, "main").as_deref(),
            Some("from-base")
        );
        assert!(read_base_branch_config(&repo, "no-such-branch").is_none());
        assert!(read_base_branch_config(&repo, "").is_none());
        assert_eq!(head_config_state(&repo, "main"), HeadConfig::SameAsBase);
    }

    /// The head comparison goes through git object ids, so a PR-supplied symlink at
    /// nitpicker.toml is never followed. `/dev/zero` makes this regression Unix-specific.
    #[cfg(unix)]
    #[test]
    fn head_config_state_never_reads_a_worktree_symlink() {
        let (_dir, repo) = repo_with_base_config();
        // the PR head commits a hostile replacement: a symlink to a device that would hang
        // an unbounded read. Detection must stay at object-id level and still say "diverges".
        std::fs::remove_file(repo.join("nitpicker.toml")).unwrap();
        std::os::unix::fs::symlink("/dev/zero", repo.join("nitpicker.toml")).unwrap();
        git(&repo, &["add", "nitpicker.toml"]);
        commit(&repo, "hostile config");
        assert_eq!(head_config_state(&repo, "main"), HeadConfig::Diverges);
        // and the config actually used is still the base branch's
        assert_eq!(
            read_base_branch_config(&repo, "main").as_deref(),
            Some("from-base")
        );
    }

    fn repo_with_base_config() -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().canonicalize().unwrap();
        init_repo(&repo);
        std::fs::write(repo.join("nitpicker.toml"), "from-base").unwrap();
        git(&repo, &["add", "nitpicker.toml"]);
        commit(&repo, "config");
        // fabricate the remote-tracking ref the PR base resolves through
        git(&repo, &["update-ref", "refs/remotes/origin/main", "HEAD"]);
        (dir, repo)
    }

    fn commit(repo: &Path, msg: &str) {
        git(
            repo,
            &[
                "-c",
                "user.email=t@test",
                "-c",
                "user.name=t",
                "-c",
                "commit.gpgsign=false",
                "commit",
                "-m",
                msg,
            ],
        );
    }

    #[test]
    fn pr_comments_tolerate_null_author() {
        // gh represents a deleted/ghost account's comment as `author: null`; one such comment must
        // not fail the whole comments-list deserialize and abort the run.
        let comments: Vec<PrComment> = serde_json::from_str(
            r#"[{"author":null,"body":"hi"},{"author":{"login":"octocat"},"body":"yo"}]"#,
        )
        .expect("null author must deserialize");
        assert!(comments[0].author.is_none());
        assert_eq!(comments[1].author.as_ref().unwrap().login, "octocat");
    }

    #[test]
    fn temp_clone_workdir_uses_the_repository_name() {
        let temp = tempfile::tempdir().unwrap();
        let path = create_temp_clone_repo_dir(temp.path(), "owner/reviewer").unwrap();
        assert_eq!(
            path.file_name().and_then(|name| name.to_str()),
            Some("reviewer")
        );
        assert!(path.is_dir());
    }

    #[test]
    fn temp_clone_workdir_rejects_unsafe_repository_names() {
        let temp = tempfile::tempdir().unwrap();
        for slug in ["", "owner/..", "owner/repo\\nested"] {
            assert!(
                create_temp_clone_repo_dir(temp.path(), slug).is_err(),
                "must reject {slug:?}"
            );
        }
    }

    fn git(repo: &Path, args: &[&str]) {
        let out = Command::new("git")
            .args(args)
            .current_dir(repo)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    fn init_repo(repo: &Path) {
        git(repo, &["init", "-b", "main"]);
        git(
            repo,
            &[
                "-c",
                "user.email=t@test",
                "-c",
                "user.name=t",
                "-c",
                "commit.gpgsign=false",
                "commit",
                "--allow-empty",
                "-m",
                "one",
            ],
        );
    }

    #[test]
    fn linked_worktrees_share_one_pr_lock() {
        let dir = tempfile::tempdir().unwrap();
        let primary = dir.path().join("primary");
        std::fs::create_dir(&primary).unwrap();
        init_repo(&primary);

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

        assert_eq!(lock_path(&primary), lock_path(&linked));
    }

    /// The guard's Drop is the only thing standing between a panic/early error and the user
    /// stranded on nitpicker's PR branch — it must switch back to the branch it captured.
    #[test]
    fn branch_restore_guard_switches_back_to_the_original_branch() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().canonicalize().unwrap();
        init_repo(&repo);

        let head = get_head_state(&repo).unwrap();
        assert!(matches!(&head, HeadState::Branch(b) if b == "main"));

        git(&repo, &["switch", "-c", "nitpicker/pr-1"]);
        drop(BranchRestoreGuard {
            repo: repo.clone(),
            head,
        });

        match get_head_state(&repo).unwrap() {
            HeadState::Branch(b) => assert_eq!(b, "main"),
            HeadState::Detached(_) => panic!("expected to be back on the main branch"),
        }
    }

    /// A detached HEAD must be restored with `switch --detach` (plain `git switch` refuses a
    /// bare commit) — the failure mode is the user silently left on the PR branch. Exercised
    /// through the guard's Drop, the path production actually takes.
    #[test]
    fn dropping_the_guard_re_detaches_onto_the_original_commit() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().canonicalize().unwrap();
        init_repo(&repo);

        git(&repo, &["switch", "--detach", "HEAD"]);
        let head = get_head_state(&repo).unwrap();
        let original_sha = match &head {
            HeadState::Detached(sha) => sha.clone(),
            HeadState::Branch(_) => panic!("expected a detached HEAD"),
        };

        git(&repo, &["switch", "main"]);
        drop(BranchRestoreGuard {
            repo: repo.clone(),
            head,
        });

        match get_head_state(&repo).unwrap() {
            HeadState::Detached(sha) => assert_eq!(sha, original_sha),
            HeadState::Branch(_) => panic!("expected HEAD re-detached onto the original commit"),
        }
    }
}