heddle-cli 0.3.1

An AI-native version control system
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
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
// SPDX-License-Identifier: Apache-2.0
//! `heddle init --quickstart` — first-run UX (heddle#231).

use super::*;

/// §5 sentinel from the spike (`docs/spikes/heddle-26-quickstart-ux.md`):
/// a fresh runner with no prior Heddle state reaches the success state
/// from a single, fully flag-driven command — no stdin.
#[test]
fn quickstart_sentinel_reaches_first_commit_from_one_command() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart should succeed: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // init landed
    assert!(dir.join(".heddle").is_dir(), "init created .heddle");

    // a thread exists
    let status = status_json(dir);
    assert_eq!(
        status.get("thread").and_then(Value::as_str),
        Some("quickstart"),
        "status surfaces the quickstart thread: {status}"
    );

    // at least one user-visible capture whose message matches `quickstart`
    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(dir)).unwrap()).unwrap();
    let states = log["states"].as_array().expect("log emits a states array");
    assert!(!states.is_empty(), "at least one capture: {log}");
    let intent = states[0]["intent"].as_str().unwrap_or_default();
    assert!(
        intent.contains("quickstart"),
        "first capture intent mentions quickstart: {intent:?}"
    );
    // identity from the flags must win over any ambient config
    assert_eq!(
        states[0]["principal"].as_str(),
        Some("CI Sentinel <ci@example.invalid>"),
        "capture is attributed to the flag identity: {log}"
    );
}

/// On an empty native directory, no capturable files exist yet, so
/// quickstart writes a root-level `QUICKSTART.md` pointer and captures
/// it (a `.heddle/`-nested placeholder would be dropped by the default
/// ignore list).
#[test]
fn quickstart_writes_placeholder_when_directory_is_empty() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    heddle(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();

    assert!(
        dir.join("QUICKSTART.md").is_file(),
        "quickstart wrote the root-level placeholder"
    );
    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(dir)).unwrap()).unwrap();
    assert_eq!(
        log["states"].as_array().map(Vec::len),
        Some(1),
        "exactly one capture: {log}"
    );
}

/// heddle#644: `heddle status` on a freshly-`init`'d native repo whose
/// log is empty points at the first save — never back at `heddle init
/// --quickstart`, which read as "you initialized wrong" on a repo that
/// is already initialized.
#[test]
fn status_recommends_first_save_not_reinit_on_empty_native_repo() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    heddle(&["init", "--no-harness-install"], Some(dir)).unwrap();

    let status = status_json(dir);
    assert_eq!(
        status["recommended_action"].as_str(),
        Some("heddle commit -m \"...\""),
        "fresh native repo recommends the first save: {status}"
    );
    assert!(
        !status["recommended_action"]
            .as_str()
            .unwrap_or_default()
            .contains("init --quickstart"),
        "status must not suggest re-init on an already-initialized repo: {status}"
    );

    // Once quickstart has produced a capture, the log is no longer empty
    // and the recommendation steps aside.
    heddle(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();
    let status = status_json(dir);
    assert_ne!(
        status["recommended_action"].as_str(),
        Some("heddle commit -m \"...\""),
        "after the first capture the first-save recommendation no longer fires: {status}"
    );
}

/// The confirmation gate refuses to act non-interactively on a directory
/// that already holds Heddle data unless `--yes` is passed.
#[test]
fn quickstart_confirmation_gate_blocks_existing_repo_without_yes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    heddle(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();

    // Re-running without `--yes` in a non-interactive context must refuse.
    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
        ],
        Some(dir),
    )
    .unwrap();
    assert!(
        !out.status.success(),
        "must refuse without --yes on an existing repo"
    );
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        combined.contains("--yes"),
        "the refusal points at --yes: {combined}"
    );
}

/// Identity priority: with no `--principal-*` flags, quickstart resolves
/// the identity already available in the user config and attributes the
/// capture to it — without writing a repo-level principal.
#[test]
fn quickstart_resolves_identity_from_user_config_without_flags() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    let out = heddle_output(
        &["init", "--quickstart", "--no-harness-install", "--yes"],
        Some(dir),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart should resolve identity from user config: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(dir)).unwrap()).unwrap();
    let states = log["states"].as_array().expect("log emits a states array");
    assert_eq!(
        states[0]["principal"].as_str(),
        Some("Heddle Test <heddle@example.com>"),
        "capture is attributed to the seeded user-config identity: {log}"
    );
}

/// ESC-safety / fail-fast ordering: when no identity is resolvable and
/// there is no interactive terminal to prompt, quickstart must refuse
/// BEFORE any filesystem write — leaving no partial `.heddle/`.
#[test]
fn quickstart_identity_failfast_leaves_no_partial_heddle() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    std::fs::write(dir.join("a.txt"), "hi").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);

    // `--yes` clears the confirmation gate so we isolate the identity
    // gate; no flags + no resolvable identity + non-interactive => bail.
    let out = heddle_output_with_env(
        &["init", "--quickstart", "--no-harness-install", "--yes"],
        Some(dir),
        &[
            ("GIT_CONFIG_GLOBAL", "/dev/null"),
            ("GIT_CONFIG_SYSTEM", "/dev/null"),
            ("GIT_CONFIG_NOSYSTEM", "1"),
            ("HEDDLE_PRINCIPAL_NAME", ""),
            ("HEDDLE_PRINCIPAL_EMAIL", ""),
        ],
    )
    .unwrap();

    assert!(
        !out.status.success(),
        "must refuse without a resolvable identity: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    assert!(
        !dir.join(".heddle").exists(),
        "a declined/aborted preflight must leave NO partial .heddle/"
    );
}

/// `--quickstart-thread` names the thread the quickstart starts.
#[test]
fn quickstart_uses_custom_thread_name() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    heddle(
        &[
            "init",
            "--quickstart",
            "--quickstart-thread",
            "research",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();

    let status = status_json(dir);
    assert_eq!(
        status.get("thread").and_then(Value::as_str),
        Some("research"),
        "status surfaces the custom thread: {status}"
    );
}

/// When the directory already has capturable files, quickstart captures
/// them and does NOT write the `QUICKSTART.md` placeholder.
#[test]
fn quickstart_captures_existing_files_without_placeholder() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    std::fs::write(dir.join("notes.txt"), "my work\n").unwrap();

    heddle(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();

    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "no placeholder when real files exist to capture"
    );
    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(dir)).unwrap()).unwrap();
    assert_eq!(
        log["states"].as_array().map(Vec::len),
        Some(1),
        "exactly one capture: {log}"
    );
}

/// On a Git-overlay repo with history, quickstart imports the history,
/// captures, and lands a Git checkpoint commit.
#[test]
fn quickstart_checkpoints_on_git_overlay() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    std::fs::write(dir.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart should checkpoint on git-overlay: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("Checkpoint:"),
        "git-overlay quickstart reports a checkpoint: {stdout}"
    );
}

/// On an unborn Git overlay (a fresh `git init` with NO commits),
/// quickstart must produce exactly ONE capture + ONE checkpoint — the
/// promised single initial commit. Previously it fabricated a "Bootstrap
/// before quickstart" snapshot before `QUICKSTART.md` was written,
/// leaving an extra empty parent commit (Codex r3 cid 3328971408).
#[test]
fn quickstart_unborn_git_yields_single_capture_and_checkpoint() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir); // unborn: no commits yet

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart should succeed on an unborn Git repo: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // Exactly one Heddle state: the bug left a "Bootstrap before
    // quickstart" parent in front of the real capture.
    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(dir)).unwrap()).unwrap();
    let states = log["states"].as_array().expect("log emits a states array");
    assert_eq!(
        states.len(),
        1,
        "exactly one capture, no extra bootstrap parent: {log}"
    );
    let intent = states[0]["intent"].as_str().unwrap_or_default();
    assert!(
        intent.contains("quickstart"),
        "the single state is the quickstart capture, not a bootstrap: {intent:?}"
    );

    // And exactly one Git checkpoint commit (no extra bootstrap parent in
    // the exported history).
    let grepo = open_git(dir).expect("open git repo");
    let tip = grepo
        .head_id()
        .expect("HEAD resolves to a checkpoint commit");
    let commit_count = grepo
        .rev_walk([tip])
        .all()
        .expect("rev-walk checkpoint history")
        .count();
    assert_eq!(
        commit_count, 1,
        "exactly one checkpoint commit, no extra bootstrap parent"
    );
}

/// The quickstart identity preflight must honor a repo-level
/// `.heddle/config.toml` `[principal]`: it outranks user and Git config
/// in `resolve_principal`, so a repo whose ONLY resolvable identity is
/// its repo-level principal must NOT be refused before it is opened
/// (Codex r3 cid 3328971410).
#[test]
fn quickstart_preflight_honors_repo_level_principal() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    // A Git repo so the test harness skips seeding a user-config identity;
    // combined with the cleared env below, the repo-level principal we pin
    // is the ONLY identity available.
    git_hermetic(&["init"], dir);

    let isolate: &[(&str, &str)] = &[
        ("GIT_CONFIG_GLOBAL", "/dev/null"),
        ("GIT_CONFIG_SYSTEM", "/dev/null"),
        ("GIT_CONFIG_NOSYSTEM", "1"),
        ("HEDDLE_PRINCIPAL_NAME", ""),
        ("HEDDLE_PRINCIPAL_EMAIL", ""),
    ];

    let init =
        heddle_output_with_env(&["init", "--no-harness-install"], Some(dir), isolate).unwrap();
    assert!(
        init.status.success(),
        "plain init should succeed: stdout={} stderr={}",
        String::from_utf8_lossy(&init.stdout),
        String::from_utf8_lossy(&init.stderr),
    );

    // Pin a repo-level principal as the sole identity, merged into the
    // config `init` already wrote (which carries the required
    // `[repository]` section).
    let cfg_path = dir.join(".heddle").join("config.toml");
    let mut cfg = repo::RepoConfig::load(&cfg_path).unwrap_or_default();
    cfg.set_principal("Repo Local", "repo@example.invalid");
    cfg.save(&cfg_path).unwrap();

    let out = heddle_output_with_env(
        &["init", "--quickstart", "--no-harness-install", "--yes"],
        Some(dir),
        isolate,
    )
    .unwrap();
    assert!(
        out.status.success(),
        "repo-level principal must satisfy the quickstart preflight: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(dir)).unwrap()).unwrap();
    let states = log["states"].as_array().expect("log emits a states array");
    assert_eq!(
        states[0]["principal"].as_str(),
        Some("Repo Local <repo@example.invalid>"),
        "capture is attributed to the repo-level principal: {log}"
    );
}

/// Codex r4 (cid 3329024451): Git's sentinel-default identity
/// (`user.name=Unknown` / `user.email=unknown@example.com`) is what
/// `resolve_principal`/`build_attribution` treat as UNCONFIGURED and
/// reject. The preflight must filter it the SAME way — a repo whose only
/// Git identity is the sentinel must fail BEFORE any `.heddle` write, not
/// pass the preflight and then have the capture refuse mid-write.
#[test]
fn quickstart_rejects_git_sentinel_identity_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    // Persist the sentinel "unconfigured" identity into the repo's local
    // Git config (the `-c` flags `git_hermetic` passes do NOT persist).
    git_hermetic(&["config", "user.name", "Unknown"], dir);
    git_hermetic(&["config", "user.email", "unknown@example.com"], dir);

    let out = heddle_output_with_env(
        &[
            "init",
            "--quickstart",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
        &[
            ("GIT_CONFIG_GLOBAL", "/dev/null"),
            ("GIT_CONFIG_SYSTEM", "/dev/null"),
            ("GIT_CONFIG_NOSYSTEM", "1"),
            ("HEDDLE_PRINCIPAL_NAME", ""),
            ("HEDDLE_PRINCIPAL_EMAIL", ""),
        ],
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "sentinel-only Git identity must not satisfy the preflight: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_identity_required"),
        "must fail with the quickstart_identity_required advice: stderr={stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: a sentinel-only identity must leave NO partial .heddle/"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}

/// Codex r5 (cid 3329078130): the `Unknown <unknown@example.com>` sentinel
/// passed via `--principal-*` flags is what `build_attribution` rejects. The
/// preflight must reject it the SAME way — fail BEFORE any `.heddle`/
/// `QUICKSTART.md` write, not persist the sentinel and then have the capture
/// refuse mid-write.
#[test]
fn quickstart_rejects_sentinel_principal_flags_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "Unknown",
            "--principal-email",
            "unknown@example.com",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "sentinel principal flags must be rejected: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_identity_required"),
        "must fail with the quickstart_identity_required advice: stderr={stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: a sentinel identity must leave NO partial .heddle/"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}

/// Codex r5 (cid 3329078132): a higher-precedence sentinel must SHADOW a
/// lower valid source, exactly as `resolve_principal` would. A repo-level
/// `[principal]` pinning the sentinel outranks a valid Git identity, so
/// `resolve_principal` stops at the sentinel and the capture is rejected —
/// the preflight must mirror that STOP-at-first-present precedence and fail
/// before writing the placeholder, NOT fall through to the valid Git source.
#[test]
fn quickstart_higher_precedence_sentinel_shadows_valid_lower_source() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    // A VALID lower-precedence Git identity. The old fall-through preflight
    // would have accepted this and let the capture proceed, only for
    // `resolve_principal` (stopping at the repo-config sentinel) to reject it
    // after `.heddle` writes.
    git_hermetic(&["config", "user.name", "Git Valid"], dir);
    git_hermetic(&["config", "user.email", "valid@example.com"], dir);

    let isolate: &[(&str, &str)] = &[
        ("GIT_CONFIG_GLOBAL", "/dev/null"),
        ("GIT_CONFIG_SYSTEM", "/dev/null"),
        ("GIT_CONFIG_NOSYSTEM", "1"),
        ("HEDDLE_PRINCIPAL_NAME", ""),
        ("HEDDLE_PRINCIPAL_EMAIL", ""),
    ];

    // Plain init to create `.heddle`, then pin a sentinel repo-level
    // principal that OUTRANKS the valid Git identity.
    heddle_output_with_env(&["init", "--no-harness-install"], Some(dir), isolate).unwrap();
    let cfg_path = dir.join(".heddle").join("config.toml");
    let mut cfg = repo::RepoConfig::load(&cfg_path).unwrap_or_default();
    cfg.set_principal("Unknown", "unknown@example.com");
    cfg.save(&cfg_path).unwrap();

    let out = heddle_output_with_env(
        &[
            "init",
            "--quickstart",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
        isolate,
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "a higher-precedence sentinel must shadow the valid lower source and fail: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_identity_required"),
        "must fail with the quickstart_identity_required advice: stderr={stderr}"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}

/// Genuine identity still proceeds: with no flags, no repo principal, and
/// no user config, a valid Git `user.*` identity (the lowest-precedence
/// source that the preflight's mirror of `resolve_principal` consults)
/// satisfies the preflight and attributes the capture.
#[test]
fn quickstart_resolves_genuine_git_identity_without_flags() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    git_hermetic(&["config", "user.name", "Git Valid"], dir);
    git_hermetic(&["config", "user.email", "valid@example.com"], dir);

    let out = heddle_output_with_env(
        &["init", "--quickstart", "--no-harness-install", "--yes"],
        Some(dir),
        &[
            ("GIT_CONFIG_GLOBAL", "/dev/null"),
            ("GIT_CONFIG_SYSTEM", "/dev/null"),
            ("GIT_CONFIG_NOSYSTEM", "1"),
            ("HEDDLE_PRINCIPAL_NAME", ""),
            ("HEDDLE_PRINCIPAL_EMAIL", ""),
        ],
    )
    .unwrap();
    assert!(
        out.status.success(),
        "a valid Git identity must satisfy the preflight: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(dir)).unwrap()).unwrap();
    let states = log["states"].as_array().expect("log emits a states array");
    assert_eq!(
        states[0]["principal"].as_str(),
        Some("Git Valid <valid@example.com>"),
        "capture is attributed to the genuine Git identity: {log}"
    );
}

/// Codex r5 (cid 3329078133): an invalid `--quickstart-thread` (a name the
/// ref machinery would reject, e.g. `a..b`) must fail in the preflight,
/// BEFORE init/bootstrap/import write any `.heddle` data — not leave a
/// half-initialized repo for a pure argument error.
#[test]
fn quickstart_rejects_invalid_thread_name_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--quickstart-thread",
            "a..b",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "an invalid thread name must be rejected: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_thread_name_invalid"),
        "must fail with the quickstart_thread_name_invalid advice: stderr={stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: an invalid thread name must leave NO partial .heddle/"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}

/// Codex r5 (cid 3329078135): re-running `--quickstart --yes` after switching
/// away from an existing quickstart thread must repoint that thread to the
/// CURRENT state before attaching, so the new capture's parent is the current
/// worktree's state — not the thread's stale tip. Previously the code skipped
/// repointing an existing thread and attached HEAD to the stale tip, recording
/// the wrong parent and corrupting history.
#[test]
fn quickstart_rerun_repoints_existing_noncurrent_thread() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    // First quickstart on the default "quickstart" thread → state A (root).
    heddle(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();

    // Move to a different thread and advance it to a new state B, so the
    // quickstart thread is no longer current and its tip A is stale.
    heddle(&["thread", "create", "work"], Some(dir)).unwrap();
    heddle(&["thread", "switch", "work"], Some(dir)).unwrap();
    std::fs::write(dir.join("work.txt"), "work\n").unwrap();
    heddle(&["capture", "-m", "work state"], Some(dir)).unwrap();
    let b_id = state_chain_ids(dir, 1)[0].clone();

    // Re-run quickstart while attached to `work`, with a fresh change so the
    // capture is a real new state C.
    std::fs::write(dir.join("more.txt"), "more\n").unwrap();
    let out = heddle_output(
        &["init", "--quickstart", "--no-harness-install", "--yes"],
        Some(dir),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "rerun quickstart should succeed: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // HEAD is now the new quickstart capture C; its parent must be B (the
    // state we were on), NOT the stale quickstart tip A.
    let chain = state_chain_ids(dir, 2);
    assert_eq!(chain.len(), 2, "the new capture has a parent: {chain:?}");
    assert_eq!(
        chain[1], b_id,
        "new capture's parent is the current state B, not the stale quickstart tip: chain={chain:?} b={b_id}"
    );
}

/// Codex r6 (cid 3329175134): a detached Git HEAD has no branch for the
/// checkpoint to advance. The later `create_git_checkpoint` refuses it, but
/// only AFTER the import/capture have written `.heddle/`. The preflight must
/// refuse a detached HEAD BEFORE any write — leaving no partial `.heddle/`.
#[test]
fn quickstart_refuses_detached_git_head_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    std::fs::write(dir.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);
    git_hermetic(&["checkout", "--detach"], dir);

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "a detached Git HEAD must be refused: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_detached_head"),
        "must fail with the quickstart_detached_head advice: {stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: a detached HEAD must leave NO partial .heddle/"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}

/// Codex r6 (cid 3329175135): a Git-overlay quickstart creates a real
/// `refs/heads/<name>`. Git's ref-name rules reject names Heddle's
/// `validate_ref_name` accepts (here a `~`), so such a name would pass
/// preflight and then fail when the branch is created — after `create_snapshot`
/// has written Heddle state. The preflight must validate against Git's rules
/// too so it fails before any write.
#[test]
fn quickstart_rejects_git_invalid_thread_name_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--quickstart-thread",
            "bad~name",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "a Git-invalid thread name must be rejected on a Git overlay: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_thread_name_invalid"),
        "must fail with the quickstart_thread_name_invalid advice: {stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: a Git-invalid thread name must leave NO partial .heddle/"
    );
}

/// Codex r6 (cid 3329175137): in a materialized thread checkout the local
/// `.heddle/` holds only an objectstore pointer; the real `[principal]` lives
/// in the SHARED dir that `Repository::open` loads. The preflight must resolve
/// identity by following the pointer — not probe the local `config.toml` only,
/// which would wrongly report "no identity" and refuse a runnable quickstart.
#[test]
fn quickstart_resolves_principal_from_shared_dir_in_materialized_checkout() {
    let main = TempDir::new().unwrap();
    let checkout = TempDir::new().unwrap();
    let empty_cfg = TempDir::new().unwrap();
    let empty_cfg_path = empty_cfg.path().join("user.toml");
    std::fs::write(&empty_cfg_path, "").unwrap();

    // Native main repo with a capture, so a thread can be materialized.
    heddle(&["init", "--no-harness-install"], Some(main.path())).unwrap();
    std::fs::write(main.path().join("file.txt"), "v1\n").unwrap();
    heddle(&["capture", "-m", "seed"], Some(main.path())).unwrap();

    // Pin the ONLY identity into the SHARED `.heddle/config.toml`.
    let shared_cfg = main.path().join(".heddle").join("config.toml");
    let mut cfg = repo::RepoConfig::load(&shared_cfg).unwrap_or_default();
    cfg.set_principal("Shared Principal", "shared@example.invalid");
    cfg.save(&shared_cfg).unwrap();

    // Materialize a thread checkout whose `.heddle/` is an objectstore pointer.
    heddle(
        &[
            "start",
            "feature/mat",
            "--workspace",
            "materialized",
            "--path",
            checkout.path().to_str().unwrap(),
        ],
        Some(main.path()),
    )
    .unwrap();
    assert!(
        checkout
            .path()
            .join(".heddle")
            .join("objectstore")
            .is_file(),
        "checkout must be a materialized (objectstore-pointer) checkout"
    );

    // Quickstart in the checkout with NO other identity source: an empty user
    // config + cleared env. The ONLY resolvable identity is the shared
    // `[principal]`, reachable solely by following the objectstore pointer.
    let out = heddle_output_with_env(
        &["init", "--quickstart", "--no-harness-install", "--yes"],
        Some(checkout.path()),
        &[
            ("HEDDLE_CONFIG", empty_cfg_path.to_str().unwrap()),
            ("HEDDLE_PRINCIPAL_NAME", ""),
            ("HEDDLE_PRINCIPAL_EMAIL", ""),
        ],
    )
    .unwrap();
    assert!(
        out.status.success(),
        "a materialized checkout must resolve [principal] from the shared dir: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(checkout.path())).unwrap())
            .unwrap();
    let states = log["states"].as_array().expect("log emits a states array");
    assert_eq!(
        states[0]["principal"].as_str(),
        Some("Shared Principal <shared@example.invalid>"),
        "capture is attributed to the shared-dir principal: {log}"
    );
}

/// Codex r6 (cid 3329175136): when a repo's only `[output].format` is repo-level
/// `json`, the preflight (which computed format from CLI/user config only) used
/// to print a TEXT confirmation prompt before the final JSON render — mixing
/// formats. The preflight must load the repo's `[output].format` so the
/// confirmation output matches the final render.
#[test]
fn quickstart_confirmation_respects_repo_json_format() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    // Existing native repo whose ONLY format setting is repo-level json.
    heddle(&["init", "--no-harness-install"], Some(dir)).unwrap();
    let cfg_path = dir.join(".heddle").join("config.toml");
    let mut cfg = repo::RepoConfig::load(&cfg_path).unwrap_or_default();
    cfg.output.format = Some(repo::OutputFormat::Json);
    cfg.save(&cfg_path).unwrap();

    // Re-run quickstart WITHOUT --yes: the confirmation gate fires. With the
    // repo format honored, it must refuse with a clean JSON envelope and emit
    // NO human-readable text prompt to stdout.
    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
        ],
        Some(dir),
    )
    .unwrap();

    assert!(
        !out.status.success(),
        "the confirmation gate must refuse without --yes"
    );
    // The fix: with the repo format honored as json, the preflight must NOT
    // emit the human-readable text confirmation prompt (it would otherwise
    // mix with the JSON final render). Before the fix this warning block was
    // printed to stdout because the preflight computed format without the
    // repo config.
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("would act on a directory that already has work"),
        "repo json format must suppress the text confirmation prompt on stdout: stdout={stdout}"
    );
    assert!(
        stdout.trim().is_empty(),
        "no stray text output when the repo format is json: stdout={stdout}"
    );
}

/// Codex r6 (cid 3329175139): a repo with commits on another ref but an unborn
/// current HEAD (e.g. after `git switch --orphan scratch`) must be treated as
/// having existing history — not history-free. History detection must key on
/// ANY local ref, so the existing-history confirmation gate fires (and, with
/// `--yes`, the history is imported) rather than skipping both.
#[test]
fn quickstart_treats_orphan_branch_repo_as_existing_history() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    std::fs::write(dir.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);
    // Unborn current HEAD, but `main` still carries the commit.
    git_hermetic(&["switch", "--orphan", "scratch"], dir);

    // Without --yes: the existing-history confirmation gate must fire — proof
    // the orphan repo is treated as having history, not as empty.
    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "an orphan-branch repo must hit the existing-history confirmation gate: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_needs_confirmation"),
        "must be the existing-history confirmation refusal, not a history-free skip: {stderr}"
    );
}

/// Codex r11 (cid 3336080241): when the current Git branch is unborn but
/// another branch has commits, quickstart must not try the pre-capture
/// write-through attachment. There is no current exportable state yet, so the
/// first capture should establish the requested thread instead of crashing with
/// "thread 'quickstart' has no state to export" after `.heddle/` was written.
#[test]
fn quickstart_orphan_unborn_head_with_history_defers_attachment_and_succeeds() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    std::fs::write(dir.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);
    git_hermetic(&["switch", "--orphan", "scratch"], dir);

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        out.status.success(),
        "quickstart should succeed by deferring attachment on an unborn current branch: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        !stderr.contains("no state to export"),
        "the write-through attachment path must not run on an unborn current branch: {stderr}"
    );

    let status = status_json(dir);
    assert_eq!(
        status.get("thread").and_then(Value::as_str),
        Some("quickstart"),
        "quickstart remains the active thread after the first capture: {status}"
    );
    assert_eq!(
        state_chain_ids(dir, 1).len(),
        1,
        "the first capture established a state for the quickstart thread"
    );
}

/// Codex r6 (cid 3329175133): `resolve_principal` lets env win OUTRIGHT, so a
/// sentinel env identity shadows even valid `--principal-*` flags — the capture
/// would still be attributed to the env sentinel and rejected by
/// `build_attribution`, but only AFTER init has written `.heddle/`. The
/// preflight must reject the env sentinel BEFORE accepting lower-precedence
/// flags, leaving no partial state.
#[test]
fn quickstart_rejects_env_sentinel_even_with_valid_flags_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    let out = heddle_output_with_env(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "Valid Name",
            "--principal-email",
            "valid@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
        &[
            ("HEDDLE_PRINCIPAL_NAME", "Unknown"),
            ("HEDDLE_PRINCIPAL_EMAIL", "unknown@example.com"),
        ],
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "a sentinel env identity must shadow valid flags and fail: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_identity_required"),
        "must fail with the quickstart_identity_required advice: {stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: an env sentinel must leave NO partial .heddle/"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}

/// Non-interactive `--install-harnesses` installs the named harness as a
/// post-write step (the decision is resolved up front, the install runs
/// after the repo exists).
#[test]
fn quickstart_installs_selected_harness() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    heddle(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--install-harnesses",
            "claude-code",
            "--harness-install-scope",
            "repo",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();

    let settings = dir.join(".claude").join("settings.json");
    assert!(settings.is_file(), "claude-code integration was installed");
    let contents = std::fs::read_to_string(&settings).unwrap();
    assert!(
        contents.contains("integration relay claude-code"),
        "settings carry the relay hooks: {contents}"
    );
}

/// `--install-harnesses none` resolves to an empty selection and installs
/// nothing.
#[test]
fn quickstart_install_none_installs_nothing() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    heddle(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--install-harnesses",
            "none",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();

    assert!(
        !dir.join(".claude").exists(),
        "selecting `none` installs no harness integration"
    );
}

/// Codex r7 (cid 3329270261): the preflight used Git discovery to decide
/// `has_git`, which walks to an ANCESTOR Git checkout — so a native Heddle
/// repo nested inside an ancestor Git checkout was wrongly treated as a Git
/// overlay and refused for the ancestor's detached HEAD, even though
/// `Repository::open` keeps it native and runs no Git checkpoint. The preflight
/// now derives capability from the opened repo, so the nested-native quickstart
/// proceeds.
#[test]
fn quickstart_native_repo_nested_in_git_checkout_is_not_overlay_refused() {
    let outer = TempDir::new().unwrap();
    let inner = outer.path().join("project");
    std::fs::create_dir(&inner).unwrap();

    // Native Heddle repo created BEFORE any Git exists anywhere, so it is a
    // genuine NativeHeddle repo (no `.git` at its own root).
    heddle(&["init", "--no-harness-install"], Some(&inner)).unwrap();
    assert!(inner.join(".heddle").is_dir());

    // Now wrap it in an ancestor Git checkout with a DETACHED HEAD.
    git_hermetic(&["init"], outer.path());
    std::fs::write(outer.path().join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], outer.path());
    git_hermetic(&["commit", "-m", "initial"], outer.path());
    git_hermetic(&["checkout", "--detach"], outer.path());

    // The nested repo is native, so quickstart creates no Git checkpoint and
    // the ancestor's detached HEAD is irrelevant. It must NOT be refused.
    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(&inner),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        out.status.success(),
        "a native repo nested in a detached-HEAD Git checkout must proceed: stdout={stdout} stderr={stderr}",
    );
    assert!(
        !stderr.contains("quickstart_detached_head"),
        "must NOT refuse with the Git-overlay detached-HEAD advice: {stderr}"
    );

    // It is initialized NATIVE — capability comes from the opened repo, not the
    // ancestor Git checkout — so no Git checkpoint is attempted.
    let init: Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(
        init["repository_mode"].as_str(),
        Some("native-heddle"),
        "the nested repo stays native, not a Git overlay: {init}"
    );
    assert!(
        inner.join(".heddle").is_dir(),
        "native .heddle/ was created"
    );
}

/// Codex r7 (cid 3329270259): in a materialized checkout whose `.heddle/`
/// objectstore points to a shared repo INSIDE a Git checkout, `resolve_principal`
/// can attribute the capture through `Repository::get_principal` →
/// `shared_checkout_parent_git_principal` (the shared dir's parent Git config).
/// The preflight's hand-rolled probe missed that source, refusing a runnable
/// quickstart. Delegating to the real `resolve_principal` over the opened repo
/// fixes it.
#[test]
fn quickstart_resolves_shared_checkout_parent_git_identity() {
    let main = TempDir::new().unwrap();
    let checkout = TempDir::new().unwrap();
    let empty_cfg = TempDir::new().unwrap();
    let empty_cfg_path = empty_cfg.path().join("user.toml");
    std::fs::write(&empty_cfg_path, "").unwrap();

    // Native main repo with a capture, so a thread can be materialized. NO
    // `[principal]` is written to the shared config — identity must come solely
    // from the shared dir's PARENT Git config below.
    heddle(&["init", "--no-harness-install"], Some(main.path())).unwrap();
    std::fs::write(main.path().join("file.txt"), "v1\n").unwrap();
    heddle(&["capture", "-m", "seed"], Some(main.path())).unwrap();

    heddle(
        &[
            "start",
            "feature/mat",
            "--workspace",
            "materialized",
            "--path",
            checkout.path().to_str().unwrap(),
        ],
        Some(main.path()),
    )
    .unwrap();
    assert!(
        checkout
            .path()
            .join(".heddle")
            .join("objectstore")
            .is_file(),
        "checkout must be a materialized (objectstore-pointer) checkout"
    );

    // Make the shared repo's containing dir a Git checkout whose ONLY identity
    // is its Git `user.*` — reachable from the checkout solely via
    // `shared_checkout_parent_git_principal`.
    git_hermetic(&["init"], main.path());
    git_hermetic(&["config", "user.name", "Parent Git"], main.path());
    git_hermetic(
        &["config", "user.email", "parent@example.invalid"],
        main.path(),
    );

    // Quickstart in the checkout with NO other identity source: empty user
    // config + cleared principal env.
    let out = heddle_output_with_env(
        &["init", "--quickstart", "--no-harness-install", "--yes"],
        Some(checkout.path()),
        &[
            ("HEDDLE_CONFIG", empty_cfg_path.to_str().unwrap()),
            ("HEDDLE_PRINCIPAL_NAME", ""),
            ("HEDDLE_PRINCIPAL_EMAIL", ""),
        ],
    )
    .unwrap();
    assert!(
        out.status.success(),
        "preflight must resolve identity from the shared dir's parent Git config: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(checkout.path())).unwrap())
            .unwrap();
    let states = log["states"].as_array().expect("log emits a states array");
    assert_eq!(
        states[0]["principal"].as_str(),
        Some("Parent Git <parent@example.invalid>"),
        "capture is attributed to the shared-checkout parent Git identity: {log}"
    );
}

/// Codex r7 (cid 3329270260): `refs/heads/<thread>` can be a syntactically
/// valid FULL ref even when `<thread>` is not a usable Git BRANCH name (e.g.
/// the reserved `HEAD`, or a leading `-`). Validating only the full ref let
/// such names pass preflight and fail at branch creation — after Heddle state
/// was written. The preflight now validates the branch shorthand too.
#[test]
fn quickstart_rejects_git_branch_invalid_shorthand_before_writes() {
    for bad in ["HEAD", "-leading"] {
        let temp = TempDir::new().unwrap();
        let dir = temp.path();
        git_hermetic(&["init"], dir);

        // `=` form so clap accepts a value that begins with `-`.
        let thread_arg = format!("--quickstart-thread={bad}");
        let out = heddle_output(
            &[
                "init",
                "--quickstart",
                &thread_arg,
                "--principal-name",
                "CI Sentinel",
                "--principal-email",
                "ci@example.invalid",
                "--no-harness-install",
                "--yes",
                "--output",
                "json",
            ],
            Some(dir),
        )
        .unwrap();

        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            !out.status.success(),
            "'{bad}' is not a usable Git branch name and must be rejected: stdout={} stderr={stderr}",
            String::from_utf8_lossy(&out.stdout),
        );
        assert!(
            stderr.contains("quickstart_thread_name_invalid"),
            "'{bad}' must fail with the quickstart_thread_name_invalid advice: {stderr}"
        );
        assert!(
            !dir.join(".heddle").exists(),
            "fail-before-writes: '{bad}' must leave NO partial .heddle/"
        );
    }
}

/// Recursively snapshot every file under `dir` as `(relative_path, bytes)`,
/// sorted — a content fingerprint used to prove a refused quickstart performed
/// ZERO writes (no metadata so it can't flake on mtime/atime).
fn snapshot_tree(dir: &std::path::Path) -> Vec<(std::path::PathBuf, Vec<u8>)> {
    fn walk(
        base: &std::path::Path,
        dir: &std::path::Path,
        out: &mut Vec<(std::path::PathBuf, Vec<u8>)>,
    ) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            match entry.file_type() {
                Ok(ft) if ft.is_dir() => walk(base, &path, out),
                Ok(ft) if ft.is_file() => {
                    let rel = path.strip_prefix(base).unwrap().to_path_buf();
                    out.push((rel, std::fs::read(&path).unwrap_or_default()));
                }
                _ => {}
            }
        }
    }
    let mut out = Vec::new();
    walk(dir, dir, &mut out);
    out.sort();
    out
}

/// Codex r8 (cid 3329342102 / 3329342201): run from a SUBDIRECTORY of an
/// existing NATIVE Heddle repo, quickstart used to `init_default(<cwd>)` — a
/// nested `.heddle/` at the subdir — because both the preflight and the write
/// path keyed on `<cwd>/.heddle`. With a single root resolved by ancestor
/// discovery, it must operate on the DISCOVERED repo, creating no nested repo.
#[test]
fn quickstart_from_subdir_targets_discovered_native_repo() {
    let temp = TempDir::new().unwrap();
    let root = temp.path();
    heddle(&["init", "--no-harness-install"], Some(root)).unwrap();
    assert!(
        root.join(".heddle").is_dir(),
        "native repo created at the root"
    );

    let sub = root.join("nested").join("deeper");
    std::fs::create_dir_all(&sub).unwrap();

    let out = heddle_output(
        &["init", "--quickstart", "--no-harness-install", "--yes"],
        Some(&sub),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart from a subdir of a native repo must proceed: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // The discovered repo is the target — NOT a nested repo at the subdir.
    assert!(
        !sub.join(".heddle").exists(),
        "must NOT create a nested .heddle/ at the subdirectory"
    );
    assert!(
        root.join(".heddle").is_dir(),
        "the discovered repo root stays the single repo"
    );
    // The quickstart ran against the discovered repo: it has the thread.
    let status = status_json(root);
    assert_eq!(
        status.get("thread").and_then(Value::as_str),
        Some("quickstart"),
        "the discovered repo carries the quickstart thread: {status}"
    );
    // The placeholder/capture landed at the discovered root, not the subdir.
    assert!(
        root.join("QUICKSTART.md").is_file(),
        "the capture wrote QUICKSTART.md at the discovered root"
    );
    assert!(
        !sub.join("QUICKSTART.md").exists(),
        "nothing was written into the subdirectory"
    );
}

/// Codex r8 (cid 3329342104 / 3329342205): run from a SUBDIRECTORY of a Git
/// checkout (no Heddle yet), quickstart used to `bootstrap_git_overlay(<cwd>)`
/// — a `.heddle/` at the subdir whose root has no `.git`, so it came up NATIVE
/// and never imported/checkpointed, while the preflight had classified it a Git
/// overlay (and could refuse on the ancestor's detached HEAD). It must now
/// bootstrap at the DISCOVERED Git root and run as a real Git overlay.
#[test]
fn quickstart_from_subdir_targets_discovered_git_root() {
    let temp = TempDir::new().unwrap();
    let root = temp.path();
    git_hermetic(&["init"], root);
    std::fs::write(root.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], root);
    git_hermetic(&["commit", "-m", "initial"], root);

    let sub = root.join("src").join("inner");
    std::fs::create_dir_all(&sub).unwrap();

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(&sub),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart from a subdir of a Git checkout must proceed: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // Targets the discovered Git ROOT, not a nested repo at the subdir.
    assert!(
        !sub.join(".heddle").exists(),
        "must NOT create a nested .heddle/ at the subdirectory"
    );
    assert!(
        root.join(".heddle").is_dir(),
        "Heddle data is created at the discovered Git root"
    );

    // It runs as a real Git overlay (not the native repo the subdir bug made).
    let init: Value = serde_json::from_str(&String::from_utf8_lossy(&out.stdout)).unwrap();
    assert_eq!(
        init["repository_mode"].as_str(),
        Some("git-overlay"),
        "the discovered Git root is a Git overlay: {init}"
    );
    assert_eq!(
        init["git_detected"].as_bool(),
        Some(true),
        "git is detected for the discovered root: {init}"
    );

    // The checkpoint advanced a real branch — impossible if it had come up as a
    // native repo at the subdir. History (initial) plus the checkpoint commit.
    let grepo = open_git(root).expect("open git repo at the discovered root");
    let tip = grepo.head_id().expect("HEAD resolves to a commit");
    let commit_count = grepo
        .rev_walk([tip])
        .all()
        .expect("rev-walk checkpoint history")
        .count();
    assert!(
        commit_count >= 2,
        "the Git-overlay quickstart imported history and added a checkpoint commit: count={commit_count}"
    );
}

/// Codex r8 (cid 3329342100 / 3329342200): the preflight used to
/// `Repository::open` the existing repo to read its capability/identity. For a
/// Git-overlay repo, `open` synchronizes `.heddle/HEAD` to Git's HEAD — a WRITE
/// that fired BEFORE the confirmation gate could refuse. A refused quickstart
/// (existing repo, non-interactive, no `--yes`) must now perform ZERO writes:
/// the preflight is fully read-only and never opens the repo.
#[test]
fn quickstart_refusal_on_existing_git_overlay_writes_nothing() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    std::fs::write(dir.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);
    // Existing Heddle Git-overlay repo: `.heddle/HEAD` now exists and matches
    // Git's current branch.
    heddle(&["init", "--no-harness-install"], Some(dir)).unwrap();
    // Drift Git's HEAD away from Heddle's HEAD so that opening the repo WOULD
    // re-sync `.heddle/HEAD` (the exact write the old preflight performed).
    git_hermetic(&["switch", "-c", "feature"], dir);

    let heddle_dir = dir.join(".heddle");
    let before = snapshot_tree(&heddle_dir);

    // Non-interactive, no `--yes`: the existing-history confirmation gate must
    // refuse — before any write.
    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "must refuse without --yes on an existing repo: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_needs_confirmation"),
        "the refusal is the confirmation gate: {stderr}"
    );

    let after = snapshot_tree(&heddle_dir);
    assert!(
        before == after,
        "a refused quickstart must not write to .heddle/ (HEAD-sync must not fire): \
         the preflight is read-only and must not open the repo"
    );
}

/// Codex r8 (cid 3329342103 / 3329342203): harness installs used to run BEFORE
/// the first capture, so `ensure_capturable_content` saw the generated
/// scaffolding (`.claude/settings.json`, …) as the user's content — skipping
/// the `QUICKSTART.md` placeholder and recording integration files as the first
/// state. Capture must run first: the first state is the user's content; the
/// install lands after and stays uncaptured.
#[test]
fn quickstart_captures_before_installing_harness() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--install-harnesses",
            "claude-code",
            "--harness-install-scope",
            "repo",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart with a harness install must succeed: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // The install ran (after the capture).
    assert!(
        dir.join(".claude").join("settings.json").is_file(),
        "the selected harness was installed"
    );
    // Capture-before-install: an EMPTY dir still got the QUICKSTART.md
    // placeholder. With install-first, `.claude/` would have made the dir look
    // non-empty and the placeholder would have been skipped.
    assert!(
        dir.join("QUICKSTART.md").is_file(),
        "the capture ran before the install, so the empty dir got QUICKSTART.md"
    );

    // Exactly one capture, and it recorded the user's content — not the harness
    // scaffolding, which remains UNTRACKED (installed after the capture).
    let log: Value =
        serde_json::from_str(&heddle(&["log", "--output", "json"], Some(dir)).unwrap()).unwrap();
    assert_eq!(
        log["states"].as_array().map(Vec::len),
        Some(1),
        "exactly one capture: {log}"
    );
    let status = status_json(dir);
    let added: Vec<String> = status["changes"]["added"]
        .as_array()
        .map(|paths| {
            paths
                .iter()
                .filter_map(|p| p.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();
    assert!(
        added.iter().any(|p| p.contains(".claude")),
        "harness scaffolding is UNTRACKED — it was installed after the capture: {status}"
    );
    assert!(
        !added.iter().any(|p| p.contains("QUICKSTART.md")),
        "QUICKSTART.md was the captured first state, not untracked: {status}"
    );
}

/// Codex r7 (cid 3329270262): an invalid `--harness-install-scope` was not
/// parsed until the post-init install step, so a pure argument error left a
/// partially initialized repo. The pre-write decision now validates the scope
/// with the same `IntegrationScope::parse` the install uses.
#[test]
fn quickstart_rejects_invalid_harness_scope_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--install-harnesses",
            "claude-code",
            "--harness-install-scope",
            "bogus",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "an invalid harness scope must be rejected before writes: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("integration_scope_invalid"),
        "must fail with the integration_scope_invalid advice: {stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: an invalid harness scope must leave NO partial .heddle/"
    );
    assert!(
        !dir.join(".claude").exists(),
        "no harness integration may be installed on a scope error"
    );
}

/// Codex r9 (cid 3329409818): `--install-harnesses codex` with the default
/// `--harness-install-scope repo` passed the generic-scope preflight (the enum
/// parses), but `install_codex` rejects any non-`user` scope — AFTER `.heddle/`,
/// `QUICKSTART.md`, and the capture/checkpoint were already written. The
/// preflight now mirrors each harness's OWN scope rule, so a scope a harness
/// will reject fails before any write.
#[test]
fn quickstart_rejects_codex_repo_scope_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--install-harnesses",
            "codex",
            "--harness-install-scope",
            "repo",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "codex + repo scope must be rejected before writes: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("integration_codex_scope_invalid"),
        "must fail with the harness-specific scope advice: {stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: a harness/scope mismatch must leave NO partial .heddle/"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}

/// Codex r9 (cid 3329409826): a shallow Git checkout (`.git/shallow`) is
/// rejected by `import_all` — but only AFTER `bootstrap_git_overlay` created
/// `.heddle/` and edited the Git excludes, leaving a half-initialized sidecar.
/// The preflight must detect the shallow clone and refuse before any write.
#[test]
fn quickstart_rejects_shallow_git_clone_before_writes() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init"], dir);
    std::fs::write(dir.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);
    // Mark the checkout shallow the way a `--depth` clone would: a `.git/shallow`
    // file listing the shallow boundary. `import_all` keys on its presence
    // (`git_dir()/shallow`), and so does the preflight's `git_is_shallow`.
    let grepo = open_git(dir).unwrap();
    let head = grepo.head_id().unwrap().to_string();
    std::fs::write(dir.join(".git").join("shallow"), format!("{head}\n")).unwrap();

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "a shallow clone must be rejected before writes: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_shallow_clone"),
        "must fail with the quickstart_shallow_clone advice: {stderr}"
    );
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: a shallow clone must leave NO partial .heddle/"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}

/// Codex r9 (cid 3329409822): run inside a nested Git checkout below an ancestor
/// Heddle repo, quickstart used to return the ancestor `.heddle` root — but
/// `Repository::open` has a special case that bootstraps the NESTED Git root
/// instead. Quickstart would then write the thread into the parent and never
/// import the nested Git history. Target resolution now mirrors
/// `Repository::open`'s nested-Git-first walk, so the nested Git root is
/// bootstrapped and imported.
#[test]
fn quickstart_nested_git_below_ancestor_heddle_targets_nested_git() {
    let outer = TempDir::new().unwrap();
    let ancestor = outer.path();
    // Ancestor native Heddle repo (no Git at its own root).
    heddle(&["init", "--no-harness-install"], Some(ancestor)).unwrap();
    assert!(ancestor.join(".heddle").is_dir());

    // A nested Git checkout below it, with history and NO `.heddle` of its own.
    let nested = ancestor.join("nested");
    std::fs::create_dir(&nested).unwrap();
    git_hermetic(&["init"], &nested);
    std::fs::write(nested.join("n.txt"), "nested\n").unwrap();
    git_hermetic(&["add", "."], &nested);
    git_hermetic(&["commit", "-m", "nested initial"], &nested);

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(&nested),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart in a nested Git checkout must bootstrap the nested root: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // The nested Git root is the target: it gets its OWN `.heddle/`, as a Git
    // overlay — NOT a write into the ancestor.
    assert!(
        nested.join(".heddle").is_dir(),
        "the nested Git root was bootstrapped with its own .heddle/"
    );
    let init: Value = serde_json::from_str(&String::from_utf8_lossy(&out.stdout)).unwrap();
    assert_eq!(
        init["repository_mode"].as_str(),
        Some("git-overlay"),
        "the nested Git root runs as a Git overlay: {init}"
    );
    // The nested quickstart carries the thread; the ancestor is untouched.
    let nested_status = status_json(&nested);
    assert_eq!(
        nested_status.get("thread").and_then(Value::as_str),
        Some("quickstart"),
        "the nested repo carries the quickstart thread: {nested_status}"
    );
    let ancestor_status = status_json(ancestor);
    assert_ne!(
        ancestor_status.get("thread").and_then(Value::as_str),
        Some("quickstart"),
        "the ancestor Heddle repo must NOT have been written into: {ancestor_status}"
    );
    // The nested Git history was imported AND checkpointed: the nested Git root
    // now has the original commit plus the checkpoint commit.
    let grepo = open_git(&nested).expect("open nested git repo");
    let tip = grepo.head_id().expect("nested HEAD resolves");
    let commit_count = grepo
        .rev_walk([tip])
        .all()
        .expect("rev-walk nested history")
        .count();
    assert!(
        commit_count >= 2,
        "the nested Git history was imported and a checkpoint added: count={commit_count}"
    );
}

/// Codex r9 (cid 3329409824): in an existing Git-overlay repo, writing only
/// `.heddle/HEAD = quickstart` is not enough — `head_ref()` deliberately
/// resolves back to the live Git branch (`main`), so the capture/checkpoint
/// advanced `main` while the `quickstart` thread stayed at the imported tip,
/// even though the output said `Thread: quickstart`. Quickstart now attaches the
/// Git checkout to the thread's branch (the same write-through `thread switch`
/// uses), so the capture AND checkpoint land on `quickstart` — `main` does not
/// move.
#[test]
fn quickstart_git_overlay_capture_and_checkpoint_land_on_quickstart_thread() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init", "-b", "main"], dir);
    std::fs::write(dir.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
        ],
        Some(dir),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "quickstart on a Git overlay must succeed: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );

    // The active thread is `quickstart`, matching the reported output.
    let status = status_json(dir);
    assert_eq!(
        status.get("thread").and_then(Value::as_str),
        Some("quickstart"),
        "the active thread is quickstart: {status}"
    );

    let grepo = open_git(dir).expect("open git repo");
    // `quickstart` advanced past the imported tip (initial + checkpoint = 2),
    // while `main` stayed at the imported tip (1 commit) — proof the capture and
    // checkpoint landed on the requested thread, not on main.
    let count_on = |branch: &str| -> usize {
        let mut reference =
            find_reference(&grepo, branch).unwrap_or_else(|_| panic!("ref {branch} exists"));
        let tip = reference.peel_to_id().expect("ref peels");
        grepo.rev_walk([tip]).all().expect("rev-walk").count()
    };
    assert_eq!(count_on("main"), 1, "main stayed at the imported tip");
    assert_eq!(
        count_on("quickstart"),
        2,
        "quickstart advanced: imported tip + the checkpoint commit"
    );
}

/// Codex r9 regression (cid 3335757978): a Git overlay where a `quickstart`
/// branch ALREADY exists with divergent history, while the checkout is on
/// another branch. The r9 thread-attachment would `import_all` that branch as a
/// thread, repoint it to the current branch's state, and write-through-move
/// `refs/heads/quickstart` onto the current branch — silently destroying the
/// user's branch. Quickstart must REFUSE before any write, leaving the existing
/// branch untouched and no `.heddle/` behind.
#[test]
fn quickstart_refuses_clobbering_existing_divergent_quickstart_branch() {
    let temp = TempDir::new().unwrap();
    let dir = temp.path();
    git_hermetic(&["init", "-b", "main"], dir);
    std::fs::write(dir.join("a.txt"), "hi\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "initial"], dir);

    // A pre-existing `quickstart` branch with its OWN distinct commit.
    git_hermetic(&["checkout", "-b", "quickstart"], dir);
    std::fs::write(dir.join("their-work.txt"), "precious\n").unwrap();
    git_hermetic(&["add", "."], dir);
    git_hermetic(&["commit", "-m", "their quickstart work"], dir);
    git_hermetic(&["checkout", "main"], dir);

    let tip_before = {
        let grepo = open_git(dir).expect("open git repo");
        find_reference(&grepo, "quickstart")
            .expect("quickstart branch exists")
            .peel_to_id()
            .expect("peels")
    };

    let out = heddle_output(
        &[
            "init",
            "--quickstart",
            "--principal-name",
            "CI Sentinel",
            "--principal-email",
            "ci@example.invalid",
            "--no-harness-install",
            "--yes",
            "--output",
            "json",
        ],
        Some(dir),
    )
    .unwrap();

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !out.status.success(),
        "a pre-existing divergent quickstart branch must be refused: stdout={} stderr={stderr}",
        String::from_utf8_lossy(&out.stdout),
    );
    assert!(
        stderr.contains("quickstart_thread_branch_collision"),
        "must fail with the collision advice pointing at --quickstart-thread: {stderr}"
    );

    // The user's branch is UNCHANGED.
    let tip_after = {
        let grepo = open_git(dir).expect("open git repo");
        find_reference(&grepo, "quickstart")
            .expect("quickstart branch still exists")
            .peel_to_id()
            .expect("peels")
    };
    assert_eq!(
        tip_before, tip_after,
        "the user's pre-existing quickstart branch must not be moved"
    );

    // Fail-before-writes: nothing landed.
    assert!(
        !dir.join(".heddle").exists(),
        "fail-before-writes: a collision must leave NO partial .heddle/"
    );
    assert!(
        !dir.join("QUICKSTART.md").exists(),
        "fail-before-writes: no QUICKSTART.md placeholder may be written"
    );
}