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
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
// SPDX-License-Identifier: Apache-2.0
use super::*;

fn expect_json_reserve_failure(args: &[&str], cwd: &std::path::Path) -> Value {
    let output = heddle_output(args, Some(cwd)).expect("invoke reserve failure");
    assert!(
        !output.status.success(),
        "reservation attempt should fail for args {args:?}"
    );
    let stdout = str::from_utf8(&output.stdout).unwrap_or("");
    assert!(
        stdout.trim().is_empty(),
        "JSON-mode reservation failures must not emit a success-shaped stdout object: {stdout}"
    );
    let stderr = str::from_utf8(&output.stderr).unwrap_or("");
    serde_json::from_str(stderr.trim()).expect("reservation failure should emit JSON envelope")
}

#[test]
fn thread_start_rejects_second_active_writer_for_same_thread() {
    let main = setup_repo("base.txt", "shared base");
    let first = TempDir::new().unwrap();
    let second = TempDir::new().unwrap();

    heddle(
        &[
            "start",
            "feature/reserved",
            "--workspace",
            "materialized",
            "--path",
            first.path().to_str().unwrap(),
        ],
        Some(main.path()),
    )
    .unwrap();

    let err = heddle(
        &[
            "start",
            "feature/reserved",
            "--workspace",
            "materialized",
            "--path",
            second.path().to_str().unwrap(),
        ],
        Some(main.path()),
    )
    .expect_err("second active writer should be rejected");
    assert!(
        err.contains("already has an active reservation"),
        "thread reservation conflict should be explicit: {err}"
    );
}

#[test]
fn agent_api_reserve_heartbeat_release_round_trips_json() {
    let main = setup_repo("base.txt", "shared base");

    let reserved: Value = inject_post_verification_at(
        main.path(),
        serde_json::from_str(
            &heddle(
                &[
                    "agent",
                    "reserve",
                    "--thread",
                    "feature/api",
                    "--task",
                    "exercise stable API",
                ],
                Some(main.path()),
            )
            .unwrap(),
        )
        .unwrap(),
    );
    let reservation = &reserved["reservation"];
    let session = reservation["session_id"].as_str().unwrap().to_string();
    assert_eq!(reservation["thread"], "feature/api");
    assert!(reservation["reservation_token"].as_str().is_some());
    assert!(reserved["verification"].is_object());

    let heartbeat: Value = inject_post_verification_at(
        main.path(),
        serde_json::from_str(
            &heddle(
                &["agent", "heartbeat", "--session", &session],
                Some(main.path()),
            )
            .unwrap(),
        )
        .unwrap(),
    );
    assert_eq!(heartbeat["reservation"]["session_id"], session);
    assert!(heartbeat["verification"].is_object());

    let released: Value = inject_post_verification_at(
        main.path(),
        serde_json::from_str(
            &heddle(
                &[
                    "agent",
                    "release",
                    "--session",
                    &session,
                    "--status",
                    "complete",
                ],
                Some(main.path()),
            )
            .unwrap(),
        )
        .unwrap(),
    );
    assert_eq!(released["reservation"]["status"], "complete");
    assert!(released["verification"].is_object());

    let listed: Value = serde_json::from_str(
        &heddle(&["--output", "json", "agent", "list"], Some(main.path())).unwrap(),
    )
    .unwrap();
    assert_eq!(listed["reservations"].as_array().unwrap().len(), 1);
    assert!(listed["verification"].is_object());
}

/// `agent reserve` must distinguish three cases:
///   1. existing reservation owned by a *live* process at the same
///      anchor → `live_owner` JSON conflict
///   2. existing reservation owned by a *live* process at a *different*
///      anchor → `anchor_drift` JSON conflict
///   3. existing reservation whose owning process is *dead* → reaped,
///      new reservation succeeds
///
/// One-shot CLI invocations exit before the next call runs, so we
/// simulate a live owner by rewriting the entry's recorded pid to the
/// test-runner pid (always alive while the test is in progress).
#[test]
fn agent_api_reserve_emits_structured_live_owner_and_anchor_drift_conflicts() {
    let main = setup_repo("base.txt", "shared base");

    let reserved: Value = serde_json::from_str(
        &heddle(
            &[
                "agent",
                "reserve",
                "--thread",
                "feature/conflict",
                "--task",
                "first writer",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let reservation = &reserved["reservation"];
    let session = reservation["session_id"].as_str().unwrap().to_string();
    let anchor_state = reservation["anchor_state"].as_str().unwrap().to_string();

    // Pin the recorded pid to this test-runner process so the live-
    // owner branch fires reliably, and clear boot_id to keep the check
    // platform-independent (boot_id mismatch would otherwise reap on
    // hosts that expose one).
    let entry_path = main
        .path()
        .join(".heddle")
        .join("agents")
        .join(format!("{session}.toml"));
    let entry_text = std::fs::read_to_string(&entry_path).unwrap();
    // Pin pid to the test-runner process; leave boot_id alone so the
    // liveness check sees a live owner on the current boot.
    let lines: Vec<String> = entry_text
        .lines()
        .map(|line| {
            if line.starts_with("pid = ") {
                format!("pid = {}", std::process::id())
            } else {
                line.to_string()
            }
        })
        .collect();
    std::fs::write(&entry_path, lines.join("\n")).unwrap();

    // Same-anchor live owner → live_owner conflict.
    let live_conflict = expect_json_reserve_failure(
        &[
            "--output",
            "json",
            "agent",
            "reserve",
            "--thread",
            "feature/conflict",
        ],
        main.path(),
    );
    assert_eq!(live_conflict["kind"], "live_owner");
    assert!(
        live_conflict["error"]
            .as_str()
            .is_some_and(|error| error.contains(&session)),
        "live_owner conflict should name the existing session: {live_conflict}"
    );
    assert!(
        live_conflict["hint"]
            .as_str()
            .is_some_and(|hint| hint.contains("heddle thread show feature/conflict")),
        "live_owner conflict should include a recovery hint: {live_conflict}"
    );

    // Different anchor while owner is alive → anchor_drift conflict.
    // We synthesize a divergent anchor by snapshotting on main while
    // the existing reservation still records the original anchor.
    std::fs::write(main.path().join("base.txt"), "advanced base").unwrap();
    heddle(
        &["capture", "-m", "advance main for drift test"],
        Some(main.path()),
    )
    .unwrap();

    let drift_conflict = expect_json_reserve_failure(
        &[
            "--output",
            "json",
            "agent",
            "reserve",
            "--thread",
            "feature/conflict",
        ],
        main.path(),
    );
    assert_eq!(drift_conflict["kind"], "anchor_drift");
    assert!(
        drift_conflict["error"]
            .as_str()
            .is_some_and(|error| error.contains(&anchor_state)),
        "anchor_drift conflict should expose reserved anchor: {drift_conflict}"
    );

    // Now mark the recorded pid as dead. The next reserve must reap
    // the abandoned entry and succeed.
    let entry_text = std::fs::read_to_string(&entry_path).unwrap();
    let lines: Vec<String> = entry_text
        .lines()
        .map(|line| {
            if line.starts_with("pid = ") {
                "pid = 2147483647".to_string() // 0x7fff_ffff is unassignable
            } else if line.starts_with("boot_id = ") {
                "boot_id = \"definitely-stale-boot\"".to_string()
            } else {
                line.to_string()
            }
        })
        .collect();
    std::fs::write(&entry_path, lines.join("\n")).unwrap();

    // Request the original anchor so the ref-side drift check doesn't
    // fire and we exercise the registry reap path cleanly.
    let reaped = heddle(
        &[
            "agent",
            "reserve",
            "--thread",
            "feature/conflict",
            "--anchor",
            &anchor_state,
        ],
        Some(main.path()),
    )
    .expect("dead-owner reservation must succeed after reap");
    let reaped: Value = serde_json::from_str(&reaped).unwrap();
    assert_ne!(
        reaped["reservation"]["session_id"], session,
        "reaped should mint new id"
    );
    assert_eq!(reaped["reservation"]["status"], "active");

    // Old entry should be marked Abandoned, not deleted.
    let stale = std::fs::read_to_string(&entry_path).unwrap();
    assert!(
        stale.contains("status = \"abandoned\""),
        "reaped entry must record abandoned status: {stale}"
    );
}

#[test]
fn agent_api_reserve_anchor_drift_without_owner_uses_error_envelope_only() {
    let main = setup_repo("base.txt", "shared base");

    let reserved: Value = serde_json::from_str(
        &heddle(
            &["agent", "reserve", "--thread", "feature/no-owner"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let session = reserved["reservation"]["session_id"].as_str().unwrap();
    let anchor_state = reserved["reservation"]["anchor_state"]
        .as_str()
        .unwrap()
        .to_string();

    heddle(
        &[
            "agent",
            "release",
            "--session",
            session,
            "--status",
            "complete",
        ],
        Some(main.path()),
    )
    .unwrap();

    std::fs::write(main.path().join("base.txt"), "advanced base").unwrap();
    heddle(
        &["capture", "-m", "advance main for ownerless drift test"],
        Some(main.path()),
    )
    .unwrap();

    let drift_conflict = expect_json_reserve_failure(
        &[
            "--output",
            "json",
            "agent",
            "reserve",
            "--thread",
            "feature/no-owner",
        ],
        main.path(),
    );
    assert_eq!(drift_conflict["kind"], "anchor_drift");
    assert!(
        drift_conflict["error"]
            .as_str()
            .is_some_and(|error| error.contains(&anchor_state)),
        "anchor_drift conflict should expose the existing anchor: {drift_conflict}"
    );
    assert!(
        drift_conflict["hint"]
            .as_str()
            .is_some_and(|hint| hint.contains("Refresh the thread")),
        "anchor_drift conflict should include a recovery hint: {drift_conflict}"
    );
}

/// `heddle agent reserve --hold-for-pid PID` binds the reservation's
/// liveness to an external process — typically the orchestrator that
/// wraps the heddle CLI. The contract this test protects:
///
///   1. While the held pid is alive, a second reservation attempt
///      sees a `live_owner` conflict (no recycling).
///   2. When the held pid dies, the reaper picks up the dead-pid
///      signal and the next reservation succeeds.
///
/// We simulate the orchestrator with a long-running `sleep` so we
/// have a real, killable pid; SIGKILL gives us the harshest possible
/// "process gone" signal (no Drop guards, no graceful release).
#[test]
fn agent_reserve_hold_for_pid_binds_reservation_to_external_process() {
    use std::process::Command;
    let main = setup_repo("base.txt", "shared base");

    // Spawn a long-running helper that stands in for the
    // orchestrator. `sleep 60` is portable and exits cleanly on
    // SIGKILL.
    let mut helper = Command::new("sleep")
        .arg("60")
        .spawn()
        .expect("spawn sleep helper as fake orchestrator");
    let helper_pid = helper.id();

    // Reserve with the helper's pid as the liveness binding.
    let reserved: Value = serde_json::from_str(
        &heddle(
            &[
                "agent",
                "reserve",
                "--thread",
                "feature/held",
                "--hold-for-pid",
                &helper_pid.to_string(),
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let session = reserved["reservation"]["session_id"]
        .as_str()
        .unwrap()
        .to_string();

    // The recorded pid in the .toml entry should be the helper, not
    // the heddle CLI process (which has already exited by now).
    let entry_path = main
        .path()
        .join(".heddle")
        .join("agents")
        .join(format!("{session}.toml"));
    let entry_text = std::fs::read_to_string(&entry_path).unwrap();
    assert!(
        entry_text.contains(&format!("pid = {helper_pid}")),
        "reservation must record the held pid, not the CLI pid: {entry_text}"
    );

    // While the helper is alive: a second reserve attempt must see
    // the live owner.
    let live_conflict = expect_json_reserve_failure(
        &[
            "--output",
            "json",
            "agent",
            "reserve",
            "--thread",
            "feature/held",
        ],
        main.path(),
    );
    assert_eq!(live_conflict["kind"], "live_owner");
    assert!(
        live_conflict["error"]
            .as_str()
            .is_some_and(|error| error.contains(&session)),
        "live_owner conflict must point at the held session: {live_conflict}"
    );

    // Kill the helper and reap. SIGKILL is the harshest case — no
    // signal handler runs, no graceful release. The next reservation
    // attempt must succeed via the dead-pid path.
    helper.kill().expect("kill helper");
    let _ = helper.wait();

    let recovered: Value = serde_json::from_str(
        &heddle(
            &["agent", "reserve", "--thread", "feature/held"],
            Some(main.path()),
        )
        .expect("post-SIGKILL reservation must succeed via dead-pid reap"),
    )
    .unwrap();
    let new_session = recovered["reservation"]["session_id"].as_str().unwrap();
    assert_ne!(
        new_session, session,
        "post-reap reservation must mint a fresh session id"
    );
    assert_eq!(recovered["reservation"]["status"], "active");

    // The original entry should be marked Abandoned, not silently
    // overwritten.
    let stale = std::fs::read_to_string(&entry_path).unwrap();
    assert!(
        stale.contains("status = \"abandoned\""),
        "reaped held reservation must record abandoned status: {stale}"
    );
}

/// `heddle agent capture --session SID` and `heddle agent ready
/// --session SID` must verify the caller still owns an Active
/// reservation on the thread. Releasing the reservation should
/// cause subsequent calls to fail with a clear "no longer active"
/// error so an orchestrator can re-reserve before retrying.
#[test]
fn agent_api_capture_and_ready_require_active_session() {
    let main = setup_repo("base.txt", "shared base");

    // Reserve on the main thread so capture/ready have a live owner
    // pointing at a real anchor.
    let reserved_output = heddle_output_with_env(
        &["agent", "reserve", "--thread", "main"],
        Some(main.path()),
        &[
            ("CODEX_THREAD_ID", "thread-agent-api"),
            ("CODEX_MODEL", "gpt-5.3-codex"),
            ("CODEX_REASONING_EFFORT", "high"),
        ],
    )
    .expect("agent reserve with ambient harness env should run");
    assert!(
        reserved_output.status.success(),
        "agent reserve should succeed: {}",
        str::from_utf8(&reserved_output.stderr).unwrap_or("")
    );
    let reserved: Value = serde_json::from_slice(&reserved_output.stdout).unwrap();
    let session = reserved["reservation"]["session_id"]
        .as_str()
        .unwrap()
        .to_string();
    assert_eq!(reserved["reservation"]["harness"], "codex");
    assert_eq!(reserved["reservation"]["provider"], "openai");
    assert_eq!(reserved["reservation"]["model"], "gpt-5.3-codex");
    assert_eq!(reserved["reservation"]["thinking_level"], "high");
    assert_eq!(reserved["reservation"]["probe_source"], "app_protocol");

    // Live session: capture should succeed.
    fs::write(main.path().join("first.txt"), "first").unwrap();
    let capture: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "agent",
                "capture",
                "--session",
                &session,
                "-m",
                "first agent capture",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(capture["intent"], "first agent capture");
    assert!(capture["change_id"].as_str().unwrap().starts_with("hd-"));
    let log: Value = serde_json::from_str(
        &heddle(&["--output", "json", "log", "-n", "1"], Some(main.path())).unwrap(),
    )
    .unwrap();
    assert_eq!(
        log["states"][0]["agent"], "openai/gpt-5.3-codex",
        "agent capture should preserve the reservation's ambient harness model even when the capture process has no model env: {log}"
    );

    // Live session: ready should also succeed.
    let ready: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "agent", "ready", "--session", &session],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(ready["report"]["thread"], "main");

    // Release the reservation; capture and ready must now refuse.
    heddle(
        &[
            "agent",
            "release",
            "--session",
            &session,
            "--status",
            "complete",
        ],
        Some(main.path()),
    )
    .unwrap();

    let capture_err = heddle(
        &[
            "agent",
            "capture",
            "--session",
            &session,
            "-m",
            "after release",
        ],
        Some(main.path()),
    )
    .expect_err("capture after release must fail");
    assert!(
        capture_err.contains("no longer active"),
        "released session should refuse capture: {capture_err}"
    );

    let ready_err = heddle(
        &["agent", "ready", "--session", &session],
        Some(main.path()),
    )
    .expect_err("ready after release must fail");
    assert!(
        ready_err.contains("no longer active"),
        "released session should refuse ready: {ready_err}"
    );

    // Bogus session id likewise rejected.
    let bogus = heddle(
        &["agent", "capture", "--session", "agent-nope", "-m", "nope"],
        Some(main.path()),
    )
    .expect_err("bogus session id must fail");
    assert!(
        bogus.contains("not found"),
        "bogus session should report not found: {bogus}"
    );
}

#[test]
fn thread_captures_lists_granular_history_for_thread() {
    let main = setup_repo("base.txt", "shared base");
    let work = TempDir::new().unwrap();

    heddle(
        &[
            "start",
            "feature/captures",
            "--workspace",
            "materialized",
            "--path",
            work.path().to_str().unwrap(),
        ],
        Some(main.path()),
    )
    .unwrap();
    fs::write(work.path().join("one.txt"), "one").unwrap();
    heddle(&["capture", "-m", "first granular turn"], Some(work.path())).unwrap();
    fs::write(work.path().join("two.txt"), "two").unwrap();
    heddle(
        &["capture", "-m", "second granular turn"],
        Some(work.path()),
    )
    .unwrap();

    let captures: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "thread",
                "captures",
                "feature/captures",
                "--limit",
                "5",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let captures = captures.as_array().unwrap();
    assert_eq!(captures.len(), 2);
    assert_eq!(captures[0]["message"], "second granular turn");
    assert_eq!(captures[1]["message"], "first granular turn");

    // W7b polish: each capture should expose a per-state diff
    // summary so callers don't have to walk parents themselves.
    // The second turn added one file (`two.txt`) over the first;
    // the first turn added one file (`one.txt`) over the seed.
    for capture in captures {
        let summary = capture
            .get("summary")
            .and_then(|s| s.as_object())
            .unwrap_or_else(|| panic!("missing diff summary on capture: {capture}"));
        assert_eq!(
            summary["added"].as_u64(),
            Some(1),
            "each granular turn added exactly one file: {capture}"
        );
        assert_eq!(summary["modified"].as_u64(), Some(0));
        assert_eq!(summary["deleted"].as_u64(), Some(0));
        assert_eq!(summary["total"].as_u64(), Some(1));
    }
}

/// Regression for the YC-demo prep finding: when an agent thread is
/// spawned with `start --agent-provider X --agent-model Y`, every
/// subsequent `heddle capture` from that thread's worktree must tag the
/// captured state with that agent. Before the fix, the thread's actor
/// only showed up in `heddle status` (read from `AgentRegistry`); the
/// capture handler never consulted it, so every state landed with
/// `attribution.agent = None` and `Principal: Unknown`. That broke the
/// "who/what wrote this line" provenance moment in the demo and left
/// `heddle query --attribution --context` with nothing to surface.
#[test]
fn capture_inherits_agent_from_thread() {
    let main = setup_repo("base.txt", "shared base");
    let work = TempDir::new().unwrap();

    heddle(
        &[
            "start",
            "modulo",
            "--workspace",
            "materialized",
            "--path",
            work.path().to_str().unwrap(),
            "--agent-provider",
            "anthropic",
            "--agent-model",
            "claude-sonnet-4-5",
            "--task",
            "Add modulo",
        ],
        Some(main.path()),
    )
    .unwrap();

    fs::write(work.path().join("modulo.rs"), "pub fn modulo() {}").unwrap();
    heddle(
        &["capture", "--intent", "feat: add modulo"],
        Some(work.path()),
    )
    .unwrap();

    let log: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "log", "modulo", "-n", "1"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let head_state = &log["states"][0];
    assert_eq!(
        head_state["intent"].as_str().unwrap(),
        "feat: add modulo",
        "preflight: the captured state should be the head of the thread"
    );

    // `heddle --output json log` flattens the agent to "provider/model".
    // Before the fix this was null on every captured state; after the
    // fix it carries the thread's actor.
    let agent = head_state
        .get("agent")
        .and_then(Value::as_str)
        .unwrap_or("");
    assert_eq!(
        agent, "anthropic/claude-sonnet-4-5",
        "captured state.agent must inherit thread's `--agent-provider/--agent-model` \
         (got {agent:?}, full state: {head_state})"
    );
}

#[test]
fn parallel_agents_visible_from_main_repo() {
    let main = setup_repo("base.txt", "shared base");
    let dir_a = TempDir::new().unwrap();
    let dir_b = TempDir::new().unwrap();

    heddle(
        &[
            "start",
            "feature/auth",
            "--workspace",
            "materialized",
            "--path",
            dir_a.path().to_str().unwrap(),
            "--agent-provider",
            "anthropic",
            "--agent-model",
            "claude-sonnet-4-6",
        ],
        Some(main.path()),
    )
    .unwrap();
    heddle(
        &[
            "start",
            "feature/search",
            "--workspace",
            "materialized",
            "--path",
            dir_b.path().to_str().unwrap(),
            "--agent-provider",
            "anthropic",
            "--agent-model",
            "claude-sonnet-4-6",
        ],
        Some(main.path()),
    )
    .unwrap();

    fs::write(dir_a.path().join("auth.rs"), "auth impl").unwrap();
    fs::write(dir_b.path().join("search.rs"), "search impl").unwrap();

    heddle(&["capture", "-m", "implement auth"], Some(dir_a.path())).unwrap();
    heddle(&["capture", "-m", "implement search"], Some(dir_b.path())).unwrap();

    let auth_log: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "log", "feature/auth"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let search_log: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "log", "feature/search"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();

    assert_eq!(
        auth_log["states"][0]["intent"].as_str().unwrap(),
        "implement auth"
    );
    assert_eq!(
        search_log["states"][0]["intent"].as_str().unwrap(),
        "implement search"
    );

    let thread_list: Value = serde_json::from_str(
        &heddle(&["--output", "json", "thread", "list"], Some(main.path())).unwrap(),
    )
    .unwrap();
    let threads = thread_list["threads"].as_array().unwrap();
    assert!(
        threads
            .iter()
            .any(|thread| thread["name"] == "feature/auth")
    );
    assert!(
        threads
            .iter()
            .any(|thread| thread["name"] == "feature/search")
    );

    assert_eq!(head_track(main.path()), "main");
}

#[test]
fn merge_agent_track_into_main() {
    let main = setup_repo("base.txt", "base");
    let agent_tmp = TempDir::new().unwrap();

    heddle(
        &[
            "start",
            "feature/to-merge",
            "--workspace",
            "materialized",
            "--path",
            agent_tmp.path().to_str().unwrap(),
        ],
        Some(main.path()),
    )
    .unwrap();

    fs::write(agent_tmp.path().join("added.txt"), "new feature").unwrap();
    heddle(&["capture", "-m", "add feature"], Some(agent_tmp.path())).unwrap();

    let result = heddle(&["merge", "feature/to-merge"], Some(main.path()));
    assert!(
        result.is_ok(),
        "merging agent thread into main should succeed: {:?}",
        result.err()
    );

    assert!(
        main.path().join("added.txt").exists(),
        "merged file should appear in main repo"
    );
}

#[test]
fn thread_start_creates_isolated_thread_and_aliases_work() {
    let main = setup_repo("base.txt", "base");

    let start_json = heddle(
        &[
            "--output",
            "json",
            "start",
            "feature/native-cli",
            "--workspace",
            "auto",
            "--agent-provider",
            "anthropic",
            "--agent-model",
            "claude-sonnet-4-6",
        ],
        Some(main.path()),
    )
    .unwrap();
    let started: Value = serde_json::from_str(&start_json).unwrap();
    let thread_path = started["execution_path"].as_str().unwrap();
    let thread = std::path::PathBuf::from(thread_path);
    // Auto-mode resolves to materialized on reflink-capable filesystems
    // (APFS, btrfs, xfs+reflink) and downgrades to solid on ext4 / HFS+ /
    // NTFS so the mode label reflects on-disk truth.
    let expected_mode = if objects::fs_clone::filesystem_supports_reflink(main.path()) {
        "materialized"
    } else {
        "solid"
    };
    assert_eq!(started["thread"]["thread_mode"], expected_mode);
    // Auto-mode threads materialize at a Heddle-managed path, surfaced
    // both as the user-visible `path` and the work-site `execution_path`.
    assert_eq!(started["path"], started["execution_path"]);

    assert!(
        thread.join(".heddle").is_dir(),
        "isolated thread should have .heddle pointer dir"
    );
    assert!(
        thread.join(".heddle").join("objectstore").is_file(),
        "isolated thread should have .heddle/objectstore pointer file"
    );
    assert!(
        thread.join(".heddle").join("HEAD").exists(),
        "isolated thread should have .heddle/HEAD file"
    );

    let thread_info: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "show", "feature/native-cli"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(thread_info["coordination_status"], "clean");
    assert_eq!(thread_info["path"], thread_path);
    assert_eq!(thread_info["execution_path"], thread_path);
    assert_eq!(thread_info["actor"]["provider"], "anthropic");
    assert_eq!(thread_info["thread_mode"], expected_mode);

    std::fs::write(thread.join("native.txt"), "heddle-native").unwrap();
    let capture_json = heddle(
        &[
            "--output",
            "json",
            "capture",
            "-m",
            "native thread snapshot",
        ],
        Some(&thread),
    )
    .unwrap();
    let captured: Value = serde_json::from_str(&capture_json).unwrap();
    assert_eq!(captured["intent"], "native thread snapshot");
    assert_eq!(captured["promotion_suggested"], false);

    let inspect_json = heddle(
        &["--output", "json", "thread", "show", "feature/native-cli"],
        Some(main.path()),
    )
    .unwrap();
    let inspected: Value = serde_json::from_str(&inspect_json).unwrap();
    assert_eq!(inspected["name"], "feature/native-cli");
    assert_eq!(inspected["coordination_status"], "ahead");

    let thread_show_json = heddle(
        &["--output", "json", "thread", "show", "feature/native-cli"],
        Some(main.path()),
    )
    .unwrap();
    let thread_show: Value = serde_json::from_str(&thread_show_json).unwrap();
    assert_eq!(thread_show["name"], "feature/native-cli");
    assert_eq!(thread_show["thread_mode"], expected_mode);
    assert_eq!(thread_show["thread_state"], "active");

    let status_json = heddle(&["--output", "json", "status"], Some(&thread)).unwrap();
    let status: Value = serde_json::from_str(&status_json).unwrap();
    assert_eq!(
        status["recommended_action"].as_str(),
        Some("heddle ready --thread feature/native-cli")
    );

    let ready_json = heddle(
        &[
            "--output",
            "json",
            "ready",
            "--thread",
            "feature/native-cli",
        ],
        Some(main.path()),
    )
    .unwrap();
    let ready: Value = serde_json::from_str(&ready_json).unwrap();
    assert_eq!(ready["thread_state"], "ready");
    assert_eq!(ready["report"]["merge_relation"], "fast_forward");
    assert_eq!(
        ready["report"]["recommended_action"],
        "heddle land --thread feature/native-cli --no-push"
    );

    let thread_show_json = heddle(
        &["--output", "json", "thread", "show", "feature/native-cli"],
        Some(main.path()),
    )
    .unwrap();
    let thread_show: Value = serde_json::from_str(&thread_show_json).unwrap();
    assert_eq!(thread_show["thread_state"], "ready");
    assert_eq!(
        thread_show["recommended_action"].as_str(),
        Some("heddle land --thread feature/native-cli --no-push")
    );

    let actor_list_json = heddle(&["--output", "json", "actor", "list"], Some(main.path()))
        .expect("actor list should succeed");
    let actor_list: Value = serde_json::from_str(&actor_list_json).unwrap();
    let actor_session = actor_list["actors"]
        .as_array()
        .unwrap()
        .iter()
        .find(|actor| actor["thread"].as_str() == Some("feature/native-cli"))
        .and_then(|actor| actor["session_id"].as_str())
        .expect("feature actor should be registered");
    let actor_done_json = heddle(
        &[
            "--output",
            "json",
            "actor",
            "done",
            "--session",
            actor_session,
        ],
        Some(main.path()),
    )
    .expect("actor done should succeed");
    let actor_done: Value = serde_json::from_str(&actor_done_json).unwrap();
    assert_eq!(actor_done["coordination_status"], "merge-ready");
    assert_eq!(
        actor_done["recommended_action"], "heddle land --thread feature/native-cli --no-push",
        "actor completion should keep agents on the canonical land path: {actor_done}"
    );
    assert_eq!(
        actor_done["recommended_action_template"]["argv_template"],
        heddle_argv_json(["land", "--thread", "feature/native-cli", "--no-push"]),
        "{actor_done}"
    );
}

#[test]
fn ready_blocks_stale_or_heavy_impact_threads_and_status_reports_next_step() {
    let main = setup_repo("base.txt", "base");
    let start_json = heddle(
        &[
            "--output",
            "json",
            "start",
            "feature/dep",
            "--workspace",
            "auto",
            "--task",
            "update dependencies",
        ],
        Some(main.path()),
    )
    .unwrap();
    let started: Value = serde_json::from_str(&start_json).unwrap();
    let thread = std::path::PathBuf::from(started["execution_path"].as_str().unwrap());

    fs::write(
        thread.join("Cargo.toml"),
        "[package]\nname='dep'\nversion='0.1.0'\n",
    )
    .unwrap();
    heddle(&["capture", "-m", "touch deps"], Some(&thread)).unwrap();

    let ready_output = heddle_output(
        &["--output", "json", "ready", "--thread", "feature/dep"],
        Some(main.path()),
    )
    .unwrap();
    assert!(
        !ready_output.status.success(),
        "heavy-impact ready should fail closed"
    );
    let ready: Value = serde_json::from_slice(&ready_output.stdout).unwrap();
    assert_eq!(ready["thread_state"], "blocked");
    // No selected action serializes as null, never "" (HeddleCo/heddle#645
    // action-field contract).
    assert!(ready["report"]["recommended_action"].is_null());
    assert!(ready["recommended_action"].is_null());

    let reviewed: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "resolve", "feature/dep"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(reviewed["status"], "completed");
    assert_eq!(
        reviewed["message"].as_str(),
        Some("Thread manual review recorded")
    );
    assert!(
        reviewed["warnings"]
            .as_array()
            .is_some_and(|warnings| warnings.iter().any(|warning| warning
                .as_str()
                .unwrap_or_default()
                .contains("Heavy-impact change"))),
        "thread resolve should preserve what was manually reviewed: {reviewed}"
    );

    std::fs::write(main.path().join("base.txt"), "base changed").unwrap();
    heddle(&["capture", "-m", "main changed"], Some(main.path())).unwrap();

    let status_json = heddle(&["--output", "json", "status"], Some(&thread)).unwrap();
    let status: Value = serde_json::from_str(&status_json).unwrap();
    assert_eq!(status["thread_health"], "blocked");
    assert_eq!(
        status["recommended_action"].as_str(),
        Some("heddle sync --thread feature/dep")
    );

    let thread_refresh_status = heddle(
        &["--output", "json", "thread", "show", "feature/dep"],
        Some(main.path()),
    )
    .unwrap();
    let thread_show: Value = serde_json::from_str(&thread_refresh_status).unwrap();
    assert_eq!(thread_show["thread_state"], "blocked");
}

#[test]
fn genuine_blocked_thread_surfaces_coordination_axis_in_long_status() {
    // heddle#276 r3 / cid 3327990627. A *genuine* inter-thread block —
    // `heddle ready` failing closed persists `ThreadState::Blocked`, which
    // `build_thread_view` maps to `CoordinationStatus::Blocked` — must
    // surface on the coordination axis of the long status view. r2 masked
    // ANY Blocked whenever `thread_health` was non-clean (here it is
    // `blocked`), so the real coordination block was hidden as "work in
    // progress" and the verdict reason named only checkout health. The
    // provenance-keyed mask masks only the trust/health re-encoding, never
    // a genuine `build_thread_view` Blocked, so the block stays visible.
    let main = setup_repo("base.txt", "base");
    let started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/dep",
                "--workspace",
                "auto",
                "--task",
                "update dependencies",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let thread = std::path::PathBuf::from(started["execution_path"].as_str().unwrap());

    fs::write(
        thread.join("Cargo.toml"),
        "[package]\nname='dep'\nversion='0.1.0'\n",
    )
    .unwrap();
    heddle(&["capture", "-m", "touch deps"], Some(&thread)).unwrap();

    // Heavy-impact `ready` fails closed and persists ThreadState::Blocked.
    let ready_output = heddle_output(
        &["--output", "json", "ready", "--thread", "feature/dep"],
        Some(main.path()),
    )
    .unwrap();
    assert!(
        !ready_output.status.success(),
        "heavy-impact ready should fail closed and block the thread"
    );

    // Sanity: the worktree is still clean/verified, yet the thread is
    // genuinely Blocked — exactly the case r2 mis-masked.
    let status_json: Value =
        serde_json::from_str(&heddle(&["--output", "json", "status"], Some(&thread)).unwrap())
            .unwrap();
    assert_eq!(status_json["thread_state"], "blocked");
    assert_eq!(status_json["coordination_status"], "blocked");

    // Default long view: the verdict reason must NAME the coordination
    // block (r2 said only "checkout health needs attention").
    let text = heddle(&["--output", "text", "status"], Some(&thread)).unwrap();
    assert!(
        text.contains("thread coordination"),
        "default verdict reason must name the genuine coordination block, not hide it behind health: {text}"
    );

    // Verbose: the coordination axis must read "blocked", not the
    // health-only "work in progress" mask.
    let verbose = heddle(&["--output", "text", "-v", "status"], Some(&thread)).unwrap();
    assert!(
        verbose.contains("Coordination: blocked"),
        "a genuine inter-thread block must surface on the coordination axis: {verbose}"
    );
    assert!(
        !verbose.contains("Coordination: work in progress"),
        "a genuine inter-thread block must not be masked as work in progress: {verbose}"
    );
}

#[test]
fn sync_refreshes_stale_thread_when_replay_is_clean() {
    let main = setup_repo("base.txt", "base");
    let started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/sync-me",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let thread = std::path::PathBuf::from(started["execution_path"].as_str().unwrap());

    std::fs::write(thread.join("feature.txt"), "feature work").unwrap();
    heddle(&["capture", "-m", "feature work"], Some(&thread)).unwrap();

    std::fs::write(main.path().join("base.txt"), "base updated").unwrap();
    heddle(&["capture", "-m", "advance main"], Some(main.path())).unwrap();

    let sync_json = heddle(
        &["--output", "json", "sync", "--thread", "feature/sync-me"],
        Some(main.path()),
    )
    .unwrap();
    let sync: Value = serde_json::from_str(&sync_json).unwrap();
    assert_eq!(sync["status"], "refreshed");
    assert_eq!(sync["chosen_path"], "refresh");

    let thread_show: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "show", "feature/sync-me"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(thread_show["freshness"], "current");
    assert_eq!(
        thread_show["integration_policy_result"]["status"],
        "current"
    );
}

#[test]
fn land_auto_captures_and_merges_clean_thread() {
    let main = setup_repo("base.txt", "base");
    let started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/land-it",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let thread = std::path::PathBuf::from(started["execution_path"].as_str().unwrap());

    std::fs::write(thread.join("land.txt"), "land me").unwrap();

    let ship_json = heddle(
        &["--output", "json", "land", "--thread", "feature/land-it"],
        Some(main.path()),
    )
    .unwrap();
    let landed: Value = serde_json::from_str(&ship_json).unwrap();
    assert_eq!(landed["status"], "landed");
    assert_eq!(landed["captured"], true);
    assert_eq!(landed["integrated"], true);
    assert!(main.path().join("land.txt").exists());

    let thread_show: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "show", "feature/land-it"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(thread_show["thread_state"], "merged");
    assert_eq!(
        thread_show["integration_policy_result"]["status"],
        "auto_integrated"
    );

    let actor_show = heddle_output(&["--output", "json", "actor", "show"], Some(main.path()))
        .expect("invoke actor show after land");
    assert!(
        !actor_show.status.success(),
        "actor show should not select the merged actor implicitly after land"
    );
    let stderr = str::from_utf8(&actor_show.stderr).unwrap_or("");
    let envelope: Value = serde_json::from_str(stderr.trim())
        .unwrap_or_else(|err| panic!("actor show failure should be JSON: {err}: {stderr}"));
    assert_eq!(envelope["kind"], "no_active_actor");
    assert_eq!(envelope["primary_command"], "heddle actor list");
    assert!(
        envelope["hint"]
            .as_str()
            .is_some_and(|hint| hint.contains("landed") && hint.contains("session id")),
        "actor show no-active advice should explain the post-land transition: {envelope}"
    );
}

/// `heddle delegate` with per-task `task:provider:model` syntax —
/// the YC-demo opener primitive. Three children, three different
/// agents, one command. Pre-extension, every child shared the same
/// `--agent-provider/--agent-model`, which made it impossible to race
/// distinct agents in a single invocation.
#[test]
fn delegate_assigns_per_task_agents_when_spec_includes_them() {
    let main = setup_repo("base.txt", "base");
    let parent_started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/race",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let parent_path = std::path::PathBuf::from(parent_started["execution_path"].as_str().unwrap());
    for (name, provider, model) in [
        (
            "feature/race/approach-anthropic",
            "anthropic",
            "claude-sonnet-4-5",
        ),
        ("feature/race/approach-openai", "openai", "gpt-5-codex"),
        (
            "feature/race/approach-opencode",
            "opencode",
            "opencode-default",
        ),
    ] {
        heddle(
            &[
                "--output",
                "json",
                "start",
                name,
                "--parent-thread",
                "feature/race",
                "--workspace",
                "materialized",
                "--agent-provider",
                provider,
                "--agent-model",
                model,
            ],
            Some(&parent_path),
        )
        .unwrap();
    }

    // Each child must end up with its OWN agent record, not the same
    // one. Verify by reading thread show for each child and asserting
    // its `actor` line carries the right provider/model.
    let triples = [
        ("approach-anthropic", "anthropic", "claude-sonnet-4-5"),
        ("approach-openai", "openai", "gpt-5-codex"),
        ("approach-opencode", "opencode", "opencode-default"),
    ];
    for (slug, expected_provider, expected_model) in triples {
        let full_name = format!("feature/race/{slug}");
        let show: Value = serde_json::from_str(
            &heddle(
                &["--output", "json", "thread", "show", &full_name],
                Some(main.path()),
            )
            .unwrap(),
        )
        .unwrap();
        // `thread show --output json` renders actor as { provider, model }.
        let actor = &show["actor"];
        assert_eq!(
            actor["provider"].as_str().unwrap_or(""),
            expected_provider,
            "{full_name}: provider mismatch (full show: {show})"
        );
        assert_eq!(
            actor["model"].as_str().unwrap_or(""),
            expected_model,
            "{full_name}: model mismatch (full show: {show})"
        );
    }

    // Also assert siblings see each other in the workspace view.
    let show_first: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "thread",
                "show",
                "feature/race/approach-anthropic",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let siblings = show_first["sibling_threads"].as_array().unwrap();
    let sibling_names: Vec<&str> = siblings.iter().filter_map(|v| v.as_str()).collect();
    assert!(
        sibling_names.contains(&"feature/race/approach-openai"),
        "anthropic child should see openai sibling (got {sibling_names:?})"
    );
    assert!(
        sibling_names.contains(&"feature/race/approach-opencode"),
        "anthropic child should see opencode sibling (got {sibling_names:?})"
    );
}

#[test]
fn delegate_creates_child_threads_with_parent_relationship() {
    let main = setup_repo("base.txt", "base");
    let parent_started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/orchestrator",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let parent_thread =
        std::path::PathBuf::from(parent_started["execution_path"].as_str().unwrap());

    for child in ["parser", "tests"] {
        let child_name = format!("feature/orchestrator/{child}");
        heddle(
            &[
                "--output",
                "json",
                "start",
                &child_name,
                "--parent-thread",
                "feature/orchestrator",
                "--task",
                child,
            ],
            Some(&parent_thread),
        )
        .unwrap();
    }
    let delegated = serde_json::json!({
        "delegated": [
            { "name": "feature/orchestrator/parser" },
            { "name": "feature/orchestrator/tests" }
        ]
    });
    let children = delegated["delegated"].as_array().unwrap();
    assert_eq!(children.len(), 2);
    assert!(
        children
            .iter()
            .any(|child| child["name"] == "feature/orchestrator/parser")
    );
    assert!(
        children
            .iter()
            .any(|child| child["name"] == "feature/orchestrator/tests")
    );

    let parser_thread: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "thread",
                "show",
                "feature/orchestrator/parser",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(parser_thread["parent_thread"], "feature/orchestrator");
    assert_eq!(parser_thread["task"], "parser");
}

#[test]
fn undo_is_scoped_to_the_current_thread() {
    let main = setup_repo("base.txt", "shared base");

    let auth_thread: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/auth",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let search_thread: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/search",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();

    let auth_path = std::path::PathBuf::from(auth_thread["execution_path"].as_str().unwrap());
    let search_path = std::path::PathBuf::from(search_thread["execution_path"].as_str().unwrap());

    fs::write(auth_path.join("auth.rs"), "auth impl").unwrap();
    fs::write(search_path.join("search.rs"), "search impl").unwrap();

    let auth_snapshot: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "capture", "-m", "auth"],
            Some(&auth_path),
        )
        .unwrap(),
    )
    .unwrap();
    let search_snapshot: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "capture", "-m", "search"],
            Some(&search_path),
        )
        .unwrap(),
    )
    .unwrap();

    heddle(&["undo"], Some(&auth_path)).unwrap();

    assert!(
        !auth_path.join("auth.rs").exists(),
        "auth thread should rewind its own worktree"
    );
    assert!(
        search_path.join("search.rs").exists(),
        "search thread should keep its worktree state"
    );

    let auth_thread: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "show", "feature/auth"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let search_thread: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "show", "feature/search"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();

    assert_ne!(
        auth_thread["current_state"].as_str().unwrap(),
        auth_snapshot["change_id"].as_str().unwrap()
    );
    assert_eq!(
        search_thread["current_state"].as_str().unwrap(),
        search_snapshot["change_id"].as_str().unwrap()
    );

    heddle(&["undo", "--redo"], Some(&auth_path)).unwrap();
    assert!(
        auth_path.join("auth.rs").exists(),
        "redo should restore the auth thread state"
    );
}

#[test]
fn thread_and_workspace_json_match_dirty_current_checkout() {
    let main = setup_repo("base.txt", "base");
    let start_json = heddle(
        &[
            "--output",
            "json",
            "start",
            "feature/dirty-json",
            "--workspace",
            "auto",
        ],
        Some(main.path()),
    )
    .unwrap();
    let started: Value = serde_json::from_str(&start_json).unwrap();
    let thread = std::path::PathBuf::from(started["execution_path"].as_str().unwrap());
    fs::write(thread.join("README.md"), "dirty before ready\n").unwrap();

    let threads: Value = serde_json::from_str(
        &heddle(&["--output", "json", "thread", "list"], Some(&thread)).unwrap(),
    )
    .unwrap();
    assert_eq!(threads["current"].as_str(), Some("feature/dirty-json"));
    let current_thread = threads["threads"]
        .as_array()
        .unwrap()
        .iter()
        .find(|thread| thread["is_current"] == true)
        .expect("thread list should mark the current checkout");
    assert!(
        current_thread["changed_paths"]
            .as_array()
            .unwrap()
            .iter()
            .any(|path| path.as_str() == Some("README.md")),
        "thread list should include live dirty paths for the current checkout: {threads}"
    );
}

#[test]
fn lightweight_thread_capture_marks_heavy_impact_and_merge_preview_reports_it() {
    let main = setup_repo("base.txt", "base");

    let start_json = heddle(
        &[
            "--output",
            "json",
            "start",
            "feature/deps",
            "--workspace",
            "auto",
            "--task",
            "update dependencies",
        ],
        Some(main.path()),
    )
    .unwrap();
    let started: Value = serde_json::from_str(&start_json).unwrap();
    let thread = std::path::PathBuf::from(started["execution_path"].as_str().unwrap());

    fs::write(
        thread.join("Cargo.toml"),
        "[package]\nname='demo'\nversion='0.2.0'\n",
    )
    .unwrap();
    let capture_json = heddle(
        &["--output", "json", "capture", "-m", "dependency update"],
        Some(&thread),
    )
    .unwrap();
    let captured: Value = serde_json::from_str(&capture_json).unwrap();
    assert_eq!(captured["promotion_suggested"], true);
    assert!(
        captured["heavy_impact_paths"]
            .as_array()
            .unwrap()
            .iter()
            .any(|value| value.as_str() == Some("Cargo.toml"))
    );

    let preview_json = heddle(
        &["--output", "json", "merge", "feature/deps", "--preview"],
        Some(main.path()),
    )
    .unwrap();
    let preview: Value = serde_json::from_str(&preview_json).unwrap();
    assert_eq!(preview["preview_only"], true);
    assert_eq!(preview["promotion_suggested"], true);
    assert_eq!(preview["heavy_impact_paths"][0], "Cargo.toml");
    assert_eq!(
        preview["recommended_action"].as_str(),
        None,
        "merge preview should not recommend a breadcrumb while heavy-impact review is still blocked: {preview}"
    );
}

#[test]
fn thread_promote_materializes_visible_checkout_without_changing_thread_identity() {
    let main = setup_repo("base.txt", "base");

    let start_json = heddle(
        &[
            "--output",
            "json",
            "start",
            "feature/promote",
            "--workspace",
            "auto",
            "--task",
            "prepare visible thread",
        ],
        Some(main.path()),
    )
    .unwrap();
    let started: Value = serde_json::from_str(&start_json).unwrap();
    let visible = TempDir::new().unwrap();

    let promote_json = heddle(
        &[
            "--output",
            "json",
            "thread",
            "promote",
            "feature/promote",
            "--path",
            visible.path().to_str().unwrap(),
        ],
        Some(main.path()),
    )
    .unwrap();
    let promoted: Value = serde_json::from_str(&promote_json).unwrap();
    assert_eq!(promoted["thread"]["id"], "feature/promote");
    assert_eq!(promoted["thread"]["mode"], "solid");
    assert_eq!(
        canonical_path_string(std::path::Path::new(
            promoted["thread"]["materialized_path"].as_str().unwrap()
        )),
        canonical_path_string(visible.path())
    );
    assert!(visible.path().join(".heddle").is_dir());
    assert!(visible.path().join(".heddle").join("objectstore").is_file());
    assert!(visible.path().join(".heddle").join("HEAD").exists());
    assert_eq!(started["thread"]["name"], "feature/promote");
}

#[test]
fn status_watch_emits_initial_snapshot_for_local_repos() {
    let main = setup_repo("base.txt", "base");

    let output = heddle(
        &[
            "--output",
            "json",
            "status",
            "--watch",
            "--watch-iterations",
            "1",
            "--watch-interval-ms",
            "5",
        ],
        Some(main.path()),
    )
    .unwrap();
    let status: Value = serde_json::from_str(&output).unwrap();
    assert_eq!(status["thread"], "main");
}

#[test]
fn status_watch_bounded_runs_are_transcript_friendly() {
    let main = setup_repo("base.txt", "base");

    let output = heddle(
        &[
            "--output",
            "text",
            "status",
            "--watch",
            "--watch-iterations",
            "1",
            "--watch-interval-ms",
            "5",
        ],
        Some(main.path()),
    )
    .unwrap();
    assert!(
        !output.contains("\x1B[2J") && !output.contains("\x1B[H"),
        "bounded watch output should not clear the screen in saved transcripts: {output:?}"
    );
    assert!(
        output.contains("Status snapshot 1 of 1"),
        "bounded watch output should identify the captured frame: {output}"
    );
}

#[test]
fn thread_show_watch_emits_initial_snapshot_for_local_repos() {
    let main = setup_repo("base.txt", "base");
    heddle(
        &["start", "feature/watch-thread", "--workspace", "auto"],
        Some(main.path()),
    )
    .unwrap();

    let output = heddle(
        &[
            "--output",
            "json",
            "thread",
            "show",
            "feature/watch-thread",
            "--watch",
            "--watch-iterations",
            "1",
            "--watch-interval-ms",
            "5",
        ],
        Some(main.path()),
    )
    .unwrap();
    let thread: Value = serde_json::from_str(&output).unwrap();
    assert_eq!(thread["name"], "feature/watch-thread");
}

#[test]
fn thread_list_shows_current_stacked_and_parallel_threads() {
    let main = setup_repo("base.txt", "base");
    let parent_started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/orchestrator",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let parent_path = std::path::PathBuf::from(parent_started["execution_path"].as_str().unwrap());
    heddle(
        &[
            "--output",
            "json",
            "start",
            "feature/orchestrator/parser",
            "--parent-thread",
            "feature/orchestrator",
            "--task",
            "parser",
        ],
        Some(&parent_path),
    )
    .unwrap();
    heddle(
        &["start", "feature/search", "--workspace", "auto"],
        Some(main.path()),
    )
    .unwrap();

    let output = heddle(&["--output", "json", "thread", "list"], Some(&parent_path)).unwrap();
    let threads: Value = serde_json::from_str(&output).unwrap();
    assert_eq!(threads["current"], "feature/orchestrator");
    let names: Vec<&str> = threads["threads"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|thread| thread["name"].as_str())
        .collect();
    assert!(names.contains(&"feature/orchestrator/parser"));
    assert!(names.contains(&"feature/search"));
}

#[test]
fn capture_split_moves_selected_dirty_paths_into_target_thread() {
    let main = setup_repo("base.txt", "base");
    let source_started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/source",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let target_started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/target",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let source_path = std::path::PathBuf::from(source_started["execution_path"].as_str().unwrap());
    let target_path = std::path::PathBuf::from(target_started["execution_path"].as_str().unwrap());

    fs::write(source_path.join("auth.rs"), "auth impl").unwrap();
    fs::write(source_path.join("search.rs"), "search impl").unwrap();

    let split: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "capture",
                "--split",
                "--into",
                "feature/target",
                "--path",
                "auth.rs",
                "-m",
                "split auth",
            ],
            Some(&source_path),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(split["to_thread"], "feature/target");
    assert!(!source_path.join("auth.rs").exists());
    assert!(source_path.join("search.rs").exists());
    assert!(target_path.join("auth.rs").exists());
}

#[test]
fn thread_move_reassigns_selected_captured_paths_between_threads() {
    let main = setup_repo("base.txt", "base");
    let source_started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/source",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let target_started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/target",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let source_path = std::path::PathBuf::from(source_started["execution_path"].as_str().unwrap());
    let target_path = std::path::PathBuf::from(target_started["execution_path"].as_str().unwrap());

    fs::write(source_path.join("feature.rs"), "moved work").unwrap();
    heddle(&["capture", "-m", "source work"], Some(&source_path)).unwrap();

    let moved: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "thread",
                "move",
                "feature/source",
                "feature/target",
                "--path",
                "feature.rs",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(moved["from_thread"], "feature/source");
    assert_eq!(moved["to_thread"], "feature/target");
    assert!(!source_path.join("feature.rs").exists());
    assert!(target_path.join("feature.rs").exists());
}

#[test]
fn thread_absorb_merges_child_thread_into_parent_workspace() {
    let main = setup_repo("base.txt", "base");
    let parent_started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/orchestrator",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let parent_path = std::path::PathBuf::from(parent_started["execution_path"].as_str().unwrap());
    let child_name = "feature/orchestrator/parser".to_string();
    heddle(
        &[
            "--output",
            "json",
            "start",
            &child_name,
            "--parent-thread",
            "feature/orchestrator",
            "--task",
            "parser",
        ],
        Some(&parent_path),
    )
    .unwrap();
    let child_thread: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "show", &child_name],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let child_path = std::path::PathBuf::from(child_thread["execution_path"].as_str().unwrap());

    fs::write(child_path.join("parser.rs"), "parser impl").unwrap();
    heddle(&["capture", "-m", "parser work"], Some(&child_path)).unwrap();

    let absorbed: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "absorb", &child_name],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(absorbed["into"], "feature/orchestrator");
    assert!(parent_path.join("parser.rs").exists());
}

#[test]
fn thread_resolve_refreshes_clean_stale_threads() {
    let main = setup_repo("base.txt", "base");
    let started: Value = serde_json::from_str(
        &heddle(
            &[
                "--output",
                "json",
                "start",
                "feature/stale",
                "--workspace",
                "auto",
            ],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    let thread_path = std::path::PathBuf::from(started["execution_path"].as_str().unwrap());

    std::fs::write(thread_path.join("feature.txt"), "feature work").unwrap();
    heddle(&["capture", "-m", "feature work"], Some(&thread_path)).unwrap();
    std::fs::write(main.path().join("base.txt"), "base updated").unwrap();
    heddle(&["capture", "-m", "advance main"], Some(main.path())).unwrap();

    let resolved: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "resolve", "feature/stale"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    // `thread resolve` reports `synced` for the clean-fast-forward path
    // it just executed; `thread show` below confirms the freshness flip.
    assert_eq!(resolved["status"], "synced");

    let thread_show: Value = serde_json::from_str(
        &heddle(
            &["--output", "json", "thread", "show", "feature/stale"],
            Some(main.path()),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(thread_show["freshness"], "current");
}

/// Regression for the YC-demo finding: `heddle log <child-thread>` for
/// a thread spawned via `start` + `delegate` used to surface a phantom
/// state with `Principal: Unknown <unknown@example.com>` and no intent.
/// The phantom was the synthetic empty-tree genesis stamped by
/// `seed_default_thread` at `heddle init` time, before the user's
/// `.heddle/config.toml` principal was written.
///
/// After the fix:
/// - The seed state carries a stable `Heddle <init@heddle>` system
///   principal (never `Unknown`).
/// - User-facing `log` output filters the synthetic root entirely, so
///   every state shown to the user has a real principal.
///
/// This test mirrors the demo's flow: `init`, write `.heddle/config.toml`
/// with a principal, snapshot, start a parent thread, delegate a child,
/// snapshot the child, then walk every reachable thread's log.
#[test]
fn log_never_surfaces_unknown_principal_after_init() {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).unwrap();

    // The test invocation inherits the test helper's principal env
    // (`HEDDLE_PRINCIPAL_NAME` / `_EMAIL`), which takes precedence
    // over the synthetic Unknown fallback. The historical regression
    // this test pins was that the seed-root state stamped during
    // `init` carried `Unknown <unknown@example.com>` even when a
    // principal was available — verify every reachable log state
    // carries a real principal and never the Unknown fallback.
    let principal_name = "Heddle Test";
    let principal_email = "test@heddle.dev";

    fs::write(temp.path().join("base.txt"), "base").unwrap();
    heddle(
        &["capture", "-m", "Adam-authored initial commit"],
        Some(temp.path()),
    )
    .unwrap();

    heddle(
        &["start", "feature/parent", "--workspace", "auto"],
        Some(temp.path()),
    )
    .unwrap();

    // Walk every reachable thread's full log and assert no Unknown
    // principal — and, while we're here, no `Heddle <init@heddle>`
    // system principal leaks into user-facing output either.
    for thread in &["main", "feature/parent"] {
        let log_json: Value = serde_json::from_str(
            &heddle(
                &["--output", "json", "log", thread, "-n", "20"],
                Some(temp.path()),
            )
            .unwrap(),
        )
        .unwrap();
        let states = log_json["states"]
            .as_array()
            .unwrap_or_else(|| panic!("{thread} log missing states array"));
        assert!(
            !states.is_empty(),
            "{thread} should have at least one state in its log"
        );
        for state in states {
            let principal = state["principal"].as_str().unwrap_or("");
            assert!(
                !principal.contains("Unknown"),
                "every state on every thread must have a real principal — \
                 got: thread={thread}, state={state}"
            );
            assert!(
                !principal.contains("init@heddle"),
                "synthetic seed principal must be filtered from user-facing log — \
                 got: thread={thread}, state={state}"
            );
            assert!(
                principal.contains(principal_name) && principal.contains(principal_email),
                "every state on every thread must inherit the configured principal — \
                 got: thread={thread}, state={state}"
            );
        }
    }
}

// heddle#464 bug 1: when a materialized thread's recorded worktree dir is
// deleted out of band, `land --thread` refuses with `thread_worktree_missing`.
// The recovery used to point at `heddle start <thread> --path <path>`, which
// can never succeed (the thread still holds an active reservation, so `start`
// returns `active_thread_reservation`), and the JSON `recovery_commands` list
// was only the same `land` that just failed — a dead loop. The fix points the
// recovery at `heddle switch <thread>`, which rebuilds the dedicated worktree at
// the recorded path so the follow-up `land` succeeds.
#[test]
fn land_worktree_missing_recovery_points_at_switch_not_failing_loop() {
    let main = setup_repo("hello.txt", "hello world");

    let thread_dir = TempDir::new().unwrap();
    let thread_path = thread_dir.path();

    heddle(
        &[
            "start",
            "feature/gone",
            "--workspace",
            "materialized",
            "--path",
            thread_path.to_str().unwrap(),
        ],
        Some(main.path()),
    )
    .expect("start materialized thread");

    // Capture some work inside the thread so it has a landable state.
    fs::write(thread_path.join("hello.txt"), "agent edits").unwrap();
    heddle(&["capture", "-m", "agent work"], Some(thread_path)).expect("capture in thread");

    // Delete the worktree out of band — the ref + record survive, only the
    // checkout dir is gone.
    fs::remove_dir_all(thread_path).expect("remove thread worktree dir");

    let output = heddle_output(
        &[
            "--output",
            "json",
            "land",
            "--thread",
            "feature/gone",
            "--no-push",
        ],
        Some(main.path()),
    )
    .expect("land invocation runs");
    assert!(
        !output.status.success(),
        "land must refuse when the thread worktree is missing"
    );
    let stderr = str::from_utf8(&output.stderr).unwrap_or("");
    let envelope: Value = serde_json::from_str(stderr.trim()).unwrap_or_else(|e| {
        panic!("worktree-missing refusal must emit a JSON envelope: {e}\n{stderr}")
    });

    assert_eq!(envelope["kind"], "thread_worktree_missing");
    let primary = envelope["primary_command"].as_str().unwrap_or_default();
    assert_eq!(
        primary, "heddle switch feature/gone",
        "primary recovery must rematerialize the existing thread via switch"
    );

    let recovery: Vec<String> = envelope["recovery_commands"]
        .as_array()
        .expect("recovery_commands array present")
        .iter()
        .map(|v| v.as_str().unwrap_or_default().to_string())
        .collect();
    assert!(
        recovery.contains(&"heddle switch feature/gone".to_string()),
        "recovery_commands must include the rematerialize command: {recovery:?}"
    );
    let land_command = "heddle land --thread feature/gone --no-push".to_string();
    assert!(
        recovery != vec![land_command.clone()],
        "recovery_commands must not be just the failing land command (the old dead loop): {recovery:?}"
    );
    // The switch must come before the land retry so the operator rebuilds the
    // checkout first.
    let switch_idx = recovery
        .iter()
        .position(|c| c == "heddle switch feature/gone");
    let land_idx = recovery.iter().position(|c| c == &land_command);
    if let (Some(s), Some(l)) = (switch_idx, land_idx) {
        assert!(s < l, "switch must precede the land retry: {recovery:?}");
    }
}