omni-dev 0.39.0

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

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};
use git2::{Oid, Repository, RepositoryState, StatusOptions};
use serde::Serialize;

use crate::git::remote::RemoteInfo;
use crate::git::resolve_git_binary;

/// Which worktrees a batch rebase should target.
#[derive(Debug, Clone)]
pub enum Selection {
    /// Rebase exactly these worktree folders (each resolved to the worktree that
    /// contains it). A path that is the main working tree, is detached, is dirty,
    /// or is not a git worktree is reported and skipped, never rebased.
    Paths(Vec<PathBuf>),
    /// Rebase every **linked** worktree of the repository that contains `base`
    /// (the process working directory). The main working tree is never included.
    All {
        /// The directory whose repository's linked worktrees are the target set.
        base: PathBuf,
    },
}

/// Knobs for a batch rebase.
#[derive(Debug, Clone, Default)]
pub struct RebaseOptions {
    /// Override the rebase target ref (default: the repository's remote default
    /// branch, e.g. `origin/main`). A `<remote>/<branch>` value is still fetched
    /// once up front; a local ref or raw commit is used as-is (no fetch).
    pub onto: Option<String>,
    /// Stash uncommitted changes before each rebase and restore them after, rather
    /// than skipping a dirty worktree.
    pub autostash: bool,
    /// Fetch and classify, but perform no rebase.
    pub dry_run: bool,
    /// Leave a conflicting worktree **mid-rebase** instead of `git rebase
    /// --abort`-ing it (#1415).
    ///
    /// The default (abort) keeps the worktree exactly as it was, which is the
    /// right conservative choice for a batch the user is watching scroll past. But
    /// it also throws away every conflict already resolved by `git rerere` and
    /// every hunk git applied cleanly before the collision — work the user then has
    /// to reproduce by hand. With this set, the worktree stays in its conflicted
    /// state so the conflict can be resolved in place and finished with
    /// `git rebase --continue`, and the batch moves on to the next worktree
    /// regardless.
    pub keep_conflicts: bool,
    /// The `git` executable to shell out to. `None` resolves it via
    /// [`resolve_git_binary`], which is what a caller with a minimal `PATH` (the
    /// daemon) needs; the field exists so a caller can resolve **once** and reuse,
    /// and so a test can point the engine at a stub.
    pub git_bin: Option<PathBuf>,
}

impl RebaseOptions {
    /// The `git` executable these options select, resolving the default lazily.
    /// Called once per [`plan`] / [`execute`] rather than per subprocess.
    fn git_bin(&self) -> PathBuf {
        self.git_bin.clone().unwrap_or_else(resolve_git_binary)
    }
}

/// The result of planning and (optionally) executing a batch rebase.
#[derive(Debug, Clone, Serialize)]
pub struct Plan {
    /// One entry per repository: the fetch that was performed (or, for a local
    /// onto ref, skipped). The length is the fetch-once-per-repo count.
    pub fetches: Vec<FetchOutcome>,
    /// One entry per selected worktree, in selection order.
    pub worktrees: Vec<WorktreeOutcome>,
}

impl Plan {
    /// Whether any worktree still needs a rebase (a [`RebaseResult::WouldRebase`]).
    /// The CLI uses this to decide whether to confirm and execute.
    #[must_use]
    pub fn has_pending_rebases(&self) -> bool {
        self.worktrees
            .iter()
            .any(|w| matches!(w.result, RebaseResult::WouldRebase { .. }))
    }
}

/// The one-shot fetch performed for a single repository.
#[derive(Debug, Clone, Serialize)]
pub struct FetchOutcome {
    /// The main working-tree root of the repository (the fetch is run here).
    pub repo_root: PathBuf,
    /// The resolved onto ref this repository's worktrees rebase onto.
    pub onto: String,
    /// Whether a fetch was actually run (false for a local onto ref).
    pub fetched: bool,
    /// Whether the fetch succeeded (always true when `fetched` is false).
    pub ok: bool,
    /// The `git fetch` error, when it failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

/// What happened (or, in a dry run, would happen) to one worktree.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WorktreeOutcome {
    /// The worktree folder.
    pub path: PathBuf,
    /// The checked-out branch, when on one (absent for a detached/unborn HEAD).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    /// The ref this worktree rebases onto (empty when it could not be resolved).
    pub onto: String,
    /// The classification / outcome.
    #[serde(flatten)]
    pub result: RebaseResult,
}

/// The per-worktree classification and outcome.
///
/// [`plan`] only ever produces `WouldRebase` / `UpToDate` / `Skipped` /
/// `FetchFailed`; [`execute`] turns each `WouldRebase` into `Rebased`
/// or `Conflict`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub enum RebaseResult {
    /// Rebased onto the fetched ref; it was `behind` commits behind beforehand.
    Rebased {
        /// Commits the worktree was behind the onto ref before the rebase.
        behind: usize,
    },
    /// Would be rebased (dry run); it is `behind` commits behind.
    WouldRebase {
        /// Commits the worktree is behind the onto ref.
        behind: usize,
    },
    /// Already on top of the onto ref — nothing to do.
    UpToDate,
    /// Skipped without touching the worktree, for a structural reason.
    Skipped {
        /// Why it was skipped.
        reason: SkipReason,
    },
    /// The rebase hit conflicts. By default it was aborted and the worktree left
    /// untouched; with [`RebaseOptions::keep_conflicts`] the worktree is instead
    /// left mid-rebase, which `left_in_place` records.
    Conflict {
        /// The `git rebase` error output (trimmed).
        detail: String,
        /// Whether the worktree was **left mid-rebase** for the user to resolve
        /// (`true`) rather than aborted back to its previous state (`false`).
        /// Omitted on the wire when false, so a pre-#1415 client sees the exact
        /// bytes it saw before.
        #[serde(skip_serializing_if = "is_false")]
        left_in_place: bool,
    },
    /// The repository's one-shot fetch failed, so no worktree of it was attempted.
    FetchFailed {
        /// The fetch error (trimmed).
        detail: String,
    },
}

/// Why a worktree was skipped rather than rebased.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SkipReason {
    /// The main working tree — rebasing it is never the intent (structural
    /// `is_main`, not a branch-name heuristic).
    MainWorkingTree,
    /// A detached or unborn HEAD — there is no branch to rebase.
    DetachedHead,
    /// Uncommitted changes to tracked files (pass `--autostash` to rebase anyway).
    Dirty,
    /// A rebase/merge/cherry-pick is already in progress.
    OperationInProgress,
    /// The path is not a git worktree.
    NotAWorktree,
    /// The onto ref could not be resolved (e.g. no remote default branch).
    NoOntoRef,
}

/// Plans a batch rebase, fetching each repository's onto ref **exactly once**.
///
/// Enumerates the selected worktrees, resolves the onto ref and fetches it once per
/// repository, then classifies each worktree against the freshly fetched ref. The
/// returned [`Plan`] is exactly what a dry run reports; a real run passes it to
/// [`execute`].
///
/// The fetch runs even for a dry run: it is non-destructive (it only advances the
/// shared remote-tracking ref) and is what pins the single snapshot every worktree
/// is measured — and would be rebased — against.
pub fn plan(selection: &Selection, opts: &RebaseOptions) -> Result<Plan> {
    let paths = resolve_selection(selection)?;
    // Resolved once for the whole plan, not per subprocess: the probe stats the
    // candidate paths, and the answer is process-stable.
    let git = opts.git_bin();

    // Phase A — inspect each path with git2 (no network): structural facts + HEAD.
    let inspected: Vec<Inspected> = paths.iter().map(|p| Inspected::read(p)).collect();

    // Phase B — resolve the onto ref once per distinct repository.
    let onto_by_repo = resolve_onto_by_repo(&inspected, opts.onto.as_deref());

    // Phase C — fetch once per repository (the fetch-once-per-repo invariant).
    let (fetches, fetch_ok) = fetch_all(&git, &onto_by_repo);

    // Phase D — classify each worktree against the now-fresh refs.
    let worktrees = inspected
        .iter()
        .map(|i| i.classify(&onto_by_repo, &fetch_ok, opts.autostash))
        .collect();

    Ok(Plan { fetches, worktrees })
}

/// Executes a [`Plan`], rebasing every [`RebaseResult::WouldRebase`] worktree.
///
/// The rest pass through unchanged. Rebases run sequentially (deterministic output;
/// no contention on the shared object database). A conflicting rebase is aborted so
/// the worktree is left exactly as it was — unless
/// [`RebaseOptions::keep_conflicts`] is set, in which case it is left mid-rebase.
/// Either way the batch continues with the remaining worktrees.
#[must_use]
pub fn execute(plan: Plan, opts: &RebaseOptions) -> Vec<WorktreeOutcome> {
    let git = opts.git_bin();
    plan.worktrees
        .into_iter()
        .map(|mut outcome| {
            if let RebaseResult::WouldRebase { behind } = outcome.result {
                outcome.result = match rebase_worktree(&git, &outcome.path, &outcome.onto, opts) {
                    Ok(()) => RebaseResult::Rebased { behind },
                    Err(detail) => RebaseResult::Conflict {
                        detail,
                        left_in_place: opts.keep_conflicts,
                    },
                };
            }
            outcome
        })
        .collect()
}

// ── selection ────────────────────────────────────────────────────────────────

/// The concrete worktree paths a [`Selection`] targets.
fn resolve_selection(selection: &Selection) -> Result<Vec<PathBuf>> {
    match selection {
        Selection::Paths(paths) => Ok(paths.clone()),
        Selection::All { base } => linked_worktree_paths(base),
    }
}

/// Every **linked** worktree path of the repository containing `base` (never the
/// main working tree). Mirrors the daemon service's repo enumeration: discover the
/// repo, resolve its shared common dir's parent as the main root, then list the
/// worktrees registered on the main repository.
fn linked_worktree_paths(base: &Path) -> Result<Vec<PathBuf>> {
    let repo = Repository::discover(base)
        .with_context(|| format!("not inside a git repository: {}", base.display()))?;
    let root = main_root(&repo);
    let main_repo = Repository::open(&root)
        .with_context(|| format!("cannot open main repository: {}", root.display()))?;
    let names = main_repo
        .worktrees()
        .context("cannot enumerate worktrees")?;
    let mut paths = Vec::new();
    // `iter()` yields `Result<Option<&str>, _>`: the first `flatten` drops per-name
    // errors, the second drops non-UTF-8 names (same idiom as the daemon service).
    for name in names.iter().flatten().flatten() {
        if let Ok(worktree) = main_repo.find_worktree(name) {
            paths.push(worktree.path().to_path_buf());
        }
    }
    Ok(paths)
}

// ── inspection (git2 reads) ──────────────────────────────────────────────────

/// A single selected path after its structural git2 inspection.
enum Inspected {
    /// The path resolved to a git worktree.
    Ok(Inspection),
    /// The path is not a git worktree (or does not exist).
    Unresolvable {
        /// The path, as given (best-effort canonicalized).
        path: PathBuf,
    },
}

/// The structural facts read from one worktree, independent of any fetch.
struct Inspection {
    path: PathBuf,
    repo_root: PathBuf,
    branch: Option<String>,
    head_oid: Option<Oid>,
    is_main: bool,
    state_clean: bool,
    dirty: bool,
}

impl Inspected {
    /// Inspects `path` with git2, degrading a non-worktree path to
    /// [`Inspected::Unresolvable`] rather than an error so one bad path never fails
    /// the whole batch.
    fn read(path: &Path) -> Self {
        let canon = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        let Ok(repo) = Repository::discover(&canon) else {
            return Self::Unresolvable { path: canon };
        };
        let is_main = !repo.is_worktree();
        let repo_root = main_root(&repo);
        let (branch, head_oid) = head_branch(&repo);
        let state_clean = repo.state() == RepositoryState::Clean;
        let dirty = is_dirty(&repo);
        Self::Ok(Inspection {
            path: canon,
            repo_root,
            branch,
            head_oid,
            is_main,
            state_clean,
            dirty,
        })
    }

    /// The repository root, for the resolvable case (used to group fetches).
    fn repo_root(&self) -> Option<&Path> {
        match self {
            Self::Ok(i) => Some(&i.repo_root),
            Self::Unresolvable { .. } => None,
        }
    }

    /// Classifies this worktree against the resolved onto refs and fetch outcomes.
    fn classify(
        &self,
        onto_by_repo: &BTreeMap<PathBuf, OntoSpec>,
        fetch_ok: &BTreeMap<PathBuf, bool>,
        autostash: bool,
    ) -> WorktreeOutcome {
        let i = match self {
            Self::Unresolvable { path } => {
                return WorktreeOutcome::skipped(
                    path.clone(),
                    None,
                    String::new(),
                    SkipReason::NotAWorktree,
                );
            }
            Self::Ok(i) => i,
        };

        let onto = onto_by_repo.get(&i.repo_root);
        let onto_display = onto.map_or_else(String::new, |s| s.display.clone());
        let branch = i.branch.clone();
        let skip = |reason| {
            WorktreeOutcome::skipped(i.path.clone(), branch.clone(), onto_display.clone(), reason)
        };

        // Structural skips (independent of the fetch), safe-before-destructive order.
        if i.is_main {
            return skip(SkipReason::MainWorkingTree);
        }
        let (Some(head), Some(_)) = (i.head_oid, i.branch.as_ref()) else {
            return skip(SkipReason::DetachedHead);
        };
        if !i.state_clean {
            return skip(SkipReason::OperationInProgress);
        }
        if i.dirty && !autostash {
            return skip(SkipReason::Dirty);
        }
        let Some(onto) = onto else {
            return skip(SkipReason::NoOntoRef);
        };

        // The repository's single fetch must have succeeded.
        if fetch_ok.get(&i.repo_root) == Some(&false) {
            let detail = "the repository's fetch failed".to_string();
            return WorktreeOutcome {
                path: i.path.clone(),
                branch,
                onto: onto_display,
                result: RebaseResult::FetchFailed { detail },
            };
        }

        // Divergence against the freshly fetched ref.
        match behind_count(&i.repo_root, head, &onto.display) {
            None => skip(SkipReason::NoOntoRef),
            Some(0) => WorktreeOutcome {
                path: i.path.clone(),
                branch,
                onto: onto_display,
                result: RebaseResult::UpToDate,
            },
            Some(behind) => WorktreeOutcome {
                path: i.path.clone(),
                branch,
                onto: onto_display,
                result: RebaseResult::WouldRebase { behind },
            },
        }
    }
}

impl WorktreeOutcome {
    /// A `Skipped` outcome.
    fn skipped(path: PathBuf, branch: Option<String>, onto: String, reason: SkipReason) -> Self {
        Self {
            path,
            branch,
            onto,
            result: RebaseResult::Skipped { reason },
        }
    }
}

/// The main working-tree root of `repo`: the parent of its shared common dir. For a
/// linked worktree this is the original checkout every worktree shares.
fn main_root(repo: &Repository) -> PathBuf {
    let commondir = repo.commondir();
    let commondir = std::fs::canonicalize(commondir).unwrap_or_else(|_| commondir.to_path_buf());
    let parent = commondir.parent().map(Path::to_path_buf);
    parent.unwrap_or(commondir)
}

/// The checked-out branch shorthand and HEAD oid. Both are `None` for a detached or
/// unborn HEAD (no branch to rebase).
fn head_branch(repo: &Repository) -> (Option<String>, Option<Oid>) {
    match repo.head() {
        Ok(head) if head.is_branch() => (
            head.shorthand().ok().map(ToString::to_string),
            head.target(),
        ),
        Ok(head) => (None, head.target()),
        Err(_) => (None, None),
    }
}

/// Whether the worktree has uncommitted changes to **tracked** files (staged or
/// unstaged). Untracked and ignored files do not block a rebase, so they are
/// excluded.
fn is_dirty(repo: &Repository) -> bool {
    let mut opts = StatusOptions::new();
    opts.include_untracked(false)
        .include_ignored(false)
        .exclude_submodules(true);
    repo.statuses(Some(&mut opts))
        .is_ok_and(|statuses| !statuses.is_empty())
}

/// Commits `onto` is ahead of `head` (i.e. how far `head` is behind `onto`), or
/// `None` when `onto` does not resolve to a commit in the repository at `repo_root`.
fn behind_count(repo_root: &Path, head: Oid, onto: &str) -> Option<usize> {
    let repo = Repository::open(repo_root).ok()?;
    let onto_oid = repo.revparse_single(onto).ok()?.peel_to_commit().ok()?.id();
    let (_ahead, behind) = repo.graph_ahead_behind(head, onto_oid).ok()?;
    Some(behind)
}

// ── onto resolution ──────────────────────────────────────────────────────────

/// The rebase target for one repository.
#[derive(Debug, Clone, PartialEq, Eq)]
struct OntoSpec {
    /// The git revspec every worktree of this repo rebases onto (e.g. `origin/main`).
    display: String,
    /// `Some((remote, branch))` when `display` is a remote-tracking ref to fetch
    /// once up front; `None` for a local ref / raw commit (no fetch).
    fetch: Option<(String, String)>,
}

/// Resolves the onto ref for every distinct repository among the resolvable
/// inspections. The map's one-entry-per-root shape **is** the fetch-once-per-repo
/// grouping: N worktrees of one repo collapse to a single entry.
fn resolve_onto_by_repo(
    inspected: &[Inspected],
    override_ref: Option<&str>,
) -> BTreeMap<PathBuf, OntoSpec> {
    let mut map: BTreeMap<PathBuf, OntoSpec> = BTreeMap::new();
    for root in inspected.iter().filter_map(Inspected::repo_root) {
        if map.contains_key(root) {
            continue;
        }
        if let Ok(repo) = Repository::open(root) {
            map.insert(root.to_path_buf(), resolve_onto(&repo, override_ref));
        }
    }
    map
}

/// The onto spec for a single repository: the `--onto` override if given, else the
/// remote (`origin`) default branch resolved from local refs.
fn resolve_onto(repo: &Repository, override_ref: Option<&str>) -> OntoSpec {
    if let Some(reference) = override_ref {
        return onto_from_override(repo, reference);
    }
    let remote = "origin";
    let branch =
        RemoteInfo::detect_main_branch_local(repo, remote).unwrap_or_else(|| "main".to_string());
    OntoSpec {
        display: format!("{remote}/{branch}"),
        fetch: Some((remote.to_string(), branch)),
    }
}

/// Interprets an explicit `--onto` value: a `<remote>/<branch>` whose first segment
/// is a configured remote is fetched once; anything else (a local branch, a raw
/// commit) is used verbatim with no fetch.
fn onto_from_override(repo: &Repository, reference: &str) -> OntoSpec {
    if let Some((remote, branch)) = reference.split_once('/') {
        if repo.find_remote(remote).is_ok() {
            return OntoSpec {
                display: reference.to_string(),
                fetch: Some((remote.to_string(), branch.to_string())),
            };
        }
    }
    OntoSpec {
        display: reference.to_string(),
        fetch: None,
    }
}

// ── fetch (shell-out, once per repo) ─────────────────────────────────────────

/// Fetches each repository's onto ref once, returning the per-repo outcomes and a
/// `root -> ok` map the classifier consults. A repo with a local onto ref records a
/// `fetched: false, ok: true` entry.
fn fetch_all(
    git: &Path,
    onto_by_repo: &BTreeMap<PathBuf, OntoSpec>,
) -> (Vec<FetchOutcome>, BTreeMap<PathBuf, bool>) {
    let mut fetches = Vec::new();
    let mut fetch_ok = BTreeMap::new();
    for (root, spec) in onto_by_repo {
        let outcome = match &spec.fetch {
            Some((remote, branch)) => {
                let result = fetch_once(git, root, remote, branch);
                let ok = result.is_ok();
                FetchOutcome {
                    repo_root: root.clone(),
                    onto: spec.display.clone(),
                    fetched: true,
                    ok,
                    detail: result.err().map(|e| e.to_string()),
                }
            }
            None => FetchOutcome {
                repo_root: root.clone(),
                onto: spec.display.clone(),
                fetched: false,
                ok: true,
                detail: None,
            },
        };
        fetch_ok.insert(root.clone(), outcome.ok);
        fetches.push(outcome);
    }
    (fetches, fetch_ok)
}

/// Runs `git fetch <remote> <branch>` once in `repo_root`. The shared object
/// database means this single fetch updates the tracking ref every worktree sees.
fn fetch_once(git: &Path, repo_root: &Path, remote: &str, branch: &str) -> Result<()> {
    let output = run_git_in(git, repo_root, &["fetch", remote, branch])?;
    if output.status.success() {
        return Ok(());
    }
    bail!(
        "git fetch {remote} {branch} failed: {}",
        trimmed_stderr(&output)
    )
}

// ── rebase (shell-out, per worktree) ─────────────────────────────────────────

/// Rebases the branch checked out in `path` onto `onto`, returning the trimmed
/// error on failure (a conflict, or anything else).
///
/// By default the rebase is aborted on failure so the worktree is left exactly as
/// it was; with `autostash`, `git rebase --abort` also restores the stashed
/// changes. With [`RebaseOptions::keep_conflicts`] the abort is **skipped** and the
/// worktree stays mid-rebase for in-place resolution — including any autostash
/// entry, which git re-applies when the rebase eventually concludes (via
/// `--continue` or a later `--abort`), exactly as for a hand-run rebase.
fn rebase_worktree(
    git: &Path,
    path: &Path,
    onto: &str,
    opts: &RebaseOptions,
) -> std::result::Result<(), String> {
    let args = rebase_args(onto, opts.autostash);
    let argv: Vec<&str> = args.iter().map(String::as_str).collect();
    match run_git_in(git, path, &argv) {
        Ok(output) if output.status.success() => Ok(()),
        Ok(output) => {
            let detail = trimmed_stderr(&output);
            if !opts.keep_conflicts {
                // Best-effort abort; harmlessly errors if no rebase is in progress.
                let _ = run_git_in(git, path, &["rebase", "--abort"]);
            }
            Err(detail)
        }
        Err(err) => Err(err.to_string()),
    }
}

/// The `git rebase` argument vector, with `--autostash` inserted when requested.
/// Pure, so the argument shape is unit-testable.
fn rebase_args(onto: &str, autostash: bool) -> Vec<String> {
    let mut args = vec!["rebase".to_string()];
    if autostash {
        args.push("--autostash".to_string());
    }
    args.push(onto.to_string());
    args
}

// ── git subprocess seam ──────────────────────────────────────────────────────

/// Runs `git <args>` in `dir`, capturing its output.
///
/// The child receives a snapshot of the current environment (`env_clear` + `envs`)
/// so the spawn stays out of the data race against concurrent `std::env::set_var`
/// (issue #1022; same idiom as `crate::cli::git::worktree`). Shelling out to the
/// user's `git` — rather than libgit2's network transport — is deliberate: it works
/// across SSH/HTTPS and honours the user's authentication configuration (ADR-0003,
/// issue #903).
///
/// That environment snapshot is also what makes the daemon host viable: under
/// launchd the daemon's own environment carries the per-user `SSH_AUTH_SOCK`, so
/// the child inherits the user's `ssh-agent` unchanged (ADR-0059). `git` itself is
/// passed in resolved, because that environment's `PATH` is minimal.
fn run_git_in(git: &Path, dir: &Path, args: &[&str]) -> Result<std::process::Output> {
    let mut cmd = Command::new(git);
    cmd.env_clear();
    cmd.envs(std::env::vars_os());
    cmd.current_dir(dir)
        .args(args)
        .output()
        .with_context(|| format!("failed to execute {} in {}", git.display(), dir.display()))
}

/// `skip_serializing_if` predicate for a `bool` defaulting to `false`, so the field
/// is dropped on the wire unless set — the protocol's forward-compatibility
/// convention (the twin of the daemon service's helper of the same name).
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(b: &bool) -> bool {
    !*b
}

/// The trimmed stderr of a git subprocess (falling back to stdout when stderr is
/// empty), for a single-line error message.
fn trimmed_stderr(output: &std::process::Output) -> String {
    let stderr = String::from_utf8_lossy(&output.stderr);
    let trimmed = stderr.trim();
    if trimmed.is_empty() {
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    } else {
        trimmed.to_string()
    }
}

/// A process-wide lock serializing the git-subprocess-heavy tests, shared across
/// modules (this module's tests and the `worktrees rebase` CLI test).
///
/// Each such test builds several repos by shelling out to `git`; run in parallel
/// across the whole suite they burst dozens of processes at once, starving
/// unrelated timing-sensitive tests (the daemon PR-poll debounce test). Holding one
/// lock caps the combined concurrent `git` load at a single scenario, which keeps
/// coverage without destabilising the suite. Poison is ignored — a panicking test
/// still releases the guard's exclusion.
#[cfg(test)]
pub(crate) fn test_serial_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    LOCK.lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    /// The shared git-load serialization guard (see [`super::test_serial_lock`]).
    fn serial() -> std::sync::MutexGuard<'static, ()> {
        super::test_serial_lock()
    }

    // ── pure helpers ──────────────────────────────────────────────────────

    #[test]
    fn rebase_args_omits_autostash_by_default() {
        assert_eq!(
            rebase_args("origin/main", false),
            vec!["rebase", "origin/main"]
        );
    }

    #[test]
    fn rebase_args_inserts_autostash_before_the_ref() {
        assert_eq!(
            rebase_args("origin/main", true),
            vec!["rebase", "--autostash", "origin/main"]
        );
    }

    #[test]
    fn onto_from_override_fetches_a_remote_tracking_ref() {
        let (_dir, repo) = repo_with_origin();
        let spec = onto_from_override(&repo, "origin/release");
        assert_eq!(spec.display, "origin/release");
        assert_eq!(
            spec.fetch,
            Some(("origin".to_string(), "release".to_string()))
        );
    }

    #[test]
    fn onto_from_override_keeps_a_multi_segment_branch_whole() {
        let (_dir, repo) = repo_with_origin();
        let spec = onto_from_override(&repo, "origin/feature/foo");
        assert_eq!(
            spec.fetch,
            Some(("origin".to_string(), "feature/foo".to_string()))
        );
    }

    #[test]
    fn onto_from_override_does_not_fetch_a_local_ref() {
        let (_dir, repo) = repo_with_origin();
        // `develop` has no `/`, and `upstream/x`'s first segment is not a remote.
        assert_eq!(onto_from_override(&repo, "develop").fetch, None);
        assert_eq!(onto_from_override(&repo, "upstream/x").fetch, None);
        assert_eq!(onto_from_override(&repo, "HEAD~2").fetch, None);
    }

    #[test]
    fn resolve_onto_defaults_to_origin_main() {
        let (_dir, repo) = repo_with_origin();
        let spec = resolve_onto(&repo, None);
        assert_eq!(spec.display, "origin/main");
        assert_eq!(spec.fetch, Some(("origin".to_string(), "main".to_string())));
    }

    // ── the fetch-once-per-repo invariant ─────────────────────────────────

    #[test]
    fn one_repo_with_many_worktrees_fetches_exactly_once() {
        // Three linked worktrees sharing one repository must yield a single fetch
        // entry — the whole point of #1400.
        let _guard = serial();
        let scenario = Scenario::new();
        scenario.add_worktree("feature-a");
        scenario.add_worktree("feature-b");
        scenario.add_worktree("feature-c");

        let plan = plan(
            &Selection::All {
                base: scenario.local,
            },
            &RebaseOptions::default(),
        )
        .unwrap();

        assert_eq!(
            plan.fetches.len(),
            1,
            "fetch must run once per repo, not per worktree"
        );
        assert_eq!(plan.worktrees.len(), 3);
        assert!(plan.fetches[0].ok);
    }

    #[test]
    fn resolve_onto_by_repo_collapses_worktrees_of_one_repo() {
        let _guard = serial();
        let scenario = Scenario::new();
        scenario.add_worktree("feature-a");
        scenario.add_worktree("feature-b");
        let paths = linked_worktree_paths(&scenario.local).unwrap();
        let inspected: Vec<Inspected> = paths.iter().map(|p| Inspected::read(p)).collect();
        let map = resolve_onto_by_repo(&inspected, None);
        assert_eq!(
            map.len(),
            1,
            "two worktrees of one repo resolve to one onto entry"
        );
    }

    // ── end-to-end classify + execute ─────────────────────────────────────

    #[test]
    fn behind_worktree_is_rebased_onto_the_fetched_ref() {
        let _guard = serial();
        let scenario = Scenario::new();
        let wt = scenario.add_worktree("feature");
        // Advance origin/main by one commit from a separate clone, so the local
        // tracking ref only learns of it on fetch.
        scenario.advance_origin_main("second\n");

        let plan = plan(
            &Selection::Paths(vec![wt.clone()]),
            &RebaseOptions::default(),
        )
        .unwrap();
        assert_eq!(plan.worktrees.len(), 1);
        assert_eq!(
            plan.worktrees[0].result,
            RebaseResult::WouldRebase { behind: 1 },
            "the feature worktree is one commit behind the fetched origin/main"
        );

        let outcomes = execute(plan, &RebaseOptions::default());
        assert_eq!(outcomes[0].result, RebaseResult::Rebased { behind: 1 });
        // The worktree is clean and its branch now contains origin/main's commit.
        assert!(head_contains(&wt, &scenario.origin_main_oid()));
    }

    #[test]
    fn up_to_date_worktree_is_not_rebased() {
        let _guard = serial();
        let scenario = Scenario::new();
        let wt = scenario.add_worktree("feature");
        // No advance: feature sits on origin/main already.
        let plan = plan(&Selection::Paths(vec![wt]), &RebaseOptions::default()).unwrap();
        assert_eq!(plan.worktrees[0].result, RebaseResult::UpToDate);
        assert!(!plan.has_pending_rebases());
    }

    #[test]
    fn dirty_worktree_is_skipped_but_autostash_rebases_it() {
        let _guard = serial();
        let scenario = Scenario::new();
        let wt = scenario.add_worktree("feature");
        scenario.advance_origin_main("second\n");
        // Dirty a file `origin/main` does not touch, so the autostash pop is clean.
        std::fs::write(wt.join("keep.txt"), "dirty change\n").unwrap();

        let skipped = plan(
            &Selection::Paths(vec![wt.clone()]),
            &RebaseOptions::default(),
        )
        .unwrap();
        assert_eq!(
            skipped.worktrees[0].result,
            RebaseResult::Skipped {
                reason: SkipReason::Dirty
            }
        );

        let opts = RebaseOptions {
            autostash: true,
            ..RebaseOptions::default()
        };
        let planned = plan(&Selection::Paths(vec![wt.clone()]), &opts).unwrap();
        assert_eq!(
            planned.worktrees[0].result,
            RebaseResult::WouldRebase { behind: 1 }
        );
        let outcomes = execute(planned, &opts);
        assert_eq!(outcomes[0].result, RebaseResult::Rebased { behind: 1 });
        // Autostash restored the local edit on top of the rebased branch.
        assert_eq!(
            std::fs::read_to_string(wt.join("keep.txt")).unwrap(),
            "dirty change\n"
        );
    }

    #[test]
    fn main_working_tree_is_skipped() {
        let _guard = serial();
        let scenario = Scenario::new();
        let plan = plan(
            &Selection::Paths(vec![scenario.local]),
            &RebaseOptions::default(),
        )
        .unwrap();
        assert_eq!(
            plan.worktrees[0].result,
            RebaseResult::Skipped {
                reason: SkipReason::MainWorkingTree
            }
        );
    }

    #[test]
    fn non_worktree_path_is_skipped_not_fatal() {
        let dir = tempfile::tempdir().unwrap();
        let plan = plan(
            &Selection::Paths(vec![dir.path().to_path_buf()]),
            &RebaseOptions::default(),
        )
        .unwrap();
        assert_eq!(
            plan.worktrees[0].result,
            RebaseResult::Skipped {
                reason: SkipReason::NotAWorktree
            }
        );
    }

    #[test]
    fn conflicting_rebase_aborts_and_leaves_the_worktree_untouched() {
        let _guard = serial();
        let scenario = Scenario::new();
        let wt = scenario.add_worktree("feature");
        // Feature edits file.txt; origin/main edits the same line differently.
        scenario.commit_in_worktree(&wt, "file.txt", "feature side\n", "feature edit");
        scenario.advance_origin_main("main side\n");
        let head_before = head_oid(&wt);

        let plan = plan(
            &Selection::Paths(vec![wt.clone()]),
            &RebaseOptions::default(),
        )
        .unwrap();
        assert!(matches!(
            plan.worktrees[0].result,
            RebaseResult::WouldRebase { .. }
        ));
        let outcomes = execute(plan, &RebaseOptions::default());
        assert!(
            matches!(
                outcomes[0].result,
                RebaseResult::Conflict {
                    left_in_place: false,
                    ..
                }
            ),
            "a conflicting rebase is reported, not silently half-applied"
        );
        // Aborted: HEAD unchanged and no rebase left in progress.
        assert_eq!(head_oid(&wt), head_before);
        let repo = Repository::open(&wt).unwrap();
        assert_eq!(repo.state(), RepositoryState::Clean);
    }

    #[test]
    fn keep_conflicts_leaves_the_worktree_mid_rebase() {
        // The inverse of the test above (#1415): the conflicted worktree must be
        // left in its conflicted state so the user can resolve it in place, rather
        // than aborted back to where it started.
        let _guard = serial();
        let scenario = Scenario::new();
        let wt = scenario.add_worktree("feature");
        scenario.commit_in_worktree(&wt, "file.txt", "feature side\n", "feature edit");
        scenario.advance_origin_main("main side\n");

        let opts = RebaseOptions {
            keep_conflicts: true,
            ..RebaseOptions::default()
        };
        let plan = plan(&Selection::Paths(vec![wt.clone()]), &opts).unwrap();
        let outcomes = execute(plan, &opts);
        assert!(
            matches!(
                outcomes[0].result,
                RebaseResult::Conflict {
                    left_in_place: true,
                    ..
                }
            ),
            "the outcome records that the worktree was left mid-rebase"
        );
        // The load-bearing assertion: a rebase really is still in progress, which
        // is what makes `git rebase --continue` (and the tree's cue) meaningful.
        let repo = Repository::open(&wt).unwrap();
        assert_ne!(
            repo.state(),
            RepositoryState::Clean,
            "the worktree must still be mid-rebase, not aborted back to clean"
        );
        // And the conflict markers are on disk for the user to resolve.
        let conflicted = std::fs::read_to_string(wt.join("file.txt")).unwrap();
        assert!(
            conflicted.contains("<<<<<<<"),
            "expected conflict markers, got: {conflicted}"
        );
    }

    #[test]
    fn a_kept_conflict_does_not_stop_the_rest_of_the_batch() {
        // A conflicting worktree left in place must not sink its siblings: the
        // batch continues, and the next worktree still rebases.
        let _guard = serial();
        let scenario = Scenario::new();
        let clashing = scenario.add_worktree("clashing");
        let clean = scenario.add_worktree("clean");
        scenario.commit_in_worktree(&clashing, "file.txt", "feature side\n", "feature edit");
        scenario.advance_origin_main("main side\n");

        let opts = RebaseOptions {
            keep_conflicts: true,
            ..RebaseOptions::default()
        };
        let plan = plan(&Selection::Paths(vec![clashing, clean.clone()]), &opts).unwrap();
        let outcomes = execute(plan, &opts);
        assert!(matches!(
            outcomes[0].result,
            RebaseResult::Conflict {
                left_in_place: true,
                ..
            }
        ));
        assert_eq!(
            outcomes[1].result,
            RebaseResult::Rebased { behind: 1 },
            "the second worktree rebases despite the first being left conflicted"
        );
        assert!(head_contains(&clean, &scenario.origin_main_oid()));
    }

    #[test]
    fn left_in_place_is_omitted_from_json_when_false() {
        // Forward-compatibility: an aborted conflict must serialize byte-identically
        // to the pre-#1415 shape, so an older client is unaffected.
        let aborted = serde_json::to_value(RebaseResult::Conflict {
            detail: "boom".to_string(),
            left_in_place: false,
        })
        .unwrap();
        assert_eq!(aborted["status"], "conflict");
        assert!(aborted.get("left_in_place").is_none());

        let kept = serde_json::to_value(RebaseResult::Conflict {
            detail: "boom".to_string(),
            left_in_place: true,
        })
        .unwrap();
        assert_eq!(kept["left_in_place"], true);
    }

    #[test]
    fn git_bin_defaults_to_the_resolver_and_honours_an_override() {
        assert_eq!(
            RebaseOptions::default().git_bin(),
            crate::git::resolve_git_binary(),
            "an unset git_bin falls back to the shared resolver"
        );
        let opts = RebaseOptions {
            git_bin: Some(PathBuf::from("/custom/git")),
            ..RebaseOptions::default()
        };
        assert_eq!(opts.git_bin(), PathBuf::from("/custom/git"));
    }

    #[test]
    fn dry_run_fetches_but_rebases_nothing() {
        let _guard = serial();
        let scenario = Scenario::new();
        let wt = scenario.add_worktree("feature");
        scenario.advance_origin_main("second\n");
        let head_before = head_oid(&wt);

        let opts = RebaseOptions {
            dry_run: true,
            ..RebaseOptions::default()
        };
        let plan = plan(&Selection::Paths(vec![wt.clone()]), &opts).unwrap();
        // Planned as would-rebase, and the fetch did happen (tracking ref advanced),
        // but we do not call execute in a dry run.
        assert_eq!(
            plan.worktrees[0].result,
            RebaseResult::WouldRebase { behind: 1 }
        );
        assert_eq!(plan.fetches.len(), 1);
        assert!(plan.fetches[0].fetched && plan.fetches[0].ok);
        assert_eq!(
            head_oid(&wt),
            head_before,
            "dry run must not move the branch"
        );
    }

    #[test]
    fn json_shape_is_kebab_tagged() {
        let outcome = WorktreeOutcome {
            path: PathBuf::from("/wt"),
            branch: Some("feature".to_string()),
            onto: "origin/main".to_string(),
            result: RebaseResult::Skipped {
                reason: SkipReason::Dirty,
            },
        };
        let value = serde_json::to_value(&outcome).unwrap();
        assert_eq!(value["status"], "skipped");
        assert_eq!(value["reason"], "dirty");
        assert_eq!(value["onto"], "origin/main");
    }

    // ── classify branches (pure — no git, no subprocess) ──────────────────

    /// An `Inspected::Ok` with a fake (never-opened) repo root, for exercising the
    /// classification branches that return before any repo is opened.
    fn inspected(
        branch: Option<&str>,
        head: Option<Oid>,
        is_main: bool,
        state_clean: bool,
        dirty: bool,
    ) -> Inspected {
        Inspected::Ok(Inspection {
            path: PathBuf::from("/wt"),
            repo_root: PathBuf::from("/repo"),
            branch: branch.map(str::to_string),
            head_oid: head,
            is_main,
            state_clean,
            dirty,
        })
    }

    fn onto_map() -> BTreeMap<PathBuf, OntoSpec> {
        let mut map = BTreeMap::new();
        map.insert(
            PathBuf::from("/repo"),
            OntoSpec {
                display: "origin/main".to_string(),
                fetch: Some(("origin".to_string(), "main".to_string())),
            },
        );
        map
    }

    fn ok_map(ok: bool) -> BTreeMap<PathBuf, bool> {
        let mut map = BTreeMap::new();
        map.insert(PathBuf::from("/repo"), ok);
        map
    }

    fn classify_reason(
        inspected: &Inspected,
        onto: &BTreeMap<PathBuf, OntoSpec>,
        autostash: bool,
    ) -> RebaseResult {
        inspected.classify(onto, &ok_map(true), autostash).result
    }

    #[test]
    fn classify_skips_the_main_working_tree() {
        let out = classify_reason(
            &inspected(Some("main"), Some(Oid::ZERO_SHA1), true, true, false),
            &onto_map(),
            false,
        );
        assert_eq!(
            out,
            RebaseResult::Skipped {
                reason: SkipReason::MainWorkingTree
            }
        );
    }

    #[test]
    fn classify_skips_a_detached_head() {
        let out = classify_reason(
            &inspected(None, Some(Oid::ZERO_SHA1), false, true, false),
            &onto_map(),
            false,
        );
        assert_eq!(
            out,
            RebaseResult::Skipped {
                reason: SkipReason::DetachedHead
            }
        );
    }

    #[test]
    fn classify_skips_an_in_progress_operation() {
        let out = classify_reason(
            &inspected(Some("f"), Some(Oid::ZERO_SHA1), false, false, false),
            &onto_map(),
            false,
        );
        assert_eq!(
            out,
            RebaseResult::Skipped {
                reason: SkipReason::OperationInProgress
            }
        );
    }

    #[test]
    fn classify_skips_dirty_only_without_autostash() {
        let dirty = inspected(Some("f"), Some(Oid::ZERO_SHA1), false, true, true);
        assert_eq!(
            classify_reason(&dirty, &onto_map(), false),
            RebaseResult::Skipped {
                reason: SkipReason::Dirty
            }
        );
        // With autostash the dirty gate is passed; the fake repo root then yields no
        // onto commit, so it lands on the later `NoOntoRef` rather than `Dirty`.
        assert_eq!(
            classify_reason(&dirty, &onto_map(), true),
            RebaseResult::Skipped {
                reason: SkipReason::NoOntoRef
            }
        );
    }

    #[test]
    fn classify_reports_no_onto_ref_when_the_repo_is_unresolved() {
        let out = classify_reason(
            &inspected(Some("f"), Some(Oid::ZERO_SHA1), false, true, false),
            &BTreeMap::new(),
            false,
        );
        assert_eq!(
            out,
            RebaseResult::Skipped {
                reason: SkipReason::NoOntoRef
            }
        );
    }

    #[test]
    fn classify_reports_fetch_failed_when_the_repos_fetch_failed() {
        let out = inspected(Some("f"), Some(Oid::ZERO_SHA1), false, true, false)
            .classify(&onto_map(), &ok_map(false), false)
            .result;
        assert!(matches!(out, RebaseResult::FetchFailed { .. }));
    }

    #[test]
    fn classify_reports_not_a_worktree_for_an_unresolvable_path() {
        let out = Inspected::Unresolvable {
            path: PathBuf::from("/x"),
        }
        .classify(&onto_map(), &ok_map(true), false)
        .result;
        assert_eq!(
            out,
            RebaseResult::Skipped {
                reason: SkipReason::NotAWorktree
            }
        );
    }

    #[test]
    fn head_branch_reports_branch_detached_and_unborn() {
        let dir = tempfile::tempdir().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        config_identity(&repo);
        // Unborn: HEAD points at an unborn branch, no commit yet.
        assert_eq!(head_branch(&repo), (None, None));
        // On a branch.
        let oid = empty_commit(&repo, "refs/heads/main", &[]);
        repo.set_head("refs/heads/main").unwrap();
        let (branch, head) = head_branch(&repo);
        assert_eq!(branch.as_deref(), Some("main"));
        assert_eq!(head, Some(oid));
        // Detached.
        repo.set_head_detached(oid).unwrap();
        assert_eq!(head_branch(&repo), (None, Some(oid)));
    }

    #[test]
    fn resolve_onto_honours_an_override() {
        let (_dir, repo) = repo_with_origin();
        assert_eq!(
            resolve_onto(&repo, Some("origin/main")).fetch,
            Some(("origin".to_string(), "main".to_string()))
        );
        assert_eq!(resolve_onto(&repo, Some("develop")).fetch, None);
    }

    #[test]
    fn fetch_all_skips_the_fetch_for_a_local_onto() {
        let mut map = BTreeMap::new();
        map.insert(
            PathBuf::from("/repo"),
            OntoSpec {
                display: "HEAD~1".to_string(),
                fetch: None,
            },
        );
        let (fetches, ok) = fetch_all(Path::new("git"), &map);
        assert_eq!(fetches.len(), 1);
        assert!(!fetches[0].fetched && fetches[0].ok);
        assert_eq!(ok.get(Path::new("/repo")), Some(&true));
    }

    #[test]
    fn fetch_once_errors_when_the_remote_is_missing() {
        let _guard = serial();
        let dir = tempfile::tempdir().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        config_identity(&repo);
        let err = fetch_once(&resolve_git_binary(), dir.path(), "origin", "main")
            .unwrap_err()
            .to_string();
        assert!(err.contains("git fetch"), "got: {err}");
    }

    // ── test scaffolding ──────────────────────────────────────────────────

    /// A repo with a bare `origin` (so `resolve_onto` sees a real remote) and one
    /// commit on `main`; no worktrees yet.
    fn repo_with_origin() -> (tempfile::TempDir, Repository) {
        let dir = tempfile::tempdir().unwrap();
        let repo = Repository::init(dir.path()).unwrap();
        config_identity(&repo);
        repo.remote("origin", "https://example.invalid/x.git")
            .unwrap();
        let oid = empty_commit(&repo, "refs/heads/main", &[]);
        repo.reference("refs/remotes/origin/main", oid, true, "seed")
            .unwrap();
        (dir, repo)
    }

    /// An `origin` bare repo, a `local` clone with `main` pushed, and helpers to add
    /// worktrees and advance `origin/main` out-of-band (as a second clone would).
    struct Scenario {
        root: tempfile::TempDir,
        origin: PathBuf,
        local: PathBuf,
    }

    impl Scenario {
        fn new() -> Self {
            let root = tempfile::tempdir().unwrap();
            let origin = root.path().join("origin.git");
            let local = root.path().join("local");
            std::fs::create_dir_all(&origin).unwrap();
            std::fs::create_dir_all(&local).unwrap();
            git(&origin, &["init", "--bare", "-b", "main"]);
            git(&local, &["init", "-b", "main"]);
            config_repo(&local, "Test", "test@example.com");
            std::fs::write(local.join("file.txt"), "first\n").unwrap();
            // A second tracked file that `origin/main` never touches, so a dirty
            // edit to it stashes/pops cleanly across a rebase (no false conflict).
            std::fs::write(local.join("keep.txt"), "keep\n").unwrap();
            git(&local, &["add", "file.txt", "keep.txt"]);
            git(&local, &["commit", "-m", "first"]);
            git(
                &local,
                &["remote", "add", "origin", origin.to_str().unwrap()],
            );
            git(&local, &["push", "-u", "origin", "main"]);
            Self {
                root,
                origin,
                local,
            }
        }

        /// Adds a linked worktree branched off the current `main` and returns its path.
        fn add_worktree(&self, name: &str) -> PathBuf {
            let path = self.root.path().join(name);
            git(
                &self.local,
                &[
                    "worktree",
                    "add",
                    "-b",
                    name,
                    path.to_str().unwrap(),
                    "main",
                ],
            );
            path
        }

        /// Advances `origin/main` by one commit that changes `file.txt`, writing
        /// directly into the bare origin's object database with `git2` — the
        /// `local` repo only learns of it on fetch.
        ///
        /// Done in-process (no `git clone`/subprocess) so the git-heavy test suite
        /// stays light enough not to starve unrelated timing-sensitive tests.
        fn advance_origin_main(&self, content: &str) {
            let repo = Repository::open_bare(&self.origin).unwrap();
            let parent = repo
                .find_commit(repo.refname_to_id("refs/heads/main").unwrap())
                .unwrap();
            // Seed the tree from the parent so `keep.txt` survives; only `file.txt`
            // changes (so a worktree that also edited `file.txt` conflicts).
            let mut builder = repo.treebuilder(Some(&parent.tree().unwrap())).unwrap();
            let blob = repo.blob(content.as_bytes()).unwrap();
            builder.insert("file.txt", blob, 0o100_644).unwrap();
            let tree = repo.find_tree(builder.write().unwrap()).unwrap();
            let sig = git2::Signature::now("Other", "other@example.com").unwrap();
            repo.commit(
                Some("refs/heads/main"),
                &sig,
                &sig,
                "advance",
                &tree,
                &[&parent],
            )
            .unwrap();
        }

        /// Commits a change inside a worktree (to set up a conflict).
        fn commit_in_worktree(&self, wt: &Path, file: &str, content: &str, msg: &str) {
            std::fs::write(wt.join(file), content).unwrap();
            git(wt, &["add", file]);
            git(wt, &["commit", "-m", msg]);
        }

        /// The current tip oid of `origin/main` on the server.
        fn origin_main_oid(&self) -> Oid {
            let repo = Repository::open_bare(&self.origin).unwrap();
            repo.refname_to_id("refs/heads/main").unwrap()
        }
    }

    /// Pins a test repo's identity and, crucially, **disables commit signing**.
    ///
    /// Test repos otherwise inherit the developer's global git config; a global
    /// `commit.gpgsign = true` makes every commit shell out to gpg, which fails
    /// under the parallel test suite ("gpg: signing failed: Cannot allocate
    /// memory"). Repo-local config wins over global, and worktrees share the main
    /// repo's config file — so this also covers the commits the production
    /// `git rebase` creates.
    fn config_repo(dir: &Path, name: &str, email: &str) {
        git(dir, &["config", "user.name", name]);
        git(dir, &["config", "user.email", email]);
        git(dir, &["config", "commit.gpgsign", "false"]);
    }

    fn git(dir: &Path, args: &[&str]) {
        let output = run_git_in(&resolve_git_binary(), dir, args).unwrap();
        assert!(
            output.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn config_identity(repo: &Repository) {
        let mut cfg = repo.config().unwrap();
        cfg.set_str("user.name", "Test").unwrap();
        cfg.set_str("user.email", "test@example.com").unwrap();
    }

    fn empty_commit(repo: &Repository, refname: &str, parents: &[&git2::Commit<'_>]) -> Oid {
        let sig = git2::Signature::now("Test", "test@example.com").unwrap();
        let tree = repo
            .find_tree(repo.treebuilder(None).unwrap().write().unwrap())
            .unwrap();
        repo.commit(Some(refname), &sig, &sig, "seed", &tree, parents)
            .unwrap()
    }

    fn head_oid(wt: &Path) -> Oid {
        let repo = Repository::open(wt).unwrap();
        let head = repo.head().unwrap();
        head.target().unwrap()
    }

    fn head_contains(wt: &Path, oid: &Oid) -> bool {
        let repo = Repository::open(wt).unwrap();
        let head = repo.head().unwrap().target().unwrap();
        repo.graph_descendant_of(head, *oid).unwrap_or(false) || head == *oid
    }
}