omh 0.3.0

Launch any coding harness, in a sandbox, with your setup already there.
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
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
//! Sessions are git worktrees on their own branch.
//!
//! This is the part that makes the sandbox real. The container protects your
//! *host*; the worktree protects your *repo*. Your working tree is never
//! mounted, so an agent cannot touch uncommitted work or `main` — review is a
//! plain `git diff`.

use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::process::Command;

/// What `remove` did with the branch, so the caller can report it truthfully
/// rather than always claiming the branch was kept.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Removed {
    /// Commits nobody has reviewed; the branch outlives the session.
    BranchKept,
    /// Nothing was committed, so the branch preserved nothing.
    BranchDropped,
    /// A scratch session (`omh auth`, `omh doctor`) never had one.
    NoBranch,
}

/// What `commit` does about files omh copied in from the checkout.
///
/// `carry_in` is for what a worktree does not get — a tracked file is already
/// there, so listing one is a misconfiguration. It is also the only path by
/// which a secret reaches the agent, and the two compose badly: a tracked path
/// in the list arrives as an ordinary modification, because `carry`'s
/// `info/exclude` is gitignore semantics and says nothing about tracked files.
/// Committing it publishes whatever local edit the user was carrying.
///
/// `carry` warns at launch, where the mistake is made. This is the backstop for
/// a session already running when the list changed.
pub struct Carried<'a> {
    paths: &'a [String],
    skip: bool,
}

impl<'a> Carried<'a> {
    /// Stop and name them. The default, because dropping a change silently is
    /// the second silent behaviour, not the fix for the first.
    pub fn refusing(paths: &'a [String]) -> Self {
        Self { paths, skip: false }
    }

    /// Leave them out and commit the rest — `--skip-carried`. Without it a
    /// tracked carried file makes a session you can never commit from.
    pub fn skipping(paths: &'a [String]) -> Self {
        Self { paths, skip: true }
    }

    /// Carried paths that the staging step actually picked up. A path is
    /// normalised the way `carry` writes it, and a carried *directory* matches
    /// everything under it.
    fn staged_among<'s>(&self, staged: &'s str) -> Vec<&'s str> {
        staged
            .lines()
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .filter(|line| {
                self.paths.iter().any(|p| {
                    let p = p.trim().trim_end_matches('/');
                    *line == p || line.starts_with(&format!("{p}/"))
                })
            })
            .collect()
    }
}

pub struct Session {
    pub id: String,
    /// `None` for a scratch session. `omh auth` and `omh doctor` need a
    /// container and a writable `/work`, not somewhere to keep work — giving
    /// them a branch litters the user's namespace with names like `omh/auth`
    /// that outlive the command that made them.
    pub branch: Option<String>,
    pub worktree: PathBuf,
}

impl Session {
    pub fn new(worktrees_dir: &Path, id: String) -> Self {
        Self {
            branch: Some(format!("omh/{id}")),
            worktree: worktrees_dir.join(&id),
            id,
        }
    }

    /// A throwaway working directory with no branch and no git registration.
    pub fn scratch(dir: PathBuf, id: String) -> Self {
        Self {
            branch: None,
            worktree: dir,
            id,
        }
    }

    /// What to call this session in output.
    pub fn label(&self) -> &str {
        self.branch.as_deref().unwrap_or(&self.id)
    }

    /// Create the worktree if it does not exist yet. Idempotent, so relaunching
    /// into an existing session resumes it.
    pub fn ensure(&self, repo: &Path, base: &str) -> Result<()> {
        if self.worktree.exists() {
            return Ok(());
        }
        std::fs::create_dir_all(self.worktree.parent().unwrap())?;
        let path = self.worktree.to_string_lossy().into_owned();

        // No branch means no git involvement at all — just a writable directory.
        let Some(branch) = self.branch.clone() else {
            std::fs::create_dir_all(&self.worktree)?;
            return Ok(());
        };

        // A directory removed outside git leaves its registration behind, and
        // `worktree add` then refuses forever. Prune first so a session id can
        // never become permanently unusable. Prune only drops entries whose
        // directory is already gone, so live sessions are unaffected.
        let _ = git(repo, &["worktree", "prune"]);

        // `omh rm` keeps branches on purpose, so a session id can outlive its
        // worktree. Reattach to the existing branch rather than failing — that
        // is what resuming a session means.
        let args: Vec<&str> = if self.branch_exists(repo) {
            vec!["worktree", "add", &path, &branch]
        } else {
            // Explicit base: without it git branches from whatever HEAD is,
            // which produces a session whose diff has the wrong baseline.
            vec!["worktree", "add", "-b", &branch, &path, base]
        };
        git(repo, &args).with_context(|| format!("creating worktree for session {}", self.id))?;
        Ok(())
    }

    fn branch_exists(&self, repo: &Path) -> bool {
        let Some(branch) = &self.branch else {
            return false;
        };
        git(repo, &["rev-parse", "--verify", "--quiet", branch]).is_ok()
    }

    /// How many commits `base` has that this session does not. A session that
    /// silently drifts behind trunk makes the agent work against stale code.
    pub fn behind(&self, repo: &Path, base: &str) -> usize {
        let Some(branch) = &self.branch else { return 0 };
        git(repo, &["rev-list", "--count", &format!("{branch}..{base}")])
            .ok()
            .and_then(|out| out.trim().parse().ok())
            .unwrap_or(0)
    }

    /// Commits on this session's branch that are not already in `base`.
    ///
    /// The question `remove` needs answered: whether keeping the branch would
    /// preserve anything.
    pub fn commits(&self, repo: &Path, base: &str) -> usize {
        let Some(branch) = &self.branch else { return 0 };
        git(repo, &["rev-list", "--count", &format!("{base}..{branch}")])
            .ok()
            .and_then(|out| out.trim().parse().ok())
            .unwrap_or(0)
    }

    pub fn remove(&self, repo: &Path, base: &str) -> Result<Removed> {
        // Decided before the worktree goes, because afterwards the branch is
        // the only thing left to ask.
        let outcome = match &self.branch {
            None => Removed::NoBranch,
            Some(_) if self.commits(repo, base) > 0 => Removed::BranchKept,
            Some(_) => Removed::BranchDropped,
        };

        if git(
            repo,
            &[
                "worktree",
                "remove",
                "--force",
                &self.worktree.to_string_lossy(),
            ],
        )
        .is_err()
        {
            // git can lose the registration while the directory survives, and
            // then refuses with "is not a working tree" — leaving a session
            // that can never be removed. Clean up whatever is on disk.
            if self.worktree.exists() {
                std::fs::remove_dir_all(&self.worktree)
                    .with_context(|| format!("removing {}", self.worktree.display()))?;
            }
            let _ = git(repo, &["worktree", "prune"]);
        }

        // A branch carrying commits outlives its worktree on purpose: removing
        // a session must never destroy work nobody has reviewed. A branch
        // carrying none holds nothing to review — `--force` above has already
        // discarded anything uncommitted — so keeping it only leaves a dead ref
        // behind after every abandoned session.
        if outcome == Removed::BranchDropped {
            if let Some(branch) = &self.branch {
                let _ = git(repo, &["branch", "-D", branch]);
            }
        }
        Ok(outcome)
    }

    pub fn diff(&self, repo: &Path, base: &str) -> Result<String> {
        let branch = self
            .branch
            .as_deref()
            .context("a scratch session has no branch")?;
        git(repo, &["diff", "--stat", &format!("{base}...{branch}")])
    }

    /// Stage the agent's work in the worktree and commit it onto the branch.
    ///
    /// Runs in the worktree rather than the checkout. On the host its `.git`
    /// pointer resolves, which is the whole reason this can be a plain git call
    /// — inside the sandbox that pointer leads nowhere and none of this works.
    pub fn commit(&self, message: Option<&str>, carried: Carried) -> Result<()> {
        let branch = self
            .branch
            .as_deref()
            .context("a scratch session has no branch to commit to")?;

        // The worktree is where the agent works, but nothing guarantees it is
        // still on the branch this session is named for — `worktree add -b` is
        // overridden by git's DWIM when the base exists only as `origin/<base>`,
        // and a session can be left detached mid-rebase. Committing anyway puts
        // the work on whatever HEAD happens to be, which has been `main`, and
        // reports the branch it did not touch.
        let head = git(&self.worktree, &["rev-parse", "--abbrev-ref", "HEAD"])?;
        anyhow::ensure!(
            head.trim() == branch,
            "{} is on {} rather than {branch}; omh will not commit to a branch it did not open",
            self.id,
            head.trim()
        );

        git(&self.worktree, &["add", "-A", "."])?;

        // A backstop, not the fix. The rules are mounted rather than written
        // into the worktree, so on a healthy launch there is nothing here to
        // take back — but a bind mount's destination has to exist, and whether
        // the runtime creates that placeholder inside `/work` is unverified
        // against a real container. Cheap insurance against the answer being
        // "yes", and against a backend that cannot mount a single file.
        //
        // An unstage rather than an `:(exclude)` pathspec: naming a path that
        // way still counts as naming it, and git answers "the following paths
        // are ignored by one of your .gitignore files" about the very file the
        // pathspec was written to leave alone.
        git_owned(&self.worktree, &unstage_rules_args())?;

        // Asked *after* staging, and against the index rather than the worktree:
        // `git diff` says nothing about untracked files, so a session whose only
        // work is new files reads as clean when the question comes first. That
        // is the shape of `e0a41b8`, where a release published an empty tap and
        // reported success.
        let staged = git(&self.worktree, &["diff", "--cached", "--name-only"])?;

        // A carried file only reaches the index when the repo tracks it, and
        // then it is the user's own local edit — possibly the secret they were
        // carrying. Refused rather than dropped: omh cannot tell a credential
        // from a deliberate change, and silently discarding either is worse
        // than stopping.
        let from_your_checkout = carried.staged_among(&staged);
        if !from_your_checkout.is_empty() {
            anyhow::ensure!(
                carried.skip,
                "{} is listed in carry_in and git tracks it, so what is in the worktree \
                 is your local copy rather than the branch's.\n  omh will neither publish \
                 that nor drop it silently.\n\n  \
                 fix the cause:  omh repo set carry_in   (carry_in is for files git does not \
                 track; a tracked file is already in the worktree)\n  \
                 or just this once:  omh s commit --skip-carried",
                from_your_checkout.join(", ")
            );
            let unstage: Vec<String> = ["reset", "-q", "--"]
                .iter()
                .map(|s| s.to_string())
                .chain(from_your_checkout.iter().map(|p| p.to_string()))
                .collect();
            git_owned(&self.worktree, &unstage)?;
        }

        let staged = git(&self.worktree, &["diff", "--cached", "--name-only"])?;
        if staged.trim().is_empty() {
            anyhow::bail!("nothing to commit in {}", self.label());
        }

        // Verbatim, and no trailer. omh has no view on what the work was for,
        // which is the refusal `omh why` already makes about rationale it does
        // not hold.
        match message {
            Some(message) => {
                git(&self.worktree, &["commit", "-q", "-m", message])?;
            }
            // git's own editor flow rather than `$EDITOR` directly: it already
            // knows `core.editor`, the commented template, and that an empty
            // message aborts. Reaching past it would reimplement three things
            // slightly wrong. Inherited stdio, because `git()` captures output
            // and an editor with nowhere to draw hangs.
            None => {
                let status = Command::new("git")
                    .current_dir(&self.worktree)
                    .arg("commit")
                    .status()
                    .context("running git commit")?;
                anyhow::ensure!(status.success(), "commit aborted");
            }
        }
        Ok(())
    }

    /// Entries in the worktree's `git status`, committed to nothing.
    ///
    /// `-uall` because git collapses an untracked directory into one line, and
    /// a session where the agent wrote a whole new module would otherwise read
    /// as a single stray file — this is the number `s ls` is glanced at for.
    ///
    /// An error is never zero. The pointer these commands run through is the one
    /// this module documents as leading nowhere inside the sandbox, and a stale
    /// one on the host is what `remove` at line 141 already handles; reporting
    /// that as a clean session is how work gets discarded.
    pub fn uncommitted(&self) -> Result<usize> {
        let out = git_owned(&self.worktree, &status_args())?;
        Ok(out.lines().filter(|l| !l.trim().is_empty()).count())
    }

    /// The branch on origin this session has already been pushed to.
    ///
    /// Read from `branch.<b>.remote`/`.merge` rather than `@{u}`, which resolves
    /// against **HEAD**: a detached worktree would report no upstream for a
    /// branch that demonstrably has one. Anything tracking a remote that is not
    /// origin is an error rather than a name, because reusing it would push to a
    /// different remote than the one it came from.
    pub fn published_as(&self) -> Result<Option<String>> {
        let Some(branch) = self.branch.as_deref() else {
            return Ok(None);
        };
        // `config --get` exits non-zero when unset, which is the common case.
        let remote = git(
            &self.worktree,
            &["config", "--get", &format!("branch.{branch}.remote")],
        )
        .unwrap_or_default();
        let remote = remote.trim();
        if remote.is_empty() {
            return Ok(None);
        }
        anyhow::ensure!(
            remote == "origin",
            "{branch} tracks {remote}, not origin — name the branch explicitly:\n  omh s push <name>"
        );
        let merge = git(
            &self.worktree,
            &["config", "--get", &format!("branch.{branch}.merge")],
        )
        .unwrap_or_default();
        Ok(merge
            .trim()
            .strip_prefix("refs/heads/")
            .filter(|name| !name.is_empty())
            .map(str::to_string))
    }

    /// Commits this session has that origin does not.
    ///
    /// `Ok(None)` means it has never been pushed, which is a different state
    /// from zero: one says name it and push, the other says you are done. `Err`
    /// is a third — git could not answer — and the caller must not render it as
    /// either of the first two.
    pub fn unpushed(&self) -> Result<Option<usize>> {
        let Some(branch) = self.branch.as_deref() else {
            return Ok(None);
        };
        let Some(target) = self.published_as()? else {
            return Ok(None);
        };
        let out = git(
            &self.worktree,
            &[
                "rev-list",
                "--count",
                &format!("refs/remotes/origin/{target}..{branch}"),
            ],
        )?;
        Ok(Some(
            out.trim().parse().context("counting unpushed commits")?,
        ))
    }

    /// Push the session branch to origin under a name a reviewer can read, and
    /// return the name it landed under.
    ///
    /// Naming is required the first time and never again. `omh/s01` records
    /// *when* the work happened rather than what it was, and on origin it
    /// outlives the session that would explain it — so omh refuses rather than
    /// choosing, the same refusal it makes about commit messages.
    pub fn push(&self, name: Option<&str>) -> Result<String> {
        let branch = self
            .branch
            .as_deref()
            .context("a scratch session has no branch to push")?;

        let target = match name {
            Some(name) => name.to_string(),
            None => self.published_as()?.with_context(|| {
                format!(
                    "{branch} is a session id, not a branch name\n  name it:  omh s push <name>"
                )
            })?,
        };

        // No `-u` here. Recording the upstream is what makes `s ls` report the
        // branch as published, and doing it in the same breath as the push means
        // a push that never reached origin still leaves that claim behind, with
        // nothing to roll it back. Set it below, once there is something true to
        // record.
        git(
            &self.worktree,
            &["push", "origin", &format!("{branch}:refs/heads/{target}")],
        )?;

        // Read it back from origin before calling this a success. `git push`
        // reports on the push URL, which need not be the fetch URL a reviewer
        // opens the PR from — the same green-and-wrong shape as `e0a41b8`, where
        // a release job passed while the tap it published to stayed empty.
        let local = git(&self.worktree, &["rev-parse", branch])?;
        let published = git(
            &self.worktree,
            &["ls-remote", "origin", &format!("refs/heads/{target}")],
        )?;
        let published = published.split_whitespace().next().unwrap_or_default();
        anyhow::ensure!(
            published == local.trim(),
            "push reported success, but origin/{target} does not hold {branch}"
        );

        git(
            &self.worktree,
            &[
                "branch",
                "--set-upstream-to",
                &format!("origin/{target}"),
                branch,
            ],
        )?;
        Ok(target)
    }
}

/// The files omh wrote into the worktree, kept out of the user's work.
///
/// `carry`'s `info/exclude` covers these only while they are untracked, and a
/// repo that commits its own `CLAUDE.md` — normal for one whose users run agent
/// harnesses — has omh's copy written over a tracked file, which gitignore
/// semantics say nothing about. Without this, omh's generated rules land on top
/// of the project's own conventions in the user's commit, and a session where
/// the agent did nothing still looks like it has work in it.
fn rules_pathspec() -> Vec<String> {
    std::iter::once(".".to_string())
        .chain(
            crate::carry::STAGED_RULES
                .iter()
                .map(|name| format!(":(exclude){name}")),
        )
        .collect()
}

fn unstage_rules_args() -> Vec<String> {
    ["reset", "-q", "--"]
        .iter()
        .map(|s| s.to_string())
        .chain(crate::carry::STAGED_RULES.iter().map(|n| n.to_string()))
        .collect()
}

fn status_args() -> Vec<String> {
    ["status", "--porcelain", "-uall", "--"]
        .iter()
        .map(|s| s.to_string())
        .chain(rules_pathspec())
        .collect()
}

/// Reject a session id that is not a single path component.
///
/// `-s` reaches `Session::new` straight from the command line and the worktree
/// path is joined from it — and `remove` deletes that directory.
pub fn validate_id(id: &str) -> Result<()> {
    if id.trim().is_empty() {
        anyhow::bail!("a session needs a name");
    }
    if id == "." || id == ".." || id.contains('/') || id.contains('\\') {
        anyhow::bail!("a session id is a single name, not a path: `{id}`");
    }
    Ok(())
}

/// The branch a session should be reviewed against. Hardcoding `main` breaks
/// every repo that still uses `master`, or any other convention — and it fails
/// at review time, after the agent has already done the work.
pub fn default_branch(repo: &Path) -> String {
    // What the remote says is authoritative when there is one — but only while
    // it still points at something. `origin/HEAD` is cached at clone time and
    // nothing refreshes it when a repo renames its trunk, so a repo cloned back
    // when it was `master` keeps claiming `master` forever. Taking that claim on
    // faith fails at `worktree add` with `invalid reference`, which is every
    // session, not just review time.
    if let Ok(head) = git(
        repo,
        &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
    ) {
        if let Some(name) = head.trim().strip_prefix("origin/") {
            let remote_ref = format!("refs/remotes/origin/{name}");
            if !name.is_empty()
                && git(repo, &["rev-parse", "--verify", "--quiet", &remote_ref]).is_ok()
            {
                return name.to_string();
            }
        }
    }
    for candidate in ["main", "master"] {
        if git(repo, &["rev-parse", "--verify", "--quiet", candidate]).is_ok() {
            return candidate.to_string();
        }
    }
    // Whatever this repo actually calls its trunk.
    git(repo, &["rev-parse", "--abbrev-ref", "HEAD"])
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|_| "HEAD".into())
}

/// The session a bare `omh <harness>` or `omh attach` should land in: the most
/// recently created one.
pub fn current(worktrees_dir: &Path) -> Option<String> {
    list(worktrees_dir).pop()
}

/// Resolve which session to use. Creating a fresh one on every launch would
/// defeat persistence entirely — you would never reattach to the agent you left
/// running — so a new session is something you ask for.
pub fn pick(worktrees_dir: &Path, explicit: Option<&str>, new: bool) -> String {
    if let Some(id) = explicit {
        return id.to_string();
    }
    if new {
        return next_id(worktrees_dir);
    }
    current(worktrees_dir).unwrap_or_else(|| next_id(worktrees_dir))
}

/// Human-readable, monotonic session ids: `s01`, `s02`, ...
pub fn next_id(worktrees_dir: &Path) -> String {
    let used = std::fs::read_dir(worktrees_dir)
        .map(|entries| {
            entries
                .flatten()
                .filter_map(|e| {
                    e.file_name()
                        .to_string_lossy()
                        .strip_prefix('s')?
                        .parse::<u32>()
                        .ok()
                })
                .max()
                .unwrap_or(0)
        })
        .unwrap_or(0);
    format!("s{:02}", used + 1)
}

pub fn list(worktrees_dir: &Path) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(worktrees_dir) else {
        return Vec::new();
    };
    let mut out: Vec<_> = entries
        .flatten()
        .filter(|e| e.path().is_dir())
        .map(|e| e.file_name().to_string_lossy().to_string())
        .collect();
    out.sort();
    out
}

/// `git` for the callers that build their arguments dynamically.
fn git_owned(cwd: &Path, args: &[String]) -> Result<String> {
    let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
    git(cwd, &borrowed)
}

fn git(cwd: &Path, args: &[&str]) -> Result<String> {
    let out = Command::new("git")
        .current_dir(cwd)
        .args(args)
        .output()
        .context("running git")?;
    if !out.status.success() {
        anyhow::bail!(
            "git {}: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

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

    fn repo() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("repo");
        std::fs::create_dir_all(&root).unwrap();
        for args in [
            vec!["init", "-q", "-b", "main"],
            vec!["config", "user.email", "t@example.com"],
            vec!["config", "user.name", "t"],
            vec!["commit", "-q", "--allow-empty", "-m", "root"],
        ] {
            git(&root, &args).unwrap();
        }
        (dir, root)
    }

    /// `rm` keeps a branch so unreviewed work is unloseable. A branch with no
    /// commits holds no work to lose — `worktree remove --force` has already
    /// discarded anything uncommitted — so keeping it preserves nothing and
    /// leaves a dead ref behind after every abandoned session.
    #[test]
    fn removing_a_session_that_produced_nothing_drops_its_branch() {
        let (dir, root) = repo();
        let s = Session::new(&dir.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();

        let outcome = s.remove(&root, "main").unwrap();
        assert_eq!(outcome, Removed::BranchDropped);
        assert!(
            git(&root, &["rev-parse", "--verify", "omh/s01"]).is_err(),
            "an empty branch should not survive its session"
        );
    }

    /// The load-bearing half: a branch carrying commits must survive, because
    /// `rm` must never be able to destroy work nobody has reviewed.
    #[test]
    fn removing_a_session_that_committed_keeps_its_branch() {
        let (dir, root) = repo();
        let s = Session::new(&dir.path().join("wt"), "s02".into());
        s.ensure(&root, "main").unwrap();

        std::fs::write(s.worktree.join("work.txt"), "agent output").unwrap();
        git(&s.worktree, &["add", "."]).unwrap();
        git(&s.worktree, &["commit", "-q", "-m", "agent work"]).unwrap();

        let outcome = s.remove(&root, "main").unwrap();
        assert_eq!(outcome, Removed::BranchKept);
        assert!(
            git(&root, &["rev-parse", "--verify", "omh/s02"]).is_ok(),
            "unreviewed work must be unloseable"
        );
    }

    /// A scratch session (`omh auth`, `omh doctor`) has no branch at all, and
    /// asking git about one would error rather than report nothing to keep.
    #[test]
    fn removing_a_scratch_session_reports_no_branch() {
        let (dir, root) = repo();
        let mut s = Session::new(&dir.path().join("wt"), "s03".into());
        s.branch = None;
        s.ensure(&root, "main").unwrap();
        assert_eq!(s.remove(&root, "main").unwrap(), Removed::NoBranch);
    }

    #[test]
    fn ensure_creates_worktree_on_its_own_branch() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        assert!(s.worktree.join(".git").exists());
        assert_eq!(s.branch.as_deref(), Some("omh/s01"));
    }

    #[test]
    fn ensure_is_idempotent() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        s.ensure(&root, "main").unwrap();
    }

    /// Regression: `rm` keeps branches on purpose so unreviewed work can never be
    /// destroyed — which made reusing a session id fail, because `ensure` always
    /// passed `-b`. Resuming a session must reattach to its existing branch.
    #[test]
    fn session_resumes_onto_a_surviving_branch() {
        let (d, root) = repo();
        let wt = d.path().join("wt");
        let s = Session::new(&wt, "s01".into());

        s.ensure(&root, "main").unwrap();
        std::fs::write(s.worktree.join("work.txt"), "agent output").unwrap();
        git(&s.worktree, &["add", "-A"]).unwrap();
        git(&s.worktree, &["commit", "-q", "-m", "agent work"]).unwrap();

        s.remove(&root, "main").unwrap();
        assert!(!s.worktree.exists(), "worktree gone");
        assert!(s.branch_exists(&root), "branch must survive rm");

        s.ensure(&root, "main").unwrap();
        assert_eq!(
            std::fs::read_to_string(s.worktree.join("work.txt")).unwrap(),
            "agent output",
            "resuming must recover the branch's work, not start empty"
        );
    }

    #[test]
    fn diff_reports_against_base() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        std::fs::write(s.worktree.join("new.rs"), "fn main() {}").unwrap();
        git(&s.worktree, &["add", "-A"]).unwrap();
        git(&s.worktree, &["commit", "-q", "-m", "add"]).unwrap();
        assert!(s.diff(&root, "main").unwrap().contains("new.rs"));
    }

    // ── committing a session's work ─────────────────────────────────────────

    /// What the commit actually contains, which is the only question these
    /// tests are asking. `git status` would answer about the worktree instead.
    fn committed_files(wt: &Path) -> String {
        git(wt, &["ls-tree", "-r", "--name-only", "HEAD"]).unwrap()
    }

    /// `commit` stages everything, so the guarantee that omh's own staging stays
    /// out of the user's work rests entirely on `carry`'s exclusion holding.
    /// Nothing else connects these two modules, and the failure — omh's
    /// `CLAUDE.md` riding into a PR on the commit omh itself made — is invisible
    /// until a reviewer finds it.
    #[test]
    fn a_file_omh_staged_never_reaches_the_commit() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        crate::carry::hide_staged_rules(&s.worktree).unwrap();
        std::fs::write(s.worktree.join("CLAUDE.md"), "staged by omh").unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();

        s.commit(Some("Add the work"), Carried::refusing(&[]))
            .unwrap();

        let files = committed_files(&s.worktree);
        assert!(
            files.contains("work.rs"),
            "the agent's work must land: {files}"
        );
        assert!(
            !files.contains("CLAUDE.md"),
            "omh's own staging must not: {files}"
        );
    }

    /// `git diff` does not report untracked files, so asking whether anything
    /// changed *before* staging answers "nothing" for a session whose only work
    /// is new files. That is `e0a41b8` — the tap formula a release published as
    /// a no-op — arriving in a second place.
    #[test]
    fn a_brand_new_file_is_committed_rather_than_read_as_nothing_to_do() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        std::fs::write(s.worktree.join("brand-new.rs"), "fn main() {}").unwrap();

        s.commit(Some("Add a new file"), Carried::refusing(&[]))
            .unwrap();

        assert!(committed_files(&s.worktree).contains("brand-new.rs"));
    }

    /// A no-op reporting success teaches people to trust a commit that never
    /// happened, and the next command they run is `push`.
    #[test]
    fn committing_a_clean_worktree_is_an_error() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();

        let err = s
            .commit(Some("nothing to say"), Carried::refusing(&[]))
            .unwrap_err();
        assert!(err.to_string().contains("nothing to commit"), "got: {err}");
    }

    /// omh has no view on what the work was for and will not invent one — the
    /// same refusal `omh why` makes about rationale it does not hold.
    #[test]
    fn the_commit_message_is_exactly_what_was_given() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();

        s.commit(Some("Fix the guard"), Carried::refusing(&[]))
            .unwrap();

        let message = git(&s.worktree, &["log", "-1", "--format=%B"]).unwrap();
        assert_eq!(
            message.trim(),
            "Fix the guard",
            "omh added something to the message"
        );
    }

    // ── pushing it somewhere a PR can be opened from ────────────────────────

    /// A real bare remote rather than a mock: half of what `push` promises is
    /// that the branch actually arrived, and nothing you can stub answers that.
    fn repo_with_origin() -> (tempfile::TempDir, PathBuf) {
        let (d, root) = repo();
        let origin = d.path().join("origin.git");
        git(
            d.path(),
            &["init", "-q", "--bare", origin.to_str().unwrap()],
        )
        .unwrap();
        git(
            &root,
            &["remote", "add", "origin", origin.to_str().unwrap()],
        )
        .unwrap();
        (d, root)
    }

    fn session_with_a_commit(root: &Path, wt: &Path, file: &str) -> Session {
        let s = Session::new(wt, "s01".into());
        s.ensure(root, "main").unwrap();
        std::fs::write(s.worktree.join(file), "fn main() {}").unwrap();
        s.commit(Some("Add the work"), Carried::refusing(&[]))
            .unwrap();
        s
    }

    /// `omh/s01` names when the work happened, not what it was. On origin it
    /// outlives the session that explains it, and it is what the PR inherits.
    #[test]
    fn pushing_without_a_name_refuses_rather_than_using_the_session_id() {
        let (d, root) = repo_with_origin();
        let s = session_with_a_commit(&root, &d.path().join("wt"), "work.rs");

        let err = s.push(None).unwrap_err();

        assert!(err.to_string().contains("not a branch name"), "got: {err}");
    }

    #[test]
    fn a_named_push_reaches_the_remote_and_sets_upstream() {
        let (d, root) = repo_with_origin();
        let s = session_with_a_commit(&root, &d.path().join("wt"), "work.rs");

        s.push(Some("fix/tap-guard")).unwrap();

        assert_eq!(s.published_as().unwrap().as_deref(), Some("fix/tap-guard"));
        let on_remote = git(&root, &["ls-remote", "origin", "fix/tap-guard"]).unwrap();
        assert!(
            !on_remote.trim().is_empty(),
            "the branch must actually be on origin"
        );
    }

    /// Naming it once is the whole bargain: refusing every time would be a
    /// command you cannot put in a loop.
    #[test]
    fn a_later_push_needs_no_name() {
        let (d, root) = repo_with_origin();
        let s = session_with_a_commit(&root, &d.path().join("wt"), "work.rs");
        s.push(Some("fix/tap-guard")).unwrap();

        std::fs::write(s.worktree.join("more.rs"), "fn more() {}").unwrap();
        s.commit(Some("Add more"), Carried::refusing(&[])).unwrap();

        assert_eq!(s.push(None).unwrap(), "fix/tap-guard");
    }

    /// Every local step can succeed while the remote a reviewer would open the
    /// PR from stays untouched — which is `e0a41b8` exactly: a release job that
    /// copied, staged, pushed and passed, against a local clone, while the tap
    /// it was publishing to stayed empty.
    ///
    /// Reproduced with a `pushurl`, because that is the configuration where the
    /// push genuinely succeeds and origin genuinely does not have it. Deleting
    /// the remote instead only proves that `git push` fails when there is
    /// nothing to push to, which needs no guard of ours — that version stays
    /// green with the read-back removed.
    #[test]
    fn a_push_that_did_not_reach_origin_is_not_a_success() {
        let (d, root) = repo_with_origin();
        let s = session_with_a_commit(&root, &d.path().join("wt"), "work.rs");
        let elsewhere = d.path().join("elsewhere.git");
        git(
            d.path(),
            &["init", "-q", "--bare", elsewhere.to_str().unwrap()],
        )
        .unwrap();
        git(
            &root,
            &[
                "config",
                "remote.origin.pushurl",
                elsewhere.to_str().unwrap(),
            ],
        )
        .unwrap();

        let err = s.push(Some("fix/tap-guard")).unwrap_err();

        assert!(
            err.to_string().contains("does not hold"),
            "the push succeeded; only the read-back can catch this: {err}"
        );
    }

    // ── what `s ls` reports about work in flight ────────────────────────────

    /// The state that strands work is the one `s ls` cannot otherwise see: a
    /// session holding a day of uncommitted changes reads exactly like an
    /// untouched one. It must not count what omh itself put there, for the same
    /// reason `commit` must not commit it.
    #[test]
    fn uncommitted_counts_the_agents_work_and_not_omhs_own() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        crate::carry::hide_staged_rules(&s.worktree).unwrap();
        std::fs::write(s.worktree.join("CLAUDE.md"), "staged by omh").unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();

        assert_eq!(s.uncommitted().unwrap(), 1);
    }

    #[test]
    fn a_clean_session_reports_nothing_uncommitted() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();

        assert_eq!(s.uncommitted().unwrap(), 0);
    }

    /// Before a push there is no upstream to measure against, which is a
    /// different answer from "nothing to push" — one means name it, the other
    /// means you are done.
    #[test]
    fn unpushed_distinguishes_never_pushed_from_up_to_date() {
        let (d, root) = repo_with_origin();
        let s = session_with_a_commit(&root, &d.path().join("wt"), "work.rs");
        assert_eq!(s.unpushed().unwrap(), None, "never pushed");

        s.push(Some("fix/tap-guard")).unwrap();
        assert_eq!(s.unpushed().unwrap(), Some(0), "everything is on origin");

        std::fs::write(s.worktree.join("more.rs"), "fn more() {}").unwrap();
        s.commit(Some("Add more"), Carried::refusing(&[])).unwrap();
        assert_eq!(s.unpushed().unwrap(), Some(1));
    }

    /// A repo that commits its own `CLAUDE.md` is the normal case for one whose
    /// users run agent harnesses, and it is the case `carry`'s exclusion cannot
    /// reach: `info/exclude` is gitignore semantics, silent about a file git
    /// already tracks. omh overwrites it at launch, so git sees a modification
    /// and `add -A` stages it — omh's generated rules landing on top of the
    /// project's own conventions, in the user's PR, on the commit omh made.
    #[test]
    fn omhs_rules_stay_out_of_the_commit_even_when_the_repo_tracks_them() {
        let (d, root) = repo();
        // The repo's own file, committed before any session exists.
        std::fs::write(root.join("CLAUDE.md"), "# House style\n\nTabs.\n").unwrap();
        git(&root, &["add", "-A"]).unwrap();
        git(&root, &["commit", "-q", "-m", "house style"]).unwrap();

        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        crate::carry::hide_staged_rules(&s.worktree).unwrap();
        // What omh does at launch: overwrite it with the merged rules.
        std::fs::write(s.worktree.join("CLAUDE.md"), "omh generated rules").unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();

        s.commit(Some("Add the work"), Carried::refusing(&[]))
            .unwrap();

        let committed = git(&s.worktree, &["show", "--stat", "--name-only", "HEAD"]).unwrap();
        assert!(committed.contains("work.rs"), "got: {committed}");
        assert!(
            !committed.contains("CLAUDE.md"),
            "omh clobbered the project's own conventions file: {committed}"
        );
        // And the repo's version is what survives on the branch.
        let on_branch = git(&s.worktree, &["show", "HEAD:CLAUDE.md"]).unwrap();
        assert!(on_branch.contains("House style"), "got: {on_branch}");
    }

    /// The same overwrite, in a session where the agent did nothing. Left
    /// counted, omh's own clobbering is the entire diff — so `commit` reports
    /// success for work that does not exist, and `s ls` reads `1 uncommitted`
    /// for a session nobody has touched.
    #[test]
    fn a_session_holding_only_omhs_overwrite_has_nothing_to_commit() {
        let (d, root) = repo();
        std::fs::write(root.join("CLAUDE.md"), "# House style\n").unwrap();
        git(&root, &["add", "-A"]).unwrap();
        git(&root, &["commit", "-q", "-m", "house style"]).unwrap();

        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        crate::carry::hide_staged_rules(&s.worktree).unwrap();
        std::fs::write(s.worktree.join("CLAUDE.md"), "omh generated rules").unwrap();

        assert_eq!(
            s.uncommitted().ok(),
            Some(0),
            "omh's own staging is not work"
        );
        let err = s
            .commit(Some("nothing the agent did"), Carried::refusing(&[]))
            .unwrap_err();
        assert!(err.to_string().contains("nothing to commit"), "got: {err}");
    }

    /// `git status --porcelain` collapses an untracked directory into one entry,
    /// so a session where the agent wrote a whole new module reads as a single
    /// stray file — and this is the number `s ls` is designed to be glanced at.
    #[test]
    fn a_new_directory_counts_once_per_file_not_once() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        std::fs::create_dir_all(s.worktree.join("newmodule")).unwrap();
        for i in 0..12 {
            std::fs::write(s.worktree.join(format!("newmodule/f{i}.rs")), "fn f() {}").unwrap();
        }

        assert_eq!(s.uncommitted().unwrap(), 12);
    }

    /// `carry_in` is documented as the only path by which a secret reaches the
    /// agent, and a carried file that the repo *tracks* arrives in the worktree
    /// as an ordinary modification — `info/exclude` says nothing about tracked
    /// files. Staged and committed, a local edit holding a credential is on the
    /// branch, and one `s push` from being published.
    #[test]
    fn a_carried_file_the_repo_tracks_is_refused_rather_than_committed() {
        let (d, root) = repo();
        std::fs::write(root.join("config.toml"), "PORT=3000\n").unwrap();
        git(&root, &["add", "-A"]).unwrap();
        git(&root, &["commit", "-q", "-m", "config"]).unwrap();

        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        // The user's local edit, carried in as `carry::apply` copies it.
        std::fs::write(
            s.worktree.join("config.toml"),
            "PORT=3000\nSECRET=hunter2\n",
        )
        .unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();

        let carried = ["config.toml".to_string()];
        let err = s
            .commit(Some("Add the work"), Carried::refusing(&carried))
            .unwrap_err();

        assert!(err.to_string().contains("config.toml"), "got: {err}");
        assert_eq!(s.commits(&root, "main"), 0, "nothing may land");
    }

    /// The escape hatch, because refusing forever would make a carried file that
    /// the repo tracks a session you can never commit from.
    #[test]
    fn skipping_carried_files_commits_the_rest_and_leaves_them_behind() {
        let (d, root) = repo();
        std::fs::write(root.join("config.toml"), "PORT=3000\n").unwrap();
        git(&root, &["add", "-A"]).unwrap();
        git(&root, &["commit", "-q", "-m", "config"]).unwrap();

        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        std::fs::write(
            s.worktree.join("config.toml"),
            "PORT=3000\nSECRET=hunter2\n",
        )
        .unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();

        let carried = ["config.toml".to_string()];
        s.commit(Some("Add the work"), Carried::skipping(&carried))
            .unwrap();

        let committed = git(&s.worktree, &["show", "--stat", "--name-only", "HEAD"]).unwrap();
        assert!(committed.contains("work.rs"), "got: {committed}");
        assert!(
            !committed.contains("config.toml"),
            "the secret must not land: {committed}"
        );
    }

    /// A carried file the repo does not track is already invisible to git, so it
    /// must not turn every commit into a refusal.
    #[test]
    fn an_untracked_carried_file_is_not_something_to_refuse_over() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        crate::carry::apply(&root, &s.worktree, &[".env.local".to_string()]).ok();
        std::fs::write(s.worktree.join(".env.local"), "SECRET=hunter2\n").unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();

        let carried = [".env.local".to_string()];
        s.commit(Some("Add the work"), Carried::refusing(&carried))
            .unwrap();

        let committed = git(&s.worktree, &["show", "--stat", "--name-only", "HEAD"]).unwrap();
        assert!(!committed.contains(".env.local"), "got: {committed}");
    }

    /// Without `-m`, git owns the message and can refuse it — an editor that
    /// writes nothing means an empty message, and git aborts. Accepting that as
    /// success reports `committed to omh/s01 (0 commits)` and exits zero, which
    /// is the same lie as an empty commit and reaches the user one command later,
    /// at `push`.
    #[test]
    fn a_commit_the_editor_abandoned_is_not_reported_as_made() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();
        // An "editor" that exits 0 having written nothing.
        git(&s.worktree, &["config", "core.editor", "true"]).unwrap();

        let err = s.commit(None, Carried::refusing(&[])).unwrap_err();

        assert!(err.to_string().contains("aborted"), "got: {err}");
        assert_eq!(
            s.commits(&root, "main"),
            0,
            "nothing may land on the branch"
        );
    }

    /// `branch.autoSetupMerge = always` — a documented git setting — makes
    /// `worktree add -b omh/s01 <path> main` track the **local** `main`. Parsing
    /// that upstream as `remote/branch` yields `main` as a branch name on origin,
    /// it fast-forwards, the read-back passes because it checks the ref it just
    /// pushed, and unreviewed agent work is on trunk.
    #[test]
    fn an_upstream_that_is_not_on_origin_is_never_read_as_a_branch_name() {
        let (d, root) = repo_with_origin();
        git(&root, &["config", "branch.autoSetupMerge", "always"]).unwrap();
        git(&root, &["push", "-q", "-u", "origin", "main"]).unwrap();
        let s = session_with_a_commit(&root, &d.path().join("wt"), "work.rs");

        let err = s.push(None).unwrap_err();

        assert!(
            err.to_string().contains("not a branch name") || err.to_string().contains("not origin"),
            "got: {err}"
        );
        let on_origin = git(&root, &["ls-remote", "origin", "refs/heads/main"]).unwrap();
        let trunk = git(&root, &["rev-parse", "main"]).unwrap();
        assert!(
            on_origin.starts_with(trunk.trim()),
            "the session branch reached origin/main: {on_origin}"
        );
    }

    /// `worktree add -b` loses to git's DWIM when the base exists only as
    /// `origin/<base>`: the worktree lands on a local branch named after the
    /// base instead. Committing then puts the agent's work on trunk and reports
    /// the branch it never touched.
    #[test]
    fn a_worktree_that_drifted_off_its_branch_is_not_committed_to() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        git(&s.worktree, &["checkout", "-q", "-b", "somewhere-else"]).unwrap();
        std::fs::write(s.worktree.join("work.rs"), "fn main() {}").unwrap();

        let err = s
            .commit(Some("Add the work"), Carried::refusing(&[]))
            .unwrap_err();

        assert!(
            err.to_string().contains("rather than omh/s01"),
            "got: {err}"
        );
    }

    /// The read-back is a detector with no undo. Recording the upstream in the
    /// same breath as the push leaves that record behind when the push did not
    /// reach origin — and `s ls` then reports the branch as published while the
    /// remote holds nothing, which is the `e0a41b8` state the guard exists to
    /// prevent, reproduced by the guard itself.
    #[test]
    fn a_failed_push_leaves_no_claim_that_the_branch_is_published() {
        let (d, root) = repo_with_origin();
        let s = session_with_a_commit(&root, &d.path().join("wt"), "work.rs");
        let elsewhere = d.path().join("elsewhere.git");
        git(
            d.path(),
            &["init", "-q", "--bare", elsewhere.to_str().unwrap()],
        )
        .unwrap();
        git(
            &root,
            &[
                "config",
                "remote.origin.pushurl",
                elsewhere.to_str().unwrap(),
            ],
        )
        .unwrap();

        assert!(s.push(Some("fix/tap-guard")).is_err());

        assert_eq!(
            s.published_as().unwrap(),
            None,
            "a push that never reached origin must not claim it did"
        );
    }

    /// `omh auth` and `omh doctor` get a writable directory, not somewhere to
    /// keep work. `diff` already refuses them; so must this.
    ///
    /// Asserting the reason: a scratch directory is not a git repository, so
    /// `add -A` refuses on its own and a bare `is_err()` stays green with the
    /// branch guard deleted.
    #[test]
    fn a_scratch_session_cannot_be_committed() {
        let d = tempfile::tempdir().unwrap();
        let s = Session::scratch(d.path().join("scratch"), "doctor".into());
        std::fs::create_dir_all(&s.worktree).unwrap();
        let err = s
            .commit(Some("anything"), Carried::refusing(&[]))
            .unwrap_err();
        assert!(err.to_string().contains("no branch"), "got: {err}");
    }

    #[test]
    fn ids_increment_and_list_in_order() {
        let d = tempfile::tempdir().unwrap();
        let wt = d.path().join("wt");
        std::fs::create_dir_all(&wt).unwrap();
        assert_eq!(next_id(&wt), "s01");
        std::fs::create_dir_all(wt.join("s01")).unwrap();
        std::fs::create_dir_all(wt.join("s02")).unwrap();
        assert_eq!(next_id(&wt), "s03");
        assert_eq!(list(&wt), ["s01", "s02"]);
    }

    #[test]
    fn git_failure_surfaces_stderr() {
        let (_d, root) = repo();
        let err = git(&root, &["rev-parse", "--verify", "nope"]).unwrap_err();
        assert!(err.to_string().contains("rev-parse"), "got: {err}");
    }

    /// Regression: a worktree directory removed outside git (manual `rm -rf`,
    /// disk cleanup, a stale checkout) left the registration behind, and every
    /// later `ensure` failed with "missing but already registered". A session id
    /// must never become permanently unusable.
    #[test]
    fn a_worktree_deleted_behind_gits_back_is_recoverable() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();

        std::fs::remove_dir_all(&s.worktree).unwrap();

        s.ensure(&root, "main")
            .expect("must recover rather than fail forever");
        assert!(s.worktree.join(".git").exists());
    }

    /// Pruning must not disturb a session whose directory is still there.
    #[test]
    fn recovering_one_session_leaves_others_alone() {
        let (d, root) = repo();
        let wt = d.path().join("wt");
        let keep = Session::new(&wt, "s01".into());
        let lose = Session::new(&wt, "s02".into());
        keep.ensure(&root, "main").unwrap();
        lose.ensure(&root, "main").unwrap();

        std::fs::remove_dir_all(&lose.worktree).unwrap();
        lose.ensure(&root, "main").unwrap();

        assert!(
            keep.worktree.join(".git").exists(),
            "untouched session survived"
        );
        assert!(lose.worktree.join(".git").exists());
    }

    fn repo_on(branch: &str) -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("repo");
        std::fs::create_dir_all(&root).unwrap();
        for args in [
            vec!["init", "-q", "-b", branch],
            vec!["config", "user.email", "t@example.com"],
            vec!["config", "user.name", "t"],
            vec!["commit", "-q", "--allow-empty", "-m", "root"],
        ] {
            git(&root, &args).unwrap();
        }
        (dir, root)
    }

    /// Regression: `omh diff` assumed `main`, so on a `master` repo it failed at
    /// review time — after the agent had already done the work.
    #[test]
    fn the_default_branch_is_detected_not_assumed() {
        for branch in ["main", "master", "trunk"] {
            let (_d, root) = repo_on(branch);
            assert_eq!(default_branch(&root), branch, "on a {branch} repo");
        }
    }

    /// The remote knows its own trunk better than any local convention does, so
    /// `origin/HEAD` outranks the `main`/`master` guess.
    #[test]
    fn the_remotes_own_answer_outranks_local_convention() {
        let (_d, root) = repo_on("main");
        git(&root, &["update-ref", "refs/remotes/origin/trunk", "HEAD"]).unwrap();
        git(
            &root,
            &[
                "symbolic-ref",
                "refs/remotes/origin/HEAD",
                "refs/remotes/origin/trunk",
            ],
        )
        .unwrap();

        assert_eq!(default_branch(&root), "trunk");
    }

    /// Regression: `origin/HEAD` is a cached guess from clone time that nothing
    /// updates when a repo renames its trunk, so it can name a branch that no
    /// longer exists. Trusting it unchecked made every session fail to start
    /// with `invalid reference: master`.
    #[test]
    fn a_stale_origin_head_loses_to_a_branch_that_exists() {
        let (_d, root) = repo_on("main");
        git(&root, &["update-ref", "refs/remotes/origin/main", "HEAD"]).unwrap();
        git(
            &root,
            &[
                "symbolic-ref",
                "refs/remotes/origin/HEAD",
                "refs/remotes/origin/master",
            ],
        )
        .unwrap();

        assert_eq!(default_branch(&root), "main");
    }

    #[test]
    fn diff_against_the_detected_default_just_works() {
        let (d, root) = repo_on("master");
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "master").unwrap();
        std::fs::write(s.worktree.join("new.rs"), "fn main() {}").unwrap();
        git(&s.worktree, &["add", "-A"]).unwrap();
        git(&s.worktree, &["commit", "-q", "-m", "work"]).unwrap();

        let out = s.diff(&root, &default_branch(&root)).unwrap();
        assert!(out.contains("new.rs"), "got: {out}");
    }

    /// Regression: sessions branched from whatever HEAD happened to be, so one
    /// created while you were on a feature branch — or a moment before a commit
    /// landed — started from the wrong place and its diff was meaningless.
    #[test]
    fn a_new_session_branches_from_the_named_base_not_from_head() {
        let (d, root) = repo_on("master");
        git(
            &root,
            &["commit", "-q", "--allow-empty", "-m", "trunk work"],
        )
        .unwrap();
        let trunk_tip = git(&root, &["rev-parse", "master"])
            .unwrap()
            .trim()
            .to_string();

        // wander off somewhere unrelated before creating the session
        git(&root, &["checkout", "-q", "-b", "feature"]).unwrap();
        git(&root, &["commit", "-q", "--allow-empty", "-m", "unrelated"]).unwrap();

        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "master").unwrap();

        let started_at = git(&s.worktree, &["rev-parse", "HEAD"])
            .unwrap()
            .trim()
            .to_string();
        assert_eq!(started_at, trunk_tip, "must start from master, not feature");
    }

    #[test]
    fn an_explicit_base_is_honoured() {
        let (d, root) = repo_on("master");
        git(&root, &["checkout", "-q", "-b", "feature"]).unwrap();
        git(
            &root,
            &["commit", "-q", "--allow-empty", "-m", "feature work"],
        )
        .unwrap();
        let tip = git(&root, &["rev-parse", "feature"])
            .unwrap()
            .trim()
            .to_string();
        git(&root, &["checkout", "-q", "master"]).unwrap();

        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "feature").unwrap();
        assert_eq!(
            git(&s.worktree, &["rev-parse", "HEAD"]).unwrap().trim(),
            tip
        );
    }

    /// Resuming must never move a branch that already holds work — rebasing an
    /// agent's unreviewed commits out from under it would be unrecoverable.
    #[test]
    fn resuming_never_moves_an_existing_branch() {
        let (d, root) = repo_on("master");
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "master").unwrap();
        std::fs::write(s.worktree.join("work.txt"), "agent output").unwrap();
        git(&s.worktree, &["add", "-A"]).unwrap();
        git(&s.worktree, &["commit", "-q", "-m", "agent work"]).unwrap();
        let agent_tip = git(&root, &["rev-parse", s.branch.as_deref().unwrap()])
            .unwrap()
            .trim()
            .to_string();

        git(
            &root,
            &["commit", "-q", "--allow-empty", "-m", "trunk moved on"],
        )
        .unwrap();
        s.remove(&root, "master").unwrap();
        s.ensure(&root, "master").unwrap();

        assert_eq!(
            git(&root, &["rev-parse", s.branch.as_deref().unwrap()])
                .unwrap()
                .trim(),
            agent_tip,
            "the agent's commit must survive"
        );
    }

    #[test]
    fn a_session_reports_how_far_behind_it_has_drifted() {
        let (d, root) = repo_on("master");
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "master").unwrap();
        assert_eq!(s.behind(&root, "master"), 0);

        for m in ["one", "two"] {
            git(&root, &["commit", "-q", "--allow-empty", "-m", m]).unwrap();
        }
        assert_eq!(s.behind(&root, "master"), 2);
    }

    // ── choosing a session ──────────────────────────────────────────────────

    fn worktrees(ids: &[&str]) -> (tempfile::TempDir, PathBuf) {
        let d = tempfile::tempdir().unwrap();
        let wt = d.path().join("wt");
        std::fs::create_dir_all(&wt).unwrap();
        for id in ids {
            std::fs::create_dir_all(wt.join(id)).unwrap();
        }
        (d, wt)
    }

    #[test]
    fn there_is_no_current_session_before_any_exist() {
        let (_d, wt) = worktrees(&[]);
        assert_eq!(current(&wt), None);
    }

    #[test]
    fn the_current_session_is_the_most_recent() {
        let (_d, wt) = worktrees(&["s01", "s02", "s03"]);
        assert_eq!(current(&wt).as_deref(), Some("s03"));
    }

    /// Regression: every bare launch called `next_id`, so `omh claude` twice
    /// produced two sessions and you could never reattach to the agent you left
    /// running — which makes dtach persistence pointless.
    #[test]
    fn a_bare_launch_resumes_rather_than_multiplying_sessions() {
        let (_d, wt) = worktrees(&["s01"]);
        assert_eq!(pick(&wt, None, false), "s01");
    }

    #[test]
    fn the_first_launch_creates_the_first_session() {
        let (_d, wt) = worktrees(&[]);
        assert_eq!(pick(&wt, None, false), "s01");
    }

    #[test]
    fn a_new_session_is_something_you_ask_for() {
        let (_d, wt) = worktrees(&["s01", "s02"]);
        assert_eq!(pick(&wt, None, true), "s03");
    }

    #[test]
    fn an_explicit_id_always_wins() {
        let (_d, wt) = worktrees(&["s01", "s02"]);
        assert_eq!(pick(&wt, Some("s01"), false), "s01");
        assert_eq!(pick(&wt, Some("s09"), true), "s09", "explicit beats --new");
    }

    /// Regression: git can lose a worktree's registration while the directory
    /// survives (a prune that raced, an admin dir removed by hand). `worktree
    /// remove` then refuses with "is not a working tree" and the session can
    /// never be removed — the mirror of the missing-directory case.
    #[test]
    fn a_worktree_git_has_forgotten_can_still_be_removed() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();

        // Commit first, so this still exercises the branch-survives path in
        // the degraded case rather than the drop-an-empty-branch path.
        std::fs::write(s.worktree.join("w.txt"), "x").unwrap();
        git(&s.worktree, &["add", "-A"]).unwrap();
        git(&s.worktree, &["commit", "-q", "-m", "agent work"]).unwrap();

        // git forgets, the directory stays
        std::fs::remove_dir_all(root.join(".git/worktrees")).unwrap();
        assert!(s.worktree.exists());

        s.remove(&root, "main")
            .expect("must clean up what is actually there");
        assert!(!s.worktree.exists(), "the directory must be gone");
        assert!(s.branch_exists(&root), "and the branch still kept");
    }

    #[test]
    fn removing_a_session_that_was_never_created_is_not_an_error() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s09".into());
        s.remove(&root, "main")
            .expect("nothing to do is not a failure");
    }

    // ── session ids are path components ─────────────────────────────────────

    #[test]
    fn ordinary_session_ids_are_accepted() {
        for id in ["s01", "doctor", "auth", "my-session"] {
            validate_id(id).unwrap_or_else(|e| panic!("{id}: {e}"));
        }
    }

    /// `-s` is user input and `remove` deletes the directory it names.
    #[test]
    fn a_session_id_cannot_escape_the_worktree_directory() {
        for id in ["..", "../..", "a/b", "/etc", ""] {
            assert!(validate_id(id).is_err(), "`{id}` must be rejected");
        }
    }

    // ── scratch sessions ────────────────────────────────────────────────────

    /// Regression: `omh auth` and `omh doctor` each left an `omh/auth` and
    /// `omh/doctor` branch behind, because `rm` keeps branches by design —
    /// a rule that is right for your work and wrong for a login.
    #[test]
    fn a_scratch_session_creates_no_branch() {
        let (d, root) = repo();
        let s = Session::scratch(d.path().join("scratch/auth"), "auth".into());
        s.ensure(&root, "main").unwrap();

        assert!(s.worktree.is_dir(), "it still needs a writable /work");
        assert_eq!(
            git(&root, &["branch", "--list", "omh/auth"])
                .unwrap()
                .trim(),
            "",
            "no branch may be created"
        );
    }

    #[test]
    fn removing_a_scratch_session_leaves_nothing_behind() {
        let (d, root) = repo();
        let s = Session::scratch(d.path().join("scratch/doctor"), "doctor".into());
        s.ensure(&root, "main").unwrap();
        s.remove(&root, "main").unwrap();

        assert!(!s.worktree.exists());
        assert_eq!(
            git(&root, &["branch", "--list", "omh/*"]).unwrap().trim(),
            ""
        );
    }

    /// A scratch directory must not live among the worktrees, or `omh s ls`
    /// lists a login as if it were a session you could resume.
    #[test]
    fn scratch_sessions_are_not_listed_as_sessions() {
        let (d, root) = repo();
        let wt = d.path().join("wt");
        Session::new(&wt, "s01".into())
            .ensure(&root, "main")
            .unwrap();
        Session::scratch(d.path().join("scratch/auth"), "auth".into())
            .ensure(&root, "main")
            .unwrap();

        assert_eq!(list(&wt), ["s01"]);
    }

    #[test]
    fn a_real_session_still_gets_its_branch() {
        let (d, root) = repo();
        let s = Session::new(&d.path().join("wt"), "s01".into());
        s.ensure(&root, "main").unwrap();
        assert_eq!(s.branch.as_deref(), Some("omh/s01"));
        assert!(s.branch_exists(&root));
    }
}