trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
//! Unit tests for the in-project spawn path (#1706, #1803, #1805, #1807).
//!
//! Why: split out of `inproject.rs` so the production module stays under the
//! 500-SLOC cap; the tests themselves are unchanged. Coverage: repos-root
//! resolution + `TRUSTY_MPM_REPOS_ROOT` precedence, old-layout migration
//! (`ensure_base_clone` + `migrate_old_layout_aside`), per-session worktree
//! creation, and `.git/info/exclude` idempotency.
//! What: pure-function + real-temp-repo assertions over the module's public
//! and private surface (reachable via `use super::*`).
//!
//! #7497: every fixture here builds a worktree to exercise something ELSE —
//! naming, sentinels, branch tracking — so it calls
//! [`super::create_session_worktree_unchecked`], which skips the
//! `disk.max_usage_pct` gate. That opt-out is deliberate and spelled at the
//! call site: a fixture must not be judged by how full the developer's volume
//! is, and the gate itself is covered by `tests/worktree_disk_usage_gate.rs`
//! against pinned measurements.
//! Test: this IS the test module.

use super::*;

/// #1807: `tm launch` and the daemon in-project path must resolve the managed
/// repo root through the SAME function so a lone `TRUSTY_MPM_REPOS_ROOT` cannot
/// send them to different roots.
///
/// Why: before the fix, the daemon path used `base_clone_path` (which honours
/// `TRUSTY_MPM_REPOS_ROOT`) while `tm launch` used `workspace_subpath` (which
/// does NOT), so setting only `TRUSTY_MPM_REPOS_ROOT` re-diverged the roots.
/// This locks in that BOTH entry points now call `base_clone_path`, and proves
/// the old `workspace_subpath` path really did diverge (guarding against a
/// regression that reverts `tm launch` to it).
/// Test: this function IS the test.
#[test]
fn launch_and_daemon_agree_on_repos_root_env() {
    let _g = crate::core::trusty_tools_config::env_test_lock();

    // The #1807 scenario: ONLY TRUSTY_MPM_REPOS_ROOT is set (no WORKSPACE_ROOT).
    // SAFETY: guarded by the crate-wide env_test_lock; both vars restored below.
    unsafe {
        std::env::set_var(REPOS_ROOT_ENV, "/explicit/repos/root");
        std::env::remove_var(crate::core::trusty_tools_config::WORKSPACE_ROOT_ENV);
    }

    // Daemon in-project path AND (post-fix) `tm launch` both resolve via this.
    let unified = base_clone_path("owner", "repo");

    // The PRE-fix `tm launch` path resolved via workspace_subpath → workspace_root,
    // which ignores TRUSTY_MPM_REPOS_ROOT.
    let cfg = crate::core::trusty_tools_config::TrustyToolsConfig::load();
    let gh = trusty_common::github_path::GithubPath {
        owner: "owner".into(),
        repo: "repo".into(),
    };
    let pre_fix_launch = crate::core::trusty_tools_config::workspace_subpath(&cfg, &gh);

    // SAFETY: guarded by env_test_lock.
    unsafe { std::env::remove_var(REPOS_ROOT_ENV) };

    assert_eq!(
        unified,
        PathBuf::from("/explicit/repos/root/owner/repo"),
        "the unified resolver (used by BOTH entry points) must honour \
             TRUSTY_MPM_REPOS_ROOT"
    );
    assert_ne!(
        unified, pre_fix_launch,
        "the pre-#1807 tm launch path (workspace_subpath) diverged from the \
             daemon root; tm launch must now use base_clone_path instead"
    );
}

/// #1805: `ensure_base_clone` must migrate a pre-existing old-layout dir aside
/// (non-empty, no top-level `.git`) and then successfully clone the fresh base,
/// instead of failing and silently falling back to full-clone-per-session.
///
/// Why: this is the exact scenario observed on `bobmatnyc/trusty-tools` — 37
/// stale UUID full-clone subdirs with no top-level `.git`. Cloning into that
/// non-empty dir fails, so the new `.worktrees/` layout never engaged.
/// Non-tautology proof: the backup-path prefix is derived from the PUBLIC
/// constant `OLD_LAYOUT_BACKUP_SUFFIX`, and the assertions check both that the
/// OLD marker survived in the backup AND that a NEW `.git` now exists at the
/// base — a silent-fallback (no migration) would leave the marker at the base
/// and no `.git`, failing both.
/// Test: this function IS the test.
#[test]
fn ensure_base_clone_migrates_old_layout_dir_aside() {
    // 1. Build a real source repo to clone from.
    let src = crate::test_support::hermetic_temp_dir();
    let src_path = src.path();
    let init = std::process::Command::new("git")
        .args(["init", src_path.to_str().expect("src utf8")])
        .output()
        .expect("git init src");
    assert!(init.status.success(), "git init src failed");
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", src_path.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(src_path.join("README"), b"src").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", src_path.to_str().expect("utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args([
            "-C",
            src_path.to_str().expect("utf8"),
            "commit",
            "-m",
            "init",
        ])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    // 2. Build an OLD-LAYOUT base dir: <parent>/owner/repo/ containing a fake
    //    per-session UUID full-clone subdir and NO top-level `.git`.
    let parent = crate::test_support::hermetic_temp_dir();
    let base = parent.path().join("owner").join("repo");
    let old_session = base.join("00000000-old-session-uuid");
    std::fs::create_dir_all(&old_session).expect("create old-layout subdir");
    std::fs::write(old_session.join("MARKER"), b"legacy").expect("write marker");
    assert!(
        !base.join(".git").exists(),
        "precondition: no top-level .git"
    );

    // 3. ensure_base_clone must migrate the old dir aside and clone fresh.
    let url = src_path.to_str().expect("src url utf8");
    ensure_base_clone(url, &base, None).expect("ensure_base_clone must migrate + clone");

    // 4. The base now holds a FRESH clone (top-level `.git` present).
    assert!(
        base.join(".git").exists(),
        "fresh shared-base clone must exist at the base path after migration"
    );

    // 5. A sibling backup dir carrying the documented suffix must exist and
    //    still contain the OLD marker (data preserved, not deleted).
    let repo_parent = base.parent().expect("base has parent");
    let backup = std::fs::read_dir(repo_parent)
        .expect("read owner dir")
        .filter_map(Result::ok)
        .map(|e| e.path())
        .find(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.contains(OLD_LAYOUT_BACKUP_SUFFIX))
                .unwrap_or(false)
        })
        .expect("a migrated backup dir must exist");
    assert!(
        backup
            .join("00000000-old-session-uuid")
            .join("MARKER")
            .exists(),
        "the old per-session data must be preserved under the backup dir"
    );
}

/// #1805: the migrator must be a no-op for the cases that are NOT old-layout —
/// an empty base dir and a dir that already contains `.git`.
///
/// Why: git clone succeeds into an empty/absent dir, and an existing `.git` is
/// the reuse path handled by the caller; migrating either would be destructive
/// and wrong. This guards the precise old-layout signature.
/// Test: this function IS the test.
#[test]
fn migrate_old_layout_aside_ignores_empty_and_git_dirs() {
    // Empty dir → Ok(None), dir untouched.
    let empty = crate::test_support::hermetic_temp_dir();
    let empty_base = empty.path().join("owner").join("repo");
    std::fs::create_dir_all(&empty_base).expect("create empty base");
    assert!(
        migrate_old_layout_aside(&empty_base)
            .expect("empty dir must not error")
            .is_none(),
        "an empty base dir must not be migrated"
    );
    assert!(empty_base.is_dir(), "empty base dir must remain in place");

    // Dir with a top-level `.git` → Ok(None), dir untouched.
    let git = crate::test_support::hermetic_temp_dir();
    let git_base = git.path().join("owner").join("repo");
    std::fs::create_dir_all(git_base.join(".git")).expect("create .git");
    std::fs::write(git_base.join("file"), b"x").expect("write file");
    assert!(
        migrate_old_layout_aside(&git_base)
            .expect("git dir must not error")
            .is_none(),
        "a dir with a top-level .git must not be migrated"
    );
    assert!(
        git_base.join(".git").is_dir(),
        ".git dir must remain in place"
    );

    // Absent path → Ok(None).
    let absent = git.path().join("does").join("not").join("exist");
    assert!(
        migrate_old_layout_aside(&absent)
            .expect("absent path must not error")
            .is_none(),
        "an absent path must not be migrated"
    );
}

/// #4270: a project directory holding a legacy `.base` store must be refused,
/// never renamed aside.
///
/// Why: `.base` matches the old-layout signature exactly — non-empty, no
/// top-level `.git` — but it is a real bare repository owning every
/// `.base/.worktrees/<id>` worktree beneath it, any of which may belong to a
/// live session. Renaming the parent orphans all of them at once. This is the
/// same failure #3605 caused one level down, and the owner ruling makes `.base`
/// cleanup a manual step, so the correct behaviour is a loud refusal that moves
/// nothing.
/// What: pre-seeds `<base>/.base/.worktrees/live/IN-USE.txt`, calls
/// `migrate_old_layout_aside`, and asserts it returns `Err` naming `.base` while
/// the marker file survives byte-for-byte and no backup sibling was created.
/// Test: this function IS the test.
#[test]
fn migrate_old_layout_aside_refuses_a_dir_holding_a_dot_base_store() {
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path().join("owner").join("repo");
    let live = base.join(".base").join(".worktrees").join("live");
    std::fs::create_dir_all(&live).expect("create legacy worktree");
    let marker = live.join("IN-USE.txt");
    std::fs::write(&marker, b"live session").expect("write marker");

    let err = migrate_old_layout_aside(&base)
        .expect_err("a dir holding a .base store must be refused, not migrated");
    assert!(
        err.contains(".base"),
        "the refusal must name the legacy store, got: {err}"
    );

    assert!(
        base.is_dir(),
        "the project dir must stay exactly where it is"
    );
    assert_eq!(
        std::fs::read(&marker).expect("the legacy worktree must survive untouched"),
        b"live session",
        "#4270: an existing .base worktree must not be disturbed, relocated, or deleted"
    );
    let siblings: Vec<_> = std::fs::read_dir(base.parent().unwrap())
        .expect("read owner dir")
        .filter_map(|e| e.ok().map(|e| e.file_name()))
        .collect();
    assert_eq!(
        siblings.len(),
        1,
        "no backup sibling may be created, got {siblings:?}"
    );
}

/// #4270: a project directory holding live worktrees must be refused too, not
/// just one holding `.base`.
///
/// Why: the first round of this fix guarded `.base` and left `.worktrees`
/// open — the same hole one name over. A project directory whose `.git` is
/// absent OR merely unreadable still matches the old-layout signature, so it
/// gets renamed whole, orphaning every session worktree beneath it. The guard
/// has to key on the class, not on one member of it.
/// What: pre-seeds `<base>/.worktrees/sess-1/IN-USE.txt` with no `.git` at all,
/// calls `migrate_old_layout_aside`, and asserts it returns `Err` naming
/// `.worktrees` while the marker survives and no backup sibling appears.
/// Test: this function IS the test.
#[test]
fn migrate_old_layout_aside_refuses_a_dir_holding_live_worktrees() {
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path().join("owner").join("repo");
    let live = base.join(".worktrees").join("sess-1");
    std::fs::create_dir_all(&live).expect("create live worktree");
    let marker = live.join("IN-USE.txt");
    std::fs::write(&marker, b"live session").expect("write marker");

    let err = migrate_old_layout_aside(&base)
        .expect_err("a dir holding live worktrees must be refused, not migrated");
    assert!(
        err.contains(".worktrees"),
        "the refusal must name what it found, got: {err}"
    );

    assert!(
        base.is_dir(),
        "the project dir must stay exactly where it is"
    );
    assert_eq!(
        std::fs::read(&marker).expect("the live worktree must survive untouched"),
        b"live session",
        "#4270: a live session worktree must not be disturbed, relocated, or deleted"
    );
    let siblings: Vec<_> = std::fs::read_dir(base.parent().unwrap())
        .expect("read owner dir")
        .filter_map(|e| e.ok().map(|e| e.file_name()))
        .collect();
    assert_eq!(
        siblings.len(),
        1,
        "no backup sibling may be created, got {siblings:?}"
    );
}

#[test]
fn try_inproject_spawn_returns_none_for_non_git_path() {
    // A directory that is not a git repo must return Ok(None), not an error.
    let tmp = std::env::temp_dir();
    let result = try_inproject_spawn(&tmp);
    assert!(
        matches!(result, Ok(None)),
        "non-git path should yield Ok(None), got {result:?}"
    );
}

#[test]
fn get_origin_url_returns_none_for_non_git() {
    // A non-git directory is an ANSWER, not a failure: git-config exits 1 for a
    // key it cannot find, and #4734 maps exactly that code to Ok(None).
    let tmp = std::env::temp_dir();
    let result = get_origin_url(&tmp);
    assert!(
        matches!(result, Ok(None)),
        "non-git dir must be Ok(None), got {result:?}"
    );
}

/// A repo with no `origin` remote is `Ok(None)` — the fall-through by design.
///
/// Why: #4734 splits git failures out of this function's `None`, and the split
/// is only correct if the legitimate no-remote case stays on the `Ok` side. If
/// it drifted to `Err`, every fall-through caller (`try_inproject_spawn`,
/// `spawn_managed_local`, `tm launch`) would start failing repos that are
/// merely un-remoted.
/// What: `git init`s a repo, adds no remote, asserts `Ok(None)`.
/// Test: this function IS the test.
#[test]
fn get_origin_url_returns_none_for_repo_without_origin() {
    let tmp = tempfile::TempDir::new().expect("temp dir");
    let init = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(tmp.path())
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");

    let result = get_origin_url(tmp.path());
    assert!(
        matches!(result, Ok(None)),
        "repo without origin must be Ok(None), got {result:?}"
    );
}

/// A remote with SEVERAL urls still resolves — it must not become an error.
///
/// Why: the one working configuration that could plausibly be broken by #4734's
/// exit-code split. `remote.<name>.url` is legitimately multi-valued (the
/// push-to-several-remotes setup), and if `git config --get` answered a
/// multi-valued key with a nonzero code, this function would newly refuse to
/// spawn for a repo that works fine. It does not — git returns the last value
/// with exit 0 — and this test is what keeps that assumption checked rather
/// than assumed.
/// What: adds a second `url` to `origin` and asserts `Ok(Some(_))`.
/// Test: this function IS the test.
#[test]
fn get_origin_url_handles_a_multi_valued_origin() {
    let tmp = tempfile::TempDir::new().expect("temp dir");
    let init = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(tmp.path())
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");
    let git = |args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(tmp.path())
            .args(args)
            .output()
            .expect("spawn git");
        assert!(out.status.success(), "git {args:?} failed");
    };
    git(&[
        "remote",
        "add",
        "origin",
        "https://github.com/acme/widget.git",
    ]);
    git(&[
        "remote",
        "set-url",
        "--add",
        "origin",
        "https://gitlab.com/acme/widget.git",
    ]);

    let result = get_origin_url(tmp.path());
    assert!(
        matches!(result, Ok(Some(_))),
        "a multi-valued origin must still resolve, got {result:?}"
    );
}

/// An unreadable `.git` DIRECTORY is `Err`, though git itself exits 1 (#4734).
///
/// Why: the exit-code split alone does not catch this. Discovery walks straight
/// past a `.git` it cannot open, finds no repo above, reads global config, and
/// reports the key missing — **exit 1, empty stderr**, identical to a repo with
/// no `origin`. That is the same misdiagnosis this ticket removes for exit 128,
/// arriving through a different filesystem fault, and no stderr matching could
/// separate them because there is no stderr. `ensure_repo_rooted_at` is what
/// catches it.
/// What: `git init`s a repo, chmods `.git` to 000, asserts `Err`. The
/// permissions are restored before the assertion so a failure does not leave an
/// undeletable temp dir behind.
/// Test: this function IS the test.
#[test]
fn get_origin_url_errors_when_the_git_dir_is_unreadable() {
    let tmp = tempfile::TempDir::new().expect("temp dir");
    let init = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(tmp.path())
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");

    let git_dir = tmp.path().join(".git");
    std::fs::set_permissions(
        &git_dir,
        std::os::unix::fs::PermissionsExt::from_mode(0o000),
    )
    .expect("chmod 000");
    let result = get_origin_url(tmp.path());
    std::fs::set_permissions(
        &git_dir,
        std::os::unix::fs::PermissionsExt::from_mode(0o755),
    )
    .expect("restore perms");

    assert!(
        result.is_err(),
        "an unreadable .git must be Err — git answers exit 1 here, which is \
         indistinguishable from 'no origin remote': {result:?}"
    );
}

/// Discovery escaping to a PARENT repo is `Err`, not that repo's remote (#4734).
///
/// Why: the worst shape of the same fault. When the unreadable `.git` sits
/// inside another git repo, discovery walks up and answers **exit 0 with the
/// parent's origin** — so the daemon would resolve the wrong `owner/repo` and
/// provision a managed clone of a different repository. Pre-existing, and not
/// something the exit-code split addresses; `ensure_repo_rooted_at` closes it
/// because it asks git which repository it actually read.
/// What: nests a child repo inside a parent with a DIFFERENT origin, makes the
/// child's `.git` unreadable, and asserts `Err` rather than the parent's URL.
/// Test: this function IS the test.
#[test]
fn get_origin_url_errors_when_discovery_escapes_to_a_parent_repo() {
    let tmp = tempfile::TempDir::new().expect("temp dir");
    let parent = tmp.path().join("parent");
    let child = parent.join("child");
    for (dir, origin) in [
        (&parent, "https://github.com/PARENT/parentrepo.git"),
        (&child, "https://github.com/CHILD/childrepo.git"),
    ] {
        std::fs::create_dir_all(dir).expect("mkdir");
        let init = std::process::Command::new("git")
            .args(["init", "-q"])
            .arg(dir)
            .output()
            .expect("git init");
        assert!(init.status.success(), "git init failed");
        let remote = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(["remote", "add", "origin", origin])
            .output()
            .expect("git remote add");
        assert!(remote.status.success(), "git remote add failed");
    }

    let child_git = child.join(".git");
    std::fs::set_permissions(
        &child_git,
        std::os::unix::fs::PermissionsExt::from_mode(0o000),
    )
    .expect("chmod 000");
    let result = get_origin_url(&child);
    std::fs::set_permissions(
        &child_git,
        std::os::unix::fs::PermissionsExt::from_mode(0o755),
    )
    .expect("restore perms");

    assert!(
        result.is_err(),
        "must refuse rather than answer with the PARENT repo's origin: {result:?}"
    );
    if let Err(msg) = &result {
        assert!(
            !msg.contains("parentrepo"),
            "the error must not hand back the wrong repo's URL: {msg}"
        );
    }
}

/// A linked worktree resolves normally — the rooted-at guard must not break it.
///
/// Why: `ensure_repo_rooted_at` compares git's `--show-toplevel` against
/// `path`, and a linked worktree's `.git` is a FILE pointing at a git dir under
/// the MAIN checkout. Comparing git dirs instead of toplevels would reject
/// every worktree tm creates, so this is the test that keeps that choice
/// honest.
/// What: builds a repo with an origin, adds a detached worktree, and asserts
/// the worktree reports the same origin.
/// Test: this function IS the test.
#[test]
fn get_origin_url_reads_a_linked_worktree() {
    let tmp = tempfile::TempDir::new().expect("temp dir");
    let main = tmp.path().join("main");
    std::fs::create_dir_all(&main).expect("mkdir");
    let git = |dir: &std::path::Path, args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .expect("spawn git");
        assert!(out.status.success(), "git {args:?} failed");
    };
    let init = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(&main)
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");
    git(
        &main,
        &[
            "remote",
            "add",
            "origin",
            "https://github.com/acme/widget.git",
        ],
    );
    git(&main, &["config", "user.email", "test@example.com"]);
    git(&main, &["config", "user.name", "Test"]);
    std::fs::write(main.join("f.txt"), "v1\n").expect("write");
    git(&main, &["add", "."]);
    git(&main, &["commit", "-q", "-m", "initial"]);

    let linked = tmp.path().join("linked");
    git(
        &main,
        &[
            "worktree",
            "add",
            "-q",
            "--detach",
            linked.to_str().expect("utf8"),
        ],
    );
    assert!(
        linked.join(".git").is_file(),
        "fixture: .git must be a file"
    );

    let result = get_origin_url(&linked);
    assert_eq!(
        result.as_ref().map(|o| o.as_deref()),
        Ok(Some("https://github.com/acme/widget.git")),
        "a linked worktree must resolve its repo's origin, got {result:?}"
    );
}

/// A git invocation that fails outright is `Err`, never `Ok(None)` (#4734).
///
/// Why: this is the fail-open the ticket is about. `try_inproject_spawn` reads
/// `Ok(None)` as "no GitHub remote here", so a config git refuses to parse used
/// to be reported to the operator as a repo without a remote — sending them to
/// `tm connect` to fix a checkout that is fine.
/// What: `git init`s a real repo (so `.git` genuinely exists), then overwrites
/// `.git/config` with a line git cannot parse. `git config --get` answers that
/// with exit 128, which must surface as `Err`.
/// Test: this function IS the test.
#[test]
fn get_origin_url_errors_when_git_config_is_unreadable() {
    let tmp = tempfile::TempDir::new().expect("temp dir");
    let init = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(tmp.path())
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");

    // An unterminated section header — `fatal: bad config line 1`, exit 128.
    std::fs::write(tmp.path().join(".git/config"), "[remote \"origin\"\n")
        .expect("write broken config");

    let result = get_origin_url(tmp.path());
    assert!(
        result.is_err(),
        "an unreadable git config must be Err, not a silent Ok(None): {result:?}"
    );
}

#[test]
fn repos_root_default_ends_with_canonical_segment() {
    // Without env overrides, repos_root() must resolve to ~/trusty-mpm-projects
    // (the canonical base — same root as workspace_root()).
    // Skip when env is overridden so CI with custom roots doesn't false-fail.
    if std::env::var(REPOS_ROOT_ENV).is_ok()
        || std::env::var(crate::core::trusty_tools_config::WORKSPACE_ROOT_ENV).is_ok()
    {
        return;
    }
    let root = repos_root();
    assert!(
        root.ends_with(DEFAULT_REPOS_DIR),
        "repos_root() default must end with '{DEFAULT_REPOS_DIR}', got {}",
        root.display()
    );
}

#[test]
fn base_clone_path_resolves_to_canonical_root() {
    // Without env overrides, base_clone_path must return
    // ~/trusty-mpm-projects/<owner>/<repo> (#1803).
    if std::env::var(REPOS_ROOT_ENV).is_ok()
        || std::env::var(crate::core::trusty_tools_config::WORKSPACE_ROOT_ENV).is_ok()
    {
        return;
    }
    let base = base_clone_path("myorg", "myrepo");
    assert!(
        base.ends_with("trusty-mpm-projects/myorg/myrepo"),
        "base_clone_path must resolve to …/trusty-mpm-projects/myorg/myrepo, got {}",
        base.display()
    );
}

/// Why (#5204): `worktree_path_for` is the CREATION site — the one place that
/// decides where a new worktree lands. Before this change it joined the
/// `".worktrees"` literal, so a configured base was honoured nowhere and
/// creation silently disagreed with every detection site. This pins that it now
/// builds its path from the resolved base.
/// What: with `TRUSTY_MPM_WORKTREES_DIRNAME` set, the returned path nests under
/// the CONFIGURED segment and no longer under `.worktrees`; with it cleared, the
/// default is unchanged.
///
/// Non-tautology proof: both expectations are spelled out as literals here
/// (`base/.sessions/<name>` and `base/.worktrees/<name>`), not derived from the
/// production resolver. A `worktree_path_for` that ignored config would produce
/// `base/.worktrees/<name>` in the first case and fail the inequality.
/// Test: itself.
#[test]
fn worktree_path_for_honours_configured_base() {
    let _g = crate::core::trusty_tools_config::env_test_lock();
    let base = std::path::Path::new("/tmp/some-checkout");

    // SAFETY: serialised by the crate-wide env lock; cleared below.
    unsafe { std::env::set_var("TRUSTY_MPM_WORKTREES_DIRNAME", ".sessions") };
    let configured = super::worktree_path_for(base, "tm-widget-01");
    // SAFETY: as above.
    unsafe { std::env::remove_var("TRUSTY_MPM_WORKTREES_DIRNAME") };
    let defaulted = super::worktree_path_for(base, "tm-widget-01");

    assert_eq!(
        configured,
        std::path::PathBuf::from("/tmp/some-checkout/.sessions/tm-widget-01"),
        "creation must nest under the configured base"
    );
    assert!(
        !configured.starts_with("/tmp/some-checkout/.worktrees"),
        "a configured base must actually replace `.worktrees`, got {}",
        configured.display()
    );
    assert_eq!(
        defaulted,
        std::path::PathBuf::from("/tmp/some-checkout/.worktrees/tm-widget-01"),
        "with nothing configured the default must be unchanged"
    );
}

#[test]
fn session_worktree_path_uses_dot_prefix() {
    // See #4162: env-var reader must hold the same lock as the setter
    let _g = crate::core::trusty_tools_config::env_test_lock();
    // create_session_worktree must place the worktree at
    // <base>/.worktrees/<worktree_name> (dot-prefixed) so it is gitignored via
    // .git/info/exclude (#1803). Since #2032 `worktree_name` is the resolved
    // SEMANTIC tmux name (e.g. `tm-trusty-tools-01`), not a raw session UUID.
    // We call the PRODUCTION function against a real temporary git repository
    // (with an initial commit so `git worktree add` can branch from HEAD) and
    // assert: (a) path is under <base>/.worktrees/, (b) ends with the name,
    // (c) the directory actually exists after the call.
    //
    // Non-tautology proof: `expected_parent` is hardcoded as `base.join(".worktrees")`
    // — NOT derived from production code. If `create_session_worktree` changed
    // to `base_path.join("worktrees").join(...)` the `starts_with` assertion
    // would fail because `base/worktrees/<name>` does NOT start with `base/.worktrees`.
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path();

    // Initialise a real git repo so `git worktree add` can run.
    let init = std::process::Command::new("git")
        .args(["init", base.to_str().expect("base is utf8")])
        .output()
        .expect("git init");
    assert!(
        init.status.success(),
        "git init failed: {}",
        String::from_utf8_lossy(&init.stderr)
    );

    // Configure identity (required for `git commit`).
    for (k, v) in [("user.email", "test@example.com"), ("user.name", "Test")] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("base is utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }

    // Create an initial commit so HEAD exists and `git worktree add -b` works.
    std::fs::write(base.join("README"), b"init").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("base is utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args([
            "-C",
            base.to_str().expect("base is utf8"),
            "commit",
            "-m",
            "init",
        ])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    // Call the production function.
    let name = "tm-test-repo-01";
    let worktree_path = create_session_worktree_unchecked(
        base,
        name,
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed on a real git repo");

    // (a) Path must be under <base>/.worktrees/ — hardcoded, not from production.
    let expected_parent = base.join(".worktrees");
    assert!(
        worktree_path.starts_with(&expected_parent),
        "worktree must be under <base>/.worktrees/, got {}",
        worktree_path.display()
    );

    // (b) Path must end with the semantic worktree name.
    assert!(
        worktree_path.ends_with(name),
        "worktree path must end with worktree name {name}, got {}",
        worktree_path.display()
    );

    // (c) The directory must actually exist (git worktree was created on disk).
    assert!(
        worktree_path.is_dir(),
        "worktree directory must exist on disk, got {}",
        worktree_path.display()
    );
}

/// Issue #2032: a worktree directory OR branch that already exists for a
/// candidate name must be detected by [`worktree_name_collides`] so
/// `SessionManager::resolve_session_name`'s extra-collision predicate steers
/// away from it instead of `create_session_worktree` silently clobbering (or
/// confusingly erroring on) it.
///
/// Why: the tmux-liveness check alone cannot see git worktrees/branches — a
/// stale worktree left behind by a hand-deleted-but-not-decommissioned
/// session must still be treated as a collision.
/// What: (a) an absent name must not collide; (b) after creating a worktree
/// for a name, THAT SAME name must collide (both the dir and the branch
/// exist); (c) a name whose branch exists but whose worktree dir was manually
/// removed must still collide (branch-only check).
/// Test: this function IS the test.
#[test]
fn worktree_name_collides_detects_existing_dir_and_branch() {
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path();

    let init = std::process::Command::new("git")
        .args(["init", base.to_str().expect("base is utf8")])
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");
    for (k, v) in [("user.email", "test@example.com"), ("user.name", "Test")] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(base.join("README"), b"init").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("utf8"), "commit", "-m", "init"])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    // (a) No collision before anything exists.
    assert!(
        !worktree_name_collides(base, "tm-fresh-01"),
        "an unused name must not collide"
    );

    // (b) After creating the worktree, the SAME name must collide.
    create_session_worktree_unchecked(
        base,
        "tm-fresh-01",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree");
    assert!(
        worktree_name_collides(base, "tm-fresh-01"),
        "an in-use name (dir + branch both exist) must collide"
    );

    // (c) Remove the worktree directory (but not the branch) — the branch-only
    // check must still report a collision.
    //
    // #6099: delete the directory directly rather than shelling out to
    // `git worktree remove`. The unit under test, `worktree_name_collides`,
    // reads exactly two things: whether the directory exists, and whether
    // `git rev-parse` resolves the branch ref. It never consults git's
    // worktree ADMIN list under `.git/worktrees/`. Routing this step through
    // `git worktree remove` made the fixture depend on that admin entry
    // surviving, and it does not always: once the entry is gone, `remove`
    // exits 128 with `'<path>' is not a working tree`, which is the panic this
    // test raised about once per six full-suite runs. A probe on git 2.54.0
    // confirms the mapping — deleting the admin entry (or letting a prune
    // delete it after the directory goes missing) reproduces that exact
    // message, while deleting only the directory leaves `remove` succeeding.
    // What removes the entry under load is still unidentified; this fix drops
    // the dependency on it instead of guessing.
    let worktree_dir = base.join(".worktrees").join("tm-fresh-01");
    if worktree_dir.exists() {
        std::fs::remove_dir_all(&worktree_dir).expect("remove the worktree directory");
    }
    // Best-effort, and deliberately not asserted: it only keeps git's admin
    // list consistent with what is on disk, which no assertion below reads.
    // This mirrors `decommission::remove_session_worktree`'s own teardown.
    let _ = std::process::Command::new("git")
        .arg("-C")
        .arg(base)
        .args(["worktree", "prune"])
        .output();
    assert!(
        !worktree_dir.exists(),
        "worktree dir must be gone before the branch-only check"
    );
    assert!(
        worktree_name_collides(base, "tm-fresh-01"),
        "a name whose branch still exists must still collide even after the \
         worktree dir was removed"
    );
}

/// Issue #2032: [`create_session_worktree`] must refuse to clobber an
/// existing worktree directory rather than silently overwriting it.
///
/// Why: `worktree_name_collides` is the PROACTIVE guard used by name
/// resolution; this is the DEFENSIVE guard inside `create_session_worktree`
/// itself, covering a caller that skips the collision check (or a TOCTOU
/// race).
/// What: creates a worktree for a name, then calls `create_session_worktree`
/// again for the SAME name and asserts it returns `Err` (not a panic, not a
/// silent overwrite) and that the original worktree directory is untouched.
/// Test: this function IS the test.
#[test]
fn create_session_worktree_rejects_existing_worktree_dir() {
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path();

    let init = std::process::Command::new("git")
        .args(["init", base.to_str().expect("base is utf8")])
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");
    for (k, v) in [("user.email", "test@example.com"), ("user.name", "Test")] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(base.join("README"), b"init").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("utf8"), "commit", "-m", "init"])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    let first = create_session_worktree_unchecked(
        base,
        "tm-dup-01",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("first create must succeed");
    assert!(first.is_dir(), "first worktree must exist");

    let second = create_session_worktree_unchecked(
        base,
        "tm-dup-01",
        &crate::session_manager::ManagedSessionId::new(),
    );
    assert!(
        second.is_err(),
        "creating a worktree for an already-existing name must error, not clobber"
    );
    assert!(
        first.is_dir(),
        "the original worktree must remain untouched after the rejected re-create"
    );
}

#[test]
fn ensure_worktrees_gitignored_idempotent() {
    // ensure_worktrees_gitignored must write .worktrees/ to .git/info/exclude
    // exactly ONCE even when called multiple times (idempotent) (#1803).
    // #7638: the entry comes from `TRUSTY_MPM_WORKTREES_DIRNAME`, which sibling
    // tests set to `.sessions` under the env lock; hold it so this reads `.worktrees`.
    let _env = crate::core::trusty_tools_config::env_test_lock();
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path();
    // Create a minimal .git dir (not a real git repo, but enough for the function).
    std::fs::create_dir_all(base.join(".git")).expect("create .git");

    // First call: must write the entry.
    ensure_worktrees_gitignored(base).expect("first call must succeed");

    let exclude = base.join(".git").join("info").join("exclude");
    let content1 = std::fs::read_to_string(&exclude).expect("exclude readable");
    let count1 = content1
        .lines()
        .filter(|l| l.trim() == ".worktrees/")
        .count();
    assert_eq!(
        count1, 1,
        "must contain exactly one .worktrees/ entry after first call"
    );

    // Second call: must NOT duplicate the entry.
    ensure_worktrees_gitignored(base).expect("second call must succeed (idempotent)");
    let content2 = std::fs::read_to_string(&exclude).expect("exclude readable");
    let count2 = content2
        .lines()
        .filter(|l| l.trim() == ".worktrees/")
        .count();
    assert_eq!(
        count2, 1,
        "second call must not add a duplicate .worktrees/ entry"
    );
}

/// #1919 regression guard: [`ensure_base_clone`] must emit a `CloningRepo`
/// stage event on the actual first-run clone — the exact "tm: first run for
/// X — cloning into ..." scenario #1904 set out to make observable — and must
/// NOT re-emit it on a subsequent idempotent call against an already-present
/// base clone (the reuse path takes the early `Ok(())` return above the emit
/// site and never runs `git clone` again).
///
/// Why: this is the single most important observable gap #1919 identified —
/// `try_inproject_spawn` (and therefore `ensure_base_clone`) runs from inside
/// `spawn_managed`'s `is_local_workdir` branch, several layers below any
/// `emit(...)` call the clone provisioner already had; before this fix nothing in
/// the in-project path announced the clone stage at all.
/// What: builds a real local source repo (same fixture pattern as
/// `ensure_base_clone_migrates_old_layout_dir_aside`), calls `ensure_base_clone`
/// once inside a fresh `provisioning_stage::scoped` (asserting exactly one
/// `CloningRepo` event, since the base dir does not yet exist), then calls it
/// again inside a SECOND fresh scope against the now-existing base clone
/// (asserting ZERO events, proving the reuse path is silent).
/// Test: this function IS the test.
#[tokio::test]
async fn ensure_base_clone_emits_cloning_repo_only_on_fresh_clone() {
    use crate::core::provisioning_stage::{ProvisioningStage, StageEmitter, scoped};

    // 1. Build a real source repo to clone from (mirrors the fixture used by
    //    `ensure_base_clone_migrates_old_layout_dir_aside` above).
    let src = crate::test_support::hermetic_temp_dir();
    let src_path = src.path();
    let init = std::process::Command::new("git")
        .args(["init", src_path.to_str().expect("src utf8")])
        .output()
        .expect("git init src");
    assert!(init.status.success(), "git init src failed");
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", src_path.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(src_path.join("README"), b"src").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", src_path.to_str().expect("utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args([
            "-C",
            src_path.to_str().expect("utf8"),
            "commit",
            "-m",
            "init",
        ])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    let parent = crate::test_support::hermetic_temp_dir();
    let base = parent.path().join("owner").join("repo");
    let url = src_path.to_str().expect("src url utf8").to_string();

    // 2. Fresh clone: exactly one CloningRepo event.
    let (tx1, mut rx1) = tokio::sync::broadcast::channel(8);
    let emitter1 = StageEmitter::new("s-1", "https://example.com/owner/repo", tx1);
    let base_for_clone = base.clone();
    let url_for_clone = url.clone();
    scoped(emitter1, async move {
        ensure_base_clone(&url_for_clone, &base_for_clone, None)
            .expect("first ensure_base_clone must succeed (fresh clone)");
    })
    .await;

    let mut stages1 = Vec::new();
    while let Ok(value) = rx1.try_recv() {
        stages1.push(value["stage"].as_str().unwrap().to_string());
    }
    assert_eq!(
        stages1,
        vec![ProvisioningStage::CloningRepo.wire_name()],
        "a fresh base clone must emit exactly one CloningRepo stage event"
    );

    // 3. Idempotent reuse: zero events (the base clone already exists).
    let (tx2, mut rx2) = tokio::sync::broadcast::channel(8);
    let emitter2 = StageEmitter::new("s-2", "https://example.com/owner/repo", tx2);
    scoped(emitter2, async move {
        ensure_base_clone(&url, &base, None)
            .expect("second ensure_base_clone must succeed (reuse)");
    })
    .await;

    let mut stages2 = Vec::new();
    while let Ok(value) = rx2.try_recv() {
        stages2.push(value["stage"].as_str().unwrap().to_string());
    }
    assert!(
        stages2.is_empty(),
        "reusing an existing base clone must NOT re-emit CloningRepo, got: {stages2:?}"
    );
}

/// #2189: [`create_session_worktree`] must leave the new session branch with a
/// working `git pull` (upstream tracking `origin/<default>`) WITHOUT letting a
/// bare `git push` target the default branch.
///
/// Why: before this fix the new `session/<name>` branch had no upstream at
/// all, so `git pull` inside a session worktree failed with "There is no
/// tracking information for the current branch." Naively setting the
/// upstream to `origin/<default>` would fix `pull` but ALSO make a bare `git
/// push` try to push session commits onto the shared default branch — this
/// test proves both halves: pull-tracking works AND push is scoped to the
/// worktree's own branch.
/// What: builds a real bare `origin` remote with one commit on `main`, clones
/// it into `base` (mirroring what `ensure_base_clone` produces in
/// production — `origin` wired up, `refs/remotes/origin/HEAD` set), then
/// calls the production `create_session_worktree` and asserts: (a) `git -C
/// <worktree> rev-parse --abbrev-ref --symbolic-full-name @{u}` resolves to
/// `origin/main`; (b) `git -C <worktree> config --worktree push.default` ==
/// `"current"`; (c) `git -C <base> config extensions.worktreeConfig` ==
/// `"true"`.
/// Test: this function IS the test.
#[test]
fn create_session_worktree_sets_pull_upstream_and_worktree_scoped_push() {
    // 1. A real bare `origin` remote, explicitly on `main` so the assertions
    //    below are not at the mercy of the host's `init.defaultBranch`.
    let origin_dir = crate::test_support::hermetic_temp_dir();
    let origin_path = origin_dir.path();
    let init = std::process::Command::new("git")
        .args([
            "init",
            "--bare",
            "-b",
            "main",
            origin_path.to_str().expect("origin utf8"),
        ])
        .output()
        .expect("git init --bare origin");
    assert!(
        init.status.success(),
        "git init --bare origin failed: {}",
        String::from_utf8_lossy(&init.stderr)
    );

    // 2. Seed the bare origin with one commit via a scratch clone (a bare repo
    //    has no working tree to commit into directly).
    let seed = crate::test_support::hermetic_temp_dir();
    let seed_path = seed.path();
    let clone_seed = std::process::Command::new("git")
        .args([
            "clone",
            origin_path.to_str().expect("origin utf8"),
            seed_path.to_str().expect("seed utf8"),
        ])
        .output()
        .expect("git clone seed");
    assert!(
        clone_seed.status.success(),
        "git clone seed failed: {}",
        String::from_utf8_lossy(&clone_seed.stderr)
    );
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", seed_path.to_str().expect("seed utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(seed_path.join("README"), b"seed").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", seed_path.to_str().expect("seed utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args([
            "-C",
            seed_path.to_str().expect("seed utf8"),
            "commit",
            "-m",
            "init",
        ])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");
    let push_seed = std::process::Command::new("git")
        .args([
            "-C",
            seed_path.to_str().expect("seed utf8"),
            "push",
            "origin",
            "main",
        ])
        .status()
        .expect("git push seed");
    assert!(push_seed.success(), "git push seed failed");

    // 3. Clone the now-non-empty bare origin into `base` — this mirrors what
    //    `ensure_base_clone` produces in production: `origin` remote wired up
    //    and `refs/remotes/origin/HEAD` set by the clone itself.
    let base_parent = crate::test_support::hermetic_temp_dir();
    let base = base_parent.path().join("base");
    let clone_base = std::process::Command::new("git")
        .args([
            "clone",
            origin_path.to_str().expect("origin utf8"),
            base.to_str().expect("base utf8"),
        ])
        .output()
        .expect("git clone base");
    assert!(
        clone_base.status.success(),
        "git clone base failed: {}",
        String::from_utf8_lossy(&clone_base.stderr)
    );
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("base utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }

    // 4. Call the production function under test.
    let worktree_path = create_session_worktree_unchecked(
        &base,
        "tm-pull-01",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed");

    // (a) `git pull` must work: @{u} resolves to origin/main.
    let upstream = std::process::Command::new("git")
        .arg("-C")
        .arg(&worktree_path)
        .args(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
        .output()
        .expect("git rev-parse @{u}");
    assert!(
        upstream.status.success(),
        "worktree branch must have an upstream set (git pull must work): {}",
        String::from_utf8_lossy(&upstream.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&upstream.stdout).trim(),
        "origin/main",
        "worktree branch upstream must track origin/main"
    );

    // (b) push.default=current must be scoped to THIS worktree only, so a
    // bare `git push` targets `origin/session/tm-pull-01`, never `main`.
    let push_default = std::process::Command::new("git")
        .arg("-C")
        .arg(&worktree_path)
        .args(["config", "--worktree", "push.default"])
        .output()
        .expect("git config --worktree push.default");
    assert!(
        push_default.status.success(),
        "worktree-scoped push.default must be set: {}",
        String::from_utf8_lossy(&push_default.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&push_default.stdout).trim(),
        "current",
        "push.default must be worktree-scoped to 'current' so push never targets main"
    );

    // (c) extensions.worktreeConfig must be enabled on the base clone —
    // required for the worktree-scoped config in (b) to take effect at all.
    let ext = std::process::Command::new("git")
        .arg("-C")
        .arg(&base)
        .args(["config", "extensions.worktreeConfig"])
        .output()
        .expect("git config extensions.worktreeConfig");
    assert!(
        ext.status.success(),
        "extensions.worktreeConfig must be set on the base clone"
    );
    assert_eq!(
        String::from_utf8_lossy(&ext.stdout).trim(),
        "true",
        "extensions.worktreeConfig must be true"
    );

    // (d) #2867: the foreign upstream is only ever armed behind an EFFECTIVE
    // push pin. Assert the pin as `git push` itself resolves it (full config
    // stack), not merely as a `--worktree`-scoped key.
    let effective = std::process::Command::new("git")
        .arg("-C")
        .arg(&worktree_path)
        .args(["config", "--get", "push.default"])
        .output()
        .expect("git config --get push.default");
    assert_eq!(
        String::from_utf8_lossy(&effective.stdout).trim(),
        "current",
        "the EFFECTIVE push.default (not just the --worktree key) must be `current` \
         whenever a foreign upstream is set (#2867)"
    );
}

/// #2867: [`super::push_is_pinned_to_current`] must report the EFFECTIVE
/// `push.default`, because that — not the exit code of the write that set it —
/// is what decides whether writing a foreign upstream is safe.
///
/// Why: the PR #2863 clobber came from a worktree whose branch tracked a ref it
/// did not own. `configure_session_branch_tracking` may only create that
/// tracking state while a bare `git push` is provably confined to the current
/// branch; if the detector returned `true` optimistically the gate would be
/// decorative.
/// What: builds a real repo, asserts the detector is `false` with no
/// `push.default` set and `false` for a non-`current` value, then enables
/// `extensions.worktreeConfig`, pins `push.default=current` in a linked
/// worktree, and asserts it flips to `true` there while a NON-pinned sibling
/// worktree still reports `false` — proving the detector reads worktree-scoped
/// config rather than the shared repo config.
/// Test: this function IS the test.
#[test]
fn push_pin_detection_matches_effective_config() {
    let repo_dir = crate::test_support::hermetic_temp_dir();
    let repo = repo_dir.path().to_path_buf();
    let git = |args: &[&str], cwd: &std::path::Path| -> bool {
        std::process::Command::new("git")
            .arg("-C")
            .arg(cwd)
            .args(args)
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    };
    if !std::process::Command::new("git")
        .args(["init", "-q", "-b", "main"])
        .arg(&repo)
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
    {
        return; // git unavailable — nothing to assert
    }
    assert!(git(&["config", "user.email", "t@example.com"], &repo));
    assert!(git(&["config", "user.name", "T"], &repo));
    std::fs::write(repo.join("README"), b"seed").expect("write README");
    assert!(git(&["add", "."], &repo));
    assert!(git(&["commit", "-qm", "init"], &repo));

    assert!(
        !super::push_is_pinned_to_current(&repo),
        "an unset push.default must NOT be reported as pinned"
    );
    assert!(git(&["config", "push.default", "simple"], &repo));
    assert!(
        !super::push_is_pinned_to_current(&repo),
        "push.default=simple must NOT be reported as pinned"
    );

    // Two linked worktrees off the same repo: only one gets the pin.
    let wt_parent = crate::test_support::hermetic_temp_dir();
    let pinned = wt_parent.path().join("pinned");
    let unpinned = wt_parent.path().join("unpinned");
    assert!(git(
        &[
            "worktree",
            "add",
            "-q",
            "-b",
            "wt-a",
            pinned.to_str().unwrap()
        ],
        &repo
    ));
    assert!(git(
        &[
            "worktree",
            "add",
            "-q",
            "-b",
            "wt-b",
            unpinned.to_str().unwrap()
        ],
        &repo
    ));
    assert!(git(&["config", "extensions.worktreeConfig", "true"], &repo));
    assert!(git(
        &["config", "--worktree", "push.default", "current"],
        &pinned
    ));

    assert!(
        super::push_is_pinned_to_current(&pinned),
        "a worktree-scoped push.default=current must be reported as pinned"
    );
    assert!(
        !super::push_is_pinned_to_current(&unpinned),
        "a sibling worktree without the pin must NOT be reported as pinned — \
         the detector must read worktree-scoped config, not the shared repo config"
    );
}

// ── #4957: session branches must be cut from origin, not stale local main ──

/// Run a git command in `cwd`, asserting success.
fn g(cwd: &std::path::Path, args: &[&str]) {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(cwd)
        .args(args)
        .output()
        .unwrap_or_else(|e| panic!("git {args:?} failed to spawn: {e}"));
    assert!(
        out.status.success(),
        "git {args:?} in {} failed: {}",
        cwd.display(),
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Read trimmed stdout of a git command in `cwd`, asserting success.
fn g_out(cwd: &std::path::Path, args: &[&str]) -> String {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(cwd)
        .args(args)
        .output()
        .unwrap_or_else(|e| panic!("git {args:?} failed to spawn: {e}"));
    assert!(
        out.status.success(),
        "git {args:?} in {} failed: {}",
        cwd.display(),
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}

/// Add one commit in `cwd` and return its sha.
fn commit(cwd: &std::path::Path, name: &str) -> String {
    std::fs::write(cwd.join(name), name.as_bytes()).expect("write file");
    g(cwd, &["add", "."]);
    g(cwd, &["commit", "-q", "-m", name]);
    g_out(cwd, &["rev-parse", "HEAD"])
}

/// A base clone whose local `main` is DELIBERATELY behind `origin/main`.
///
/// Why: this is the whole point of the #4957 fixture. A test that only checks
/// "a worktree was created" passes against the pre-fix code; only a base whose
/// local ref lags the remote can tell `HEAD` and `origin/main` apart.
/// What: builds a bare `origin` seeded with commit A, clones it into `base`
/// (so `base`'s local `main` AND `refs/remotes/origin/main` both sit at A),
/// then pushes commit B to `origin` from a separate seed clone that `base`
/// never sees. Returns `(base_path, sha_a, sha_b)` plus the TempDir guards
/// that must stay alive for the duration of the test.
struct StaleBase {
    base: std::path::PathBuf,
    origin: std::path::PathBuf,
    sha_a: String,
    sha_b: String,
    _guards: Vec<tempfile::TempDir>,
}

fn stale_base_fixture() -> StaleBase {
    let origin_dir = crate::test_support::hermetic_temp_dir();
    let origin = origin_dir.path().to_path_buf();
    let init = std::process::Command::new("git")
        .args(["init", "--bare", "-q", "-b", "main"])
        .arg(&origin)
        .output()
        .expect("git init --bare");
    assert!(
        init.status.success(),
        "git init --bare failed: {}",
        String::from_utf8_lossy(&init.stderr)
    );

    // Seed clone: the only checkout that ever pushes to `origin`.
    let seed_parent = crate::test_support::hermetic_temp_dir();
    let seed = seed_parent.path().join("seed");
    let clone = std::process::Command::new("git")
        .args(["clone", "-q"])
        .arg(&origin)
        .arg(&seed)
        .output()
        .expect("git clone seed");
    assert!(
        clone.status.success(),
        "git clone seed failed: {}",
        String::from_utf8_lossy(&clone.stderr)
    );
    g(&seed, &["config", "user.email", "t@example.com"]);
    g(&seed, &["config", "user.name", "T"]);
    let sha_a = commit(&seed, "A");
    g(&seed, &["push", "-q", "origin", "main"]);

    // Base clone: takes A, then never hears about B.
    let base_parent = crate::test_support::hermetic_temp_dir();
    let base = base_parent.path().join("base");
    let clone_base = std::process::Command::new("git")
        .args(["clone", "-q"])
        .arg(&origin)
        .arg(&base)
        .output()
        .expect("git clone base");
    assert!(
        clone_base.status.success(),
        "git clone base failed: {}",
        String::from_utf8_lossy(&clone_base.stderr)
    );
    g(&base, &["config", "user.email", "t@example.com"]);
    g(&base, &["config", "user.name", "T"]);

    // Advance `origin/main` behind the base clone's back.
    let sha_b = commit(&seed, "B");
    g(&seed, &["push", "-q", "origin", "main"]);

    assert_eq!(
        g_out(&base, &["rev-parse", "HEAD"]),
        sha_a,
        "fixture precondition: the base clone's local main must be STALE (at A)"
    );
    assert_ne!(sha_a, sha_b, "fixture precondition: A and B must differ");

    StaleBase {
        base,
        origin,
        sha_a,
        sha_b,
        _guards: vec![origin_dir, seed_parent, base_parent],
    }
}

/// #4957: a new session worktree must start at the FETCHED `origin/<default>`
/// tip, not at the base checkout's stale local `main`.
///
/// Why: the reported failure was eight `session/*` branches and local `main`
/// all pointing at the same three-week-old commit, 667 behind `origin/main`,
/// because `git worktree add -b` was given no start-point and no fetch
/// preceded it. Asserting only "a worktree exists" would have passed against
/// that code; the fixture's deliberately-stale local `main` is what makes this
/// test fail before the fix.
/// What: builds a base clone at commit A while `origin/main` has moved to B,
/// calls the production `create_session_worktree`, and asserts the new
/// worktree's `HEAD` is B — and explicitly not A.
/// Test: this function IS the test.
#[test]
fn session_worktree_branches_from_fetched_origin_not_stale_local_main() {
    let fx = stale_base_fixture();

    let worktree = create_session_worktree_unchecked(
        &fx.base,
        "tm-stale-4957",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed against a real base clone");

    let head = g_out(&worktree, &["rev-parse", "HEAD"]);
    assert_ne!(
        head, fx.sha_a,
        "the session worktree was cut from the STALE local main ({}) — #4957",
        fx.sha_a
    );
    assert_eq!(
        head, fx.sha_b,
        "the session worktree must start at the freshly-fetched origin/main tip"
    );
}

/// #4957: when the fetch fails, the session branch must still prefer the
/// last-known `origin/<default>` over the base checkout's local `HEAD`, and
/// the degradation must not read as a clean success.
///
/// Why: falling straight back to local `HEAD` on a failed fetch reintroduces
/// the exact defect for every offline spawn — the fail-open shape this repo
/// keeps getting bitten by. The base is given a LOCAL commit C that `origin`
/// never saw, so `HEAD` and `refs/remotes/origin/main` are distinguishable.
/// What: removes the `origin` repo so the fetch cannot succeed, adds local
/// commit C to the base, then asserts the worktree starts at A (the stale
/// remote-tracking ref) rather than C, and that
/// `inproject_start_point::resolve` reports a warning rather than `Fresh`.
/// Test: this function IS the test.
#[test]
fn session_worktree_falls_back_to_remote_tracking_ref_when_fetch_fails() {
    let fx = stale_base_fixture();
    let sha_c = commit(&fx.base, "C");
    std::fs::remove_dir_all(&fx.origin).expect("remove origin to break the fetch");

    let resolved = super::super::inproject_start_point::resolve(&fx.base).expect("resolves");
    assert_eq!(
        resolved.git_ref(),
        Some("origin/main"),
        "a failed fetch must still hand back the last-known remote-tracking ref"
    );
    let warning = resolved
        .warning()
        .expect("a failed fetch must warn — it must never read as a clean success");
    assert!(
        warning.contains("git fetch origin main failed"),
        "the warning must name the failure: {warning}"
    );

    let worktree = create_session_worktree_unchecked(
        &fx.base,
        "tm-offline-4957",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("an unreachable remote must not fail worktree creation");

    let head = g_out(&worktree, &["rev-parse", "HEAD"]);
    assert_ne!(
        head, sha_c,
        "an offline spawn must not silently fall back to the base checkout's local HEAD"
    );
    assert_eq!(
        head, fx.sha_a,
        "an offline spawn must start at the last fetched origin/main"
    );
}

/// #4957: a repo with no `origin` remote must keep working, branching from
/// `HEAD` without a spurious staleness warning.
///
/// Why: the fix must not turn "purely local repo" into an error or a noisy
/// warning — there `HEAD` is simply the correct start point.
/// What: builds a remote-less repo with one commit, asserts
/// `inproject_start_point::resolve` reports `LocalOnly` with no warning and no
/// start-point ref, and that the created worktree starts at that commit.
/// Test: this function IS the test.
#[test]
fn session_worktree_without_a_remote_still_branches_from_head() {
    let dir = crate::test_support::hermetic_temp_dir();
    let repo = dir.path().join("repo");
    std::fs::create_dir_all(&repo).expect("mkdir repo");
    let init = std::process::Command::new("git")
        .args(["init", "-q", "-b", "main"])
        .arg(&repo)
        .output()
        .expect("git init");
    assert!(
        init.status.success(),
        "git init failed: {}",
        String::from_utf8_lossy(&init.stderr)
    );
    g(&repo, &["config", "user.email", "t@example.com"]);
    g(&repo, &["config", "user.name", "T"]);
    let sha = commit(&repo, "only");

    let resolved = super::super::inproject_start_point::resolve(&repo).expect("resolves");
    assert_eq!(
        resolved.git_ref(),
        Some("refs/heads/main"),
        "a remote-less repo branches from its local default branch"
    );
    assert_eq!(
        resolved.warning(),
        None,
        "a remote-less repo is not a degradation and must not warn"
    );

    let worktree = create_session_worktree_unchecked(
        &repo,
        "tm-local-4957",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("a repo with no remote must still get a worktree");
    assert_eq!(
        g_out(&worktree, &["rev-parse", "HEAD"]),
        sha,
        "a remote-less repo's worktree must start at the local HEAD commit"
    );
}

/// 🔴 #8934 MEDIUM 6: a local-only worktree is cut from the local default
/// branch even when the root has a feature branch checked out, and a repo
/// with no default branch refuses rather than guessing.
/// Test: this function IS the test.
#[test]
fn session_worktree_in_a_local_only_repo_branches_from_its_default_branch() {
    let dir = crate::test_support::hermetic_temp_dir();
    let repo = dir.path().join("repo");
    std::fs::create_dir_all(&repo).expect("mkdir repo");
    g(&repo, &["init", "-q", "-b", "main"]);
    g(&repo, &["config", "user.email", "t@example.com"]);
    g(&repo, &["config", "user.name", "T"]);
    let main_sha = commit(&repo, "on-main");
    g(&repo, &["checkout", "-q", "-b", "feature-8934"]);
    let feature_sha = commit(&repo, "on-feature");

    let worktree = create_session_worktree_unchecked(
        &repo,
        "tm-local-8934",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("a local-only repo with a main branch gets a worktree");
    let head = g_out(&worktree, &["rev-parse", "HEAD"]);
    assert_ne!(head, feature_sha, "cut from the checked-out feature branch");
    assert_eq!(head, main_sha, "must start at the local default branch");

    g(&repo, &["branch", "-q", "-m", "main", "zz-8934-other"]);
    let err = super::super::inproject_start_point::resolve(&repo)
        .expect_err("no default branch must refuse");
    assert!(err.contains("no local default branch"), "{err}");
}

/// #4270: `clean -ffd` in the base clone must not delete session worktrees.
///
/// Why: the two review rounds contradicted each other on whether the missing
/// `.git/info/exclude` entry was cosmetic, and the disagreement was a data-loss
/// question, so it is settled here in the suite rather than by hand. Measured
/// against real git: a single-force `clean` reports `Skipping repository` and
/// is safe, which is what makes this look harmless — but `-ff` removes the
/// worktrees directory outright, uncommitted session work included. The exclude
/// entry is therefore a safety guard. This test moved here from the provisioner
/// suite when #6000 removed that path; the guard is unchanged and now has one
/// owner, [`ensure_base_clone`].
/// What: builds the shipping topology with the production `ensure_base_clone`
/// and `create_session_worktree`, writes an uncommitted file into the worktree,
/// then runs a real `clean -ffd` in the base and asserts the file survives.
/// Test: this function IS the test.
#[test]
fn worktrees_exclude_entry_protects_against_double_force_clean() {
    // #7638: `ensure_base_clone`, the worktree path and `want` each resolve the
    // process-global `TRUSTY_MPM_WORKTREES_DIRNAME`, which sibling tests set
    // under the env lock; hold it so all three resolutions see one value.
    let _env = crate::core::trusty_tools_config::env_test_lock();
    let scratch = crate::test_support::hermetic_temp_dir();
    let origin = scratch.path().join("origin");
    std::fs::create_dir_all(&origin).expect("origin dir");
    for args in [
        vec!["init", "-q"],
        vec!["config", "user.email", "test@example.com"],
        vec!["config", "user.name", "Test"],
    ] {
        let Ok(out) = std::process::Command::new("git")
            .args(&args)
            .current_dir(&origin)
            .output()
        else {
            eprintln!("worktrees_exclude_entry_protects_against_double_force_clean: no git");
            return;
        };
        assert!(out.status.success(), "git {args:?} failed");
    }
    std::fs::write(origin.join("README"), b"seed").expect("seed file");
    for args in [vec!["add", "."], vec!["commit", "-q", "-m", "seed"]] {
        let out = std::process::Command::new("git")
            .args(&args)
            .current_dir(&origin)
            .output()
            .expect("git");
        assert!(out.status.success(), "git {args:?} failed");
    }

    let base = scratch.path().join("owner").join("repo");
    let url = format!("file://{}", origin.display());
    ensure_base_clone(&url, &base, None).expect("ensure_base_clone must succeed");

    let worktree = create_session_worktree_unchecked(
        &base,
        "sess-1",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed");
    let wip = worktree.join("WIP.txt");
    std::fs::write(&wip, b"uncommitted session work").expect("write WIP");

    // The guard itself: the worktrees directory must be excluded in the base.
    let exclude = std::fs::read_to_string(base.join(".git").join("info").join("exclude"))
        .expect("the base clone must have a .git/info/exclude");
    let want = format!(
        "{}/",
        crate::session_manager::decommission::worktrees_dirname()
    );
    assert!(
        exclude.lines().any(|l| l.trim() == want),
        "ensure_base_clone must exclude {want}, got: {exclude}"
    );

    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(&base)
        .args(["clean", "-ffd"])
        .output()
        .expect("git clean -ffd");
    let said = String::from_utf8_lossy(&out.stdout);

    assert!(
        wip.exists(),
        "#4270: `clean -ffd` in the base DELETED a session worktree's \
         uncommitted work — git said: {said}"
    );
    assert!(
        !said.contains(&want),
        "`clean -ffd` must not touch the worktrees directory at all, got: {said}"
    );
}

/// `Option::None` (no `--account` selected) leaves `ensure_base_clone`'s
/// child env untouched — no `account_clone::AccountCloneEnv` is even constructed. Proven
/// at the call-site level: `ensure_base_clone` only calls
/// `account_clone_env` inside its `if let Some(account) = account` arm, so
/// this is a compile-time/structural guarantee rather than a runtime one;
/// this test pins the ambient (unchanged) clone path still succeeds when
/// `account` is absent, matching every pre-#7166 `ensure_base_clone` call.
#[test]
fn ensure_base_clone_with_no_account_is_the_pre_7166_shape() {
    let src = crate::test_support::hermetic_temp_dir();
    let src_path = src.path();
    assert!(
        std::process::Command::new("git")
            .args(["init", src_path.to_str().expect("src utf8")])
            .status()
            .expect("git init src")
            .success(),
        "git init src failed"
    );
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        assert!(
            std::process::Command::new("git")
                .args(["-C", src_path.to_str().expect("utf8"), "config", k, v])
                .status()
                .expect("git config")
                .success(),
            "git config {k} failed"
        );
    }
    std::fs::write(src_path.join("README"), b"src").expect("write README");
    assert!(
        std::process::Command::new("git")
            .args(["-C", src_path.to_str().expect("utf8"), "add", "."])
            .status()
            .expect("git add")
            .success(),
        "git add failed"
    );
    assert!(
        std::process::Command::new("git")
            .args([
                "-C",
                src_path.to_str().expect("utf8"),
                "commit",
                "-m",
                "init",
            ])
            .status()
            .expect("git commit")
            .success(),
        "git commit failed"
    );

    let parent = crate::test_support::hermetic_temp_dir();
    let base = parent.path().join("owner").join("repo");

    ensure_base_clone(src_path.to_str().expect("utf8"), &base, None)
        .expect("an unselected account must not change ambient clone behaviour");
    assert!(base.join(".git").exists());
}