galdr 0.16.1

Record & Replay for agent skills — capture a session's tool calls and distill them into a reproducible skill. Local-first.
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
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
//! End-to-end tests that drive the compiled `galdr` binary.
//!
//! Each test runs in its own temporary `HOME`, so `~/.galdr` and `~/.agents` are
//! isolated and the tests are hermetic and parallel-safe. The binary path comes
//! from `CARGO_BIN_EXE_galdr`, which cargo sets for integration tests.

use std::io::{Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_galdr")
}

/// An isolated `HOME` with a `galdr` command builder.
struct Sandbox {
    home: tempfile::TempDir,
}

impl Sandbox {
    fn new() -> Self {
        Self {
            home: tempfile::tempdir().unwrap(),
        }
    }

    fn home(&self) -> &Path {
        self.home.path()
    }

    fn cmd(&self) -> Command {
        let mut command = Command::new(bin());
        command.env("HOME", self.home.path());
        command
    }

    fn run(&self, args: &[&str]) -> Output {
        self.cmd().args(args).output().unwrap()
    }

    /// Feeds a PostToolUse event to the sensor on stdin.
    fn hook(&self, json: &str, fail: bool) -> Output {
        let mut command = self.cmd();
        command.arg("hook");
        if fail {
            command.env("GALDR_HOOK_FAIL", "1");
        }
        let mut child = command
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(json.as_bytes())
            .unwrap();
        child.wait_with_output().unwrap()
    }

    fn span_lines(&self, rec_id: &str) -> usize {
        let path = self
            .home()
            .join(".galdr/spans")
            .join(format!("{rec_id}.jsonl"));
        std::fs::read_to_string(path)
            .map(|s| s.lines().filter(|l| !l.trim().is_empty()).count())
            .unwrap_or(0)
    }

    /// The rec_id of the sole in-progress recording (read from its `active.d/` flag,
    /// since `recordings/` is only written on stop). Panics if not exactly one is
    /// active — the callers all record a single recording.
    fn active_rec_id(&self) -> String {
        let dir = self.home().join(".galdr/active.d");
        let mut ids: Vec<String> = std::fs::read_dir(&dir)
            .unwrap()
            .flatten()
            .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("json"))
            .map(|e| {
                let raw = std::fs::read_to_string(e.path()).unwrap();
                let value: serde_json::Value = serde_json::from_str(&raw).unwrap();
                value["rec_id"].as_str().unwrap().to_string()
            })
            .collect();
        assert_eq!(ids.len(), 1, "expected exactly one active recording");
        ids.pop().unwrap()
    }

    /// The rec_id of the active recording with the given name (for concurrency tests
    /// where several recordings are active at once).
    fn active_rec_id_by_name(&self, name: &str) -> String {
        let dir = self.home().join(".galdr/active.d");
        for entry in std::fs::read_dir(&dir).unwrap().flatten() {
            if entry.path().extension().and_then(|x| x.to_str()) != Some("json") {
                continue;
            }
            let raw = std::fs::read_to_string(entry.path()).unwrap();
            let value: serde_json::Value = serde_json::from_str(&raw).unwrap();
            if value["name"].as_str() == Some(name) {
                return value["rec_id"].as_str().unwrap().to_string();
            }
        }
        panic!("no active recording named {name}");
    }

    fn recording_ids(&self) -> Vec<String> {
        let dir = self.home().join(".galdr/recordings");
        let mut ids: Vec<String> = std::fs::read_dir(dir)
            .map(|entries| {
                entries
                    .flatten()
                    .filter_map(|entry| {
                        let path = entry.path();
                        if path.extension()?.to_str()? == "json" {
                            Some(path.file_stem()?.to_str()?.to_string())
                        } else {
                            None
                        }
                    })
                    .collect()
            })
            .unwrap_or_default();
        ids.sort();
        ids
    }

    /// Records a sequence of events under `name` and returns the rec_id.
    fn record(&self, name: &str, events: &[&str]) -> String {
        let before = self.recording_ids();
        assert!(self.run(&["rec", "start", name]).status.success());
        for event in events {
            assert!(self.hook(event, false).status.success());
        }
        assert!(self.run(&["rec", "stop"]).status.success());
        self.recording_ids()
            .into_iter()
            .find(|id| !before.contains(id))
            .expect("a new recording id")
    }

    fn skill_md(&self, skill_name: &str) -> String {
        let path = self
            .home()
            .join(".agents/skills")
            .join(skill_name)
            .join("SKILL.md");
        std::fs::read_to_string(path).unwrap()
    }
}

/// Writes a crates.io sparse-index fixture (one NDJSON line per entry) and returns
/// its path, for driving `galdr upgrade`/`doctor` hermetically via `GALDR_INDEX_FILE`
/// — no network, deterministic across machines.
fn write_index_fixture(sb: &Sandbox, entries: &[(&str, bool)]) -> PathBuf {
    let path = sb.home().join("index.json");
    let mut body = String::new();
    for (vers, yanked) in entries {
        body.push_str(&format!(
            r#"{{"name":"galdr","vers":"{vers}","deps":[],"cksum":"x","features":{{}},"yanked":{yanked}}}"#
        ));
        body.push('\n');
    }
    std::fs::write(&path, body).unwrap();
    path
}

/// Writes an always-succeeding `launchctl` stand-in that appends its arguments to a
/// log file, and returns `(script_path, log_path)`. Point `GALDR_LAUNCHCTL` at the
/// script so `galdr daemon install`/`status`/`uninstall` exercise the real command
/// wiring (arg construction, exit-code handling) without touching the live launchd.
#[cfg(target_os = "macos")]
fn fake_launchctl(sb: &Sandbox) -> (PathBuf, PathBuf) {
    use std::os::unix::fs::PermissionsExt;
    let log = sb.home().join("launchctl.log");
    let script = sb.home().join("fake-launchctl.sh");
    std::fs::write(
        &script,
        format!(
            "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nexit 0\n",
            log.display()
        ),
    )
    .unwrap();
    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    (script, log)
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

const BASH_STATUS: &str =
    r#"{"tool_name":"Bash","tool_input":{"command":"git status"},"tool_response":{}}"#;

fn write_human_recording(sb: &Sandbox, rec_id: &str, name: &str, value: serde_json::Value) {
    let root = sb.home().join(".galdr");
    std::fs::create_dir_all(root.join("spans")).unwrap();
    std::fs::create_dir_all(root.join("recordings")).unwrap();
    let event = serde_json::json!({
        "ts": "2026-06-30T00:00:00Z",
        "seq": 0,
        "tool_name": "human.browser.input",
        "tool_input": {},
        "tool_response": {},
        "event_kind": "human",
        "human": {
            "source": {
                "kind": "browser",
                "url": "https://example.test/issues/new",
                "title": "New issue"
            },
            "action": "human.browser.input",
            "target": {
                "primary": {
                    "kind": "label",
                    "value": "Issue title"
                },
                "label": "Issue title"
            },
            "value": value,
            "verification_hint": "Confirm the issue was saved."
        }
    });
    std::fs::write(
        root.join("spans").join(format!("{rec_id}.jsonl")),
        format!("{}\n", serde_json::to_string(&event).unwrap()),
    )
    .unwrap();
    let recording = serde_json::json!({
        "rec_id": rec_id,
        "name": name,
        "started_at": "2026-06-30T00:00:00Z",
        "ended_at": "2026-06-30T00:01:00Z",
        "steps": 1,
        "cwd": null
    });
    std::fs::write(
        root.join("recordings").join(format!("{rec_id}.json")),
        serde_json::to_string_pretty(&recording).unwrap(),
    )
    .unwrap();
}

fn active_browser_port(sb: &Sandbox) -> u16 {
    let raw =
        std::fs::read_to_string(sb.home().join(".galdr/observe/browser-active.json")).unwrap();
    let value: serde_json::Value = serde_json::from_str(&raw).unwrap();
    value["port"].as_u64().unwrap() as u16
}

fn post_browser_event(port: u16, event: serde_json::Value) {
    let body = serde_json::to_string(&event).unwrap();
    let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
    let request = format!(
        "POST /event HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
        body.len(),
        body
    );
    stream.write_all(request.as_bytes()).unwrap();
    let mut response = String::new();
    stream.read_to_string(&mut response).unwrap();
    assert!(
        response.starts_with("HTTP/1.1 204"),
        "unexpected response: {response}"
    );
}

#[test]
fn json_output_is_machine_readable() {
    // The CLI is the AI-first surface: every --json flag must emit a single,
    // parseable JSON document an agent can consume without scraping a table.
    let sb = Sandbox::new();
    let id = sb.record("json task", &[BASH_STATUS]);

    let refined = sb.home().join("r.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-json-task\ndescription: \"json\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );

    let parse = |args: &[&str]| -> serde_json::Value {
        let out = sb.run(args);
        assert!(out.status.success(), "{args:?} failed");
        serde_json::from_str(&stdout(&out))
            .unwrap_or_else(|e| panic!("{args:?} did not emit valid JSON: {e}"))
    };

    // list → array with our recording
    let list = parse(&["list", "--json"]);
    assert!(
        list.as_array()
            .unwrap()
            .iter()
            .any(|r| r["rec_id"] == id.as_str())
    );

    // show → object with steps
    let show = parse(&["show", &id, "--json"]);
    assert_eq!(show["recording"]["name"], "json task");
    assert_eq!(show["steps"].as_array().unwrap().len(), 1);

    // skills → array carrying the origin classification
    let skills = parse(&["skills", "--json"]);
    let skill = skills
        .as_array()
        .unwrap()
        .iter()
        .find(|s| s["skill_name"] == "galdr-json-task")
        .expect("the distilled skill is listed");
    assert_eq!(skill["origin"], "galdr");

    // harnesses → array, always non-empty (the known set)
    let harnesses = parse(&["harnesses", "--json"]);
    assert!(!harnesses.as_array().unwrap().is_empty());
    assert!(
        harnesses
            .as_array()
            .unwrap()
            .iter()
            .any(|h| h["key"] == "claude")
    );

    // outcome list → object with usage/labels keys
    assert!(
        sb.run(&[
            "outcome",
            "usage",
            "--skill",
            "galdr-json-task",
            "--rec",
            &id,
            "--outcome",
            "success",
        ])
        .status
        .success()
    );
    let outcomes = parse(&["outcome", "list", "--json"]);
    assert!(outcomes["usage"].is_array());
    assert!(outcomes["labels"].is_array());
}

#[test]
fn default_distill_writes_an_unauthored_draft() {
    // A replay of the tool calls is not yet a skill: the default hands the agent a
    // faithful draft to author — status draft, real steps, an authoring marker — and
    // prints the brief that tells the agent what to add and how to install it.
    let sb = Sandbox::new();
    let id = sb.record(
        "deploy preview",
        &[
            BASH_STATUS,
            r#"{"tool_name":"Write","tool_input":{"file_path":"/repo/out.txt"},"tool_response":{}}"#,
        ],
    );
    let out = sb.run(&["distill", &id]);
    assert!(out.status.success());
    let said = stdout(&out);
    assert!(said.contains("author the real skill"), "{said}");
    assert!(said.contains("galdr distill --from"), "{said}");

    let skill = sb.skill_md("galdr-deploy-preview");
    assert!(skill.contains("galdr:unauthored"), "draft marker:\n{skill}");
    for section in ["## When to use", "## Steps", "## Verification"] {
        assert!(skill.contains(section), "missing {section}:\n{skill}");
    }
    // It is catalogued as a draft, pending authoring — not final.
    let listing = stdout(&sb.run(&["skills"]));
    assert!(
        listing.contains("draft"),
        "should list as draft:\n{listing}"
    );
}

#[test]
fn fast_distill_produces_a_complete_usable_skill() {
    // `--fast` is the mechanical one-shot: a complete, valid skill in the open-standard
    // anatomy, installed as final — no authoring pass, no draft.
    let sb = Sandbox::new();
    let id = sb.record(
        "deploy preview",
        &[
            BASH_STATUS,
            r#"{"tool_name":"Write","tool_input":{"file_path":"/repo/out.txt"},"tool_response":{}}"#,
        ],
    );
    assert!(sb.run(&["distill", &id, "--fast"]).status.success());

    let skill = sb.skill_md("galdr-deploy-preview");
    for section in ["## When to use", "## Inputs", "## Steps", "## Verification"] {
        assert!(skill.contains(section), "missing {section}:\n{skill}");
    }
    assert!(!skill.contains("galdr:unauthored"));
    assert!(!skill.contains("[galdr DRAFT]"));
    assert!(!skill.contains("TODO(agent)"));
    // It scores as a complete, ready skill — not a draft.
    let listing = stdout(&sb.run(&["skills"]));
    assert!(listing.contains("final"));
    assert!(listing.contains("ready"));
}

#[test]
fn distill_name_chooses_the_skill_name() {
    // galdr supplies the mechanism; the caller brings the naming intelligence. `--name`
    // installs under a chosen, memorable name instead of the mechanical galdr-<slug>.
    let sb = Sandbox::new();
    let id = sb.record("whatever the recording was called", &[BASH_STATUS]);
    assert!(
        sb.run(&["distill", &id, "--fast", "--name", "rust-greenlight"])
            .status
            .success()
    );
    let md = sb.skill_md("rust-greenlight");
    assert!(md.contains("name: rust-greenlight"), "{md}");
    assert!(
        !sb.home()
            .join(".agents/skills/galdr-whatever-the-recording-was-called")
            .exists(),
        "the mechanical name must not also be created"
    );
    // It still validates and is classified as a galdr skill (origin is content-based,
    // not the name prefix), so dropping the prefix is safe.
    assert!(sb.run(&["validate", "rust-greenlight"]).status.success());
}

#[test]
fn distill_from_honors_the_frontmatter_name() {
    // A refined skill renamed in its frontmatter must install under that name, not the
    // mechanical recording slug — so `galdr validate <name>` finds it and identity does
    // not split between the directory and the skill's own `name:`.
    let sb = Sandbox::new();
    let id = sb.record("visual branding upgrade", &[BASH_STATUS]);

    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: skill-family-upgrade\ndescription: \"upgrade a family of related skills\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();

    let out = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(
        stdout(&out).contains(
            "installed as skill-family-upgrade (renamed from recording slug galdr-visual-branding-upgrade)"
        ),
        "{}",
        stdout(&out)
    );

    // Installed under the frontmatter name; the mechanical slug directory is not created.
    assert!(
        sb.home()
            .join(".agents/skills/skill-family-upgrade/SKILL.md")
            .exists()
    );
    assert!(
        !sb.home()
            .join(".agents/skills/galdr-visual-branding-upgrade")
            .exists(),
        "the recording-slug directory must not be created"
    );

    // The catalog keys it under the frontmatter name, and `validate` resolves it.
    assert!(stdout(&sb.run(&["skills"])).contains("skill-family-upgrade"));
    assert!(
        sb.run(&["validate", "skill-family-upgrade"])
            .status
            .success(),
        "the renamed skill must validate by its frontmatter name"
    );
}

#[test]
fn distill_from_name_flag_overrides_the_frontmatter() {
    // An explicit --name keeps priority over the frontmatter name.
    let sb = Sandbox::new();
    let id = sb.record("branding", &[BASH_STATUS]);
    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: frontmatter-name\ndescription: \"x\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let out = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .args(["--name", "explicit-name"])
        .output()
        .unwrap();
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(
        sb.home()
            .join(".agents/skills/explicit-name/SKILL.md")
            .exists()
    );
    assert!(
        !sb.home().join(".agents/skills/frontmatter-name").exists(),
        "the frontmatter name must not win over an explicit --name"
    );
}

#[test]
fn distill_from_refuses_a_frontmatter_name_held_by_another_skill() {
    // A frontmatter name already taken by an UNRELATED skill (a different recording) is
    // refused without touching anything — no silent clobber of someone else's skill.
    let sb = Sandbox::new();
    let other = sb.record("other", &[BASH_STATUS]);
    let other_file = sb.home().join("other.md");
    std::fs::write(
        &other_file,
        format!(
            "---\nname: taken-name\ndescription: \"the incumbent\"\n---\n\n## Provenance\n- rec_id: `{other}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &other, "--from"])
            .arg(&other_file)
            .output()
            .unwrap()
            .status
            .success()
    );

    let mine = sb.record("mine", &[BASH_STATUS]);
    let mine_file = sb.home().join("mine.md");
    std::fs::write(
        &mine_file,
        format!(
            "---\nname: taken-name\ndescription: \"the challenger\"\n---\n\n## Provenance\n- rec_id: `{mine}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let refused = sb
        .cmd()
        .args(["distill", &mine, "--from"])
        .arg(&mine_file)
        .output()
        .unwrap();
    assert!(
        !refused.status.success(),
        "a colliding frontmatter name must be refused"
    );
    assert!(
        stderr(&refused).contains("already exists"),
        "{}",
        stderr(&refused)
    );

    // The incumbent is untouched, and the challenger's own recording slug is not created.
    let incumbent =
        std::fs::read_to_string(sb.home().join(".agents/skills/taken-name/SKILL.md")).unwrap();
    assert!(incumbent.contains("the incumbent"), "{incumbent}");
    assert!(!sb.home().join(".agents/skills/galdr-mine").exists());
}

#[test]
fn distill_from_migrates_a_stale_draft_under_the_slug() {
    // A prior draft under the mechanical slug must not survive as a second copy once the
    // authored skill installs under its frontmatter name: it is retired to .retired.
    let sb = Sandbox::new();
    let id = sb.record("family upgrade", &[BASH_STATUS]);
    assert!(sb.run(&["distill", &id]).status.success());
    assert!(
        sb.home()
            .join(".agents/skills/galdr-family-upgrade/SKILL.md")
            .exists(),
        "the draft is written under the recording slug"
    );

    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: skill-family-upgrade\ndescription: \"upgrade a family of related skills\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let out = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(out.status.success(), "{}", stderr(&out));

    // The renamed skill is the only live copy; the stale draft was retired, not left behind.
    assert!(
        sb.home()
            .join(".agents/skills/skill-family-upgrade/SKILL.md")
            .exists()
    );
    assert!(
        !sb.home()
            .join(".agents/skills/galdr-family-upgrade")
            .exists(),
        "the stale slug directory must be moved aside"
    );
    assert!(
        sb.home()
            .join(".agents/skills/.retired/galdr-family-upgrade/SKILL.md")
            .exists(),
        "the stale draft should be retired to .retired"
    );
}

#[test]
fn validate_passes_clean_skills_and_refuses_bad_content() {
    // The gate is reachable from the CLI: a clean distilled skill validates, a file
    // carrying a personal path is refused, and --all --json is machine-readable.
    let sb = Sandbox::new();
    let id = sb.record("validate demo", &[BASH_STATUS]);
    assert!(sb.run(&["distill", &id]).status.success());

    let ok = sb.run(&["validate", "galdr-validate-demo"]);
    assert!(
        ok.status.success(),
        "a clean distilled skill must pass: {}",
        String::from_utf8_lossy(&ok.stderr)
    );

    let all = sb.run(&["validate", "--all", "--json"]);
    assert!(all.status.success());
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&all)).unwrap();
    assert!(parsed.is_array(), "--json emits an array: {}", stdout(&all));

    // A file with a personal path is a hard security failure (exit non-zero).
    let bad = sb.home().join("bad.md");
    std::fs::write(
        &bad,
        "---\nname: galdr-bad\ndescription: \"x\"\n---\n\n## When to use\n\nx\n\n## Steps\n\n1. **Read** — /Users/alice/secret.txt\n\n## Verification\n\ny\n",
    )
    .unwrap();
    let refused = sb
        .cmd()
        .args(["validate", "--file"])
        .arg(&bad)
        .output()
        .unwrap();
    assert!(
        !refused.status.success(),
        "a personal path must fail the gate"
    );
}

#[test]
fn setup_codex_check_and_print_work() {
    let sb = Sandbox::new();
    let missing = stdout(&sb.run(&["setup", "codex", "--check"]));
    assert!(missing.contains("not found"));

    let snippet = stdout(&sb.run(&["setup", "codex", "--print"]));
    assert!(snippet.contains("PostToolUse"));
    assert!(snippet.contains("galdr hook"));
    // Codex skips an untrusted hook, so `--print` must spell out the trust step.
    assert!(
        snippet.contains("/hooks"),
        "print must explain trusting the hook"
    );

    let hooks = sb.home().join(".codex/hooks.json");
    std::fs::create_dir_all(hooks.parent().unwrap()).unwrap();
    std::fs::write(
        &hooks,
        r#"{"hooks":{"PostToolUse":[{"matcher":".*","hooks":[{"type":"command","command":"galdr hook"}]}]}}"#,
    )
    .unwrap();
    let configured = stdout(&sb.run(&["setup", "codex", "--check"]));
    assert!(configured.contains("is present"));
}

#[test]
fn setup_cursor_check_and_print_work() {
    let sb = Sandbox::new();
    let missing = stdout(&sb.run(&["setup", "cursor", "--check"]));
    assert!(missing.contains("not found"));

    let snippet = stdout(&sb.run(&["setup", "cursor", "--print"]));
    assert!(snippet.contains("postToolUse"));
    assert!(snippet.contains("galdr hook"));

    let hooks = sb.home().join(".cursor/hooks.json");
    std::fs::create_dir_all(hooks.parent().unwrap()).unwrap();
    std::fs::write(&hooks, snippet).unwrap();
    let configured = stdout(&sb.run(&["setup", "cursor", "--check"]));
    assert!(configured.contains("is present"));
}

#[test]
fn a_cursor_event_records_with_mapped_fields() {
    // Cursor's postToolUse payload renames two fields: `tool_output` (a JSON-stringified
    // string) for the result, and `conversation_id` for the session. The sensor maps both.
    let sb = Sandbox::new();
    let cursor_event = r#"{"tool_name":"Bash","tool_input":{"command":"ls"},"tool_output":"{\"exit_code\":0}","conversation_id":"conv-abc","cwd":"/x"}"#;
    let id = sb.record("cursor task", &[cursor_event]);
    assert_eq!(sb.span_lines(&id), 1);
    let span = std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl")))
        .unwrap();
    assert!(
        span.contains(r#""exit_code":0"#),
        "tool_output is parsed into tool_response: {span}"
    );
    assert!(
        span.contains("conv-abc"),
        "conversation_id maps to session_id: {span}"
    );
}

#[test]
fn distilled_skill_is_linked_into_installed_harnesses() {
    // The make-or-break for "R/R for Claude Code": a distilled skill must become
    // discoverable in the harness it was recorded in, not dead-end in the open
    // standard root the harness never reads.
    let sb = Sandbox::new();
    // Stand up a Claude Code skills dir so the harness is "installed" and known.
    std::fs::create_dir_all(sb.home().join(".claude/skills")).unwrap();

    let id = sb.record("link task", &[BASH_STATUS]);
    let refined = sb.home().join("r.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-link-task\ndescription: \"link\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );

    // The skill is now reachable through the Claude Code skills directory.
    let linked = sb.home().join(".claude/skills/galdr-link-task/SKILL.md");
    assert!(
        linked.exists(),
        "the distilled skill must be discoverable in ~/.claude/skills"
    );
    // And it resolves back to the canonical open-standard copy.
    let canonical = sb.home().join(".agents/skills/galdr-link-task/SKILL.md");
    assert!(canonical.exists());
}

#[test]
fn link_never_clobbers_a_real_skill_already_in_the_harness() {
    let sb = Sandbox::new();
    // A user's own, hand-authored skill of the same name already lives in Claude Code.
    let existing = sb.home().join(".claude/skills/galdr-keepme");
    std::fs::create_dir_all(&existing).unwrap();
    std::fs::write(existing.join("SKILL.md"), "real user content").unwrap();

    let id = sb.record("keepme", &[BASH_STATUS]);
    let refined = sb.home().join("r.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-keepme\ndescription: \"x\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );

    // The user's real file is untouched (not replaced by a symlink).
    let content =
        std::fs::read_to_string(sb.home().join(".claude/skills/galdr-keepme/SKILL.md")).unwrap();
    assert_eq!(content, "real user content");
    assert!(
        !sb.home()
            .join(".claude/skills/galdr-keepme")
            .symlink_metadata()
            .unwrap()
            .file_type()
            .is_symlink()
    );

    // `galdr link --json` reports the conflict rather than silently failing.
    let out = sb.run(&["link", "--skill", "galdr-keepme", "--json"]);
    let results: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    assert!(
        results
            .as_array()
            .unwrap()
            .iter()
            .any(|r| r["harness"] == "Claude Code" && r["status"] == "conflict")
    );
}

#[test]
fn link_rejects_path_traversal_in_skill_name() {
    // `galdr link --skill ../x` must not escape the skills root to create a symlink
    // at an arbitrary sibling path.
    let sb = Sandbox::new();
    let out = sb.run(&["link", "--skill", "../evil"]);
    assert!(
        !out.status.success(),
        "path-traversal skill name must be rejected"
    );
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("path separator") || err.contains("invalid skill name"),
        "{err}"
    );
    // Nothing got created outside the skills dir.
    assert!(!sb.home().join(".claude/evil").exists());
}

#[test]
fn rm_retires_a_skill_unlinking_and_moving_it() {
    // The full lifecycle: `galdr rm` unlinks the skill from every harness, moves its
    // directory into .retired (never a hard delete), and refreshes the catalog so it
    // drops out of `galdr skills`.
    let sb = Sandbox::new();
    std::fs::create_dir_all(sb.home().join(".claude/skills")).unwrap();

    let id = sb.record("retire me", &[BASH_STATUS]);
    assert!(sb.run(&["distill", &id, "--fast"]).status.success());

    let link = sb.home().join(".claude/skills/galdr-retire-me");
    assert!(link.exists(), "the skill should be linked into the harness");
    assert!(stdout(&sb.run(&["skills"])).contains("galdr-retire-me"));

    let rm = sb.run(&["rm", "galdr-retire-me", "--force"]);
    assert!(rm.status.success(), "{}", stderr(&rm));
    let said = stdout(&rm);
    assert!(
        said.contains("Unlinked"),
        "reports what it unlinked: {said}"
    );
    assert!(said.contains("retired 'galdr-retire-me'"), "{said}");

    // The harness symlink is gone (and does not dangle).
    assert!(
        sb.home()
            .join(".claude/skills/galdr-retire-me")
            .symlink_metadata()
            .is_err(),
        "the harness symlink must be removed"
    );
    // The canonical directory left the active root for .retired.
    assert!(!sb.home().join(".agents/skills/galdr-retire-me").exists());
    assert!(
        sb.home()
            .join(".agents/skills/.retired/galdr-retire-me/SKILL.md")
            .exists(),
        "the skill should be moved to .retired, not deleted"
    );
    // The refreshed catalog no longer lists it.
    let listing = stdout(&sb.run(&["skills"]));
    assert!(
        !listing.contains("galdr-retire-me"),
        "a retired skill must drop out of the catalog: {listing}"
    );
}

#[test]
fn rm_of_a_missing_skill_fails_clearly() {
    let sb = Sandbox::new();
    let out = sb.run(&["rm", "does-not-exist", "--force"]);
    assert!(!out.status.success(), "removing a missing skill must fail");
    assert!(stderr(&out).contains("not installed"), "{}", stderr(&out));
}

#[test]
fn rm_without_force_refuses_in_a_non_interactive_context() {
    // Tests run with no TTY. Without --force the retire must refuse (a serious CLI does
    // not mutate on a non-interactive run without an explicit opt-in) and change nothing.
    let sb = Sandbox::new();
    let id = sb.record("keep unless forced", &[BASH_STATUS]);
    assert!(sb.run(&["distill", &id, "--fast"]).status.success());

    let out = sb.run(&["rm", "galdr-keep-unless-forced"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("--force"), "{}", stderr(&out));
    assert!(
        sb.home()
            .join(".agents/skills/galdr-keep-unless-forced/SKILL.md")
            .exists(),
        "a refused retire must leave the skill in place"
    );
}

#[test]
fn rm_suffixes_a_retired_name_that_already_exists() {
    // Retiring two skills that share a name must not clobber the earlier copy: the
    // second lands on a numeric suffix under .retired.
    let sb = Sandbox::new();
    let first = sb.record("twice", &[BASH_STATUS]);
    assert!(sb.run(&["distill", &first, "--fast"]).status.success());
    assert!(sb.run(&["rm", "galdr-twice", "--force"]).status.success());

    let second = sb.record("twice", &[BASH_STATUS]);
    assert!(sb.run(&["distill", &second, "--fast"]).status.success());
    assert!(sb.run(&["rm", "galdr-twice", "--force"]).status.success());

    assert!(
        sb.home()
            .join(".agents/skills/.retired/galdr-twice/SKILL.md")
            .exists()
    );
    assert!(
        sb.home()
            .join(".agents/skills/.retired/galdr-twice.1/SKILL.md")
            .exists(),
        "the second retirement of the same name must be suffixed"
    );
}

#[test]
fn export_redact_scrubs_secrets_from_every_file_not_just_raw() {
    // The worst redaction bug: --redact scrubbed raw.redacted.jsonl but left the
    // secret in steps.md (the Bash command summary). It must scrub all files.
    let sb = Sandbox::new();
    let id = sb.record(
        "leaky",
        &[r#"{"tool_name":"Bash","tool_input":{"command":"curl -H 'Authorization: Bearer ghp_SECRETtoken123' https://api"},"tool_response":{}}"#],
    );
    let out = sb.home().join("exp");
    assert!(
        sb.cmd()
            .args(["export", &id, "--out"])
            .arg(&out)
            .arg("--redact")
            .output()
            .unwrap()
            .status
            .success()
    );
    for file in ["steps.md", "raw.redacted.jsonl"] {
        let content = std::fs::read_to_string(out.join(file)).unwrap();
        assert!(
            !content.contains("ghp_SECRETtoken123"),
            "{file} still leaks the secret:\n{content}"
        );
    }
    assert!(
        std::fs::read_to_string(out.join("steps.md"))
            .unwrap()
            .contains("[REDACTED]")
    );
}

#[test]
fn galdr_root_is_locked_to_the_owner() {
    // Spans hold raw tool data; another local user must not be able to read them.
    let sb = Sandbox::new();
    sb.record("private", &[BASH_STATUS]);
    let meta = std::fs::metadata(sb.home().join(".galdr")).unwrap();
    use std::os::unix::fs::PermissionsExt;
    assert_eq!(
        meta.permissions().mode() & 0o077,
        0,
        "~/.galdr must be 0700 (no group/other access)"
    );
}

#[test]
fn hook_survives_an_oversized_payload() {
    // A hostile/huge stdin must not crash the sensor; it caps the read and drops the
    // (truncated, unparseable) event, still exiting 0.
    let sb = Sandbox::new();
    assert!(sb.run(&["rec", "start", "big"]).status.success());
    let id = sb.active_rec_id();
    let huge = format!(
        r#"{{"tool_name":"Bash","tool_input":{{"command":"{}"}},"tool_response":{{}}}}"#,
        "A".repeat(2_000_000)
    );
    let out = sb.hook(&huge, false);
    assert!(out.status.success(), "the sensor must always exit 0");
    // A 2 MB payload is under the cap, so it records; the point is it does not crash.
    assert!(sb.span_lines(&id) <= 1);
}

#[test]
fn computer_use_screenshots_are_dropped_but_actions_recorded() {
    // galdr captures an agent's Computer Use as tool calls, but the screenshot (a big
    // base64 image, possibly sensitive) is dropped from the span — only the action stays.
    let sb = Sandbox::new();
    assert!(sb.run(&["rec", "start", "gui task"]).status.success());
    let id = sb.active_rec_id();
    let blob = "iVBORw0KGgoAAAANSUhEUg".repeat(80);
    let shot = format!(
        r#"{{"tool_name":"mcp__computer-use__computer","tool_input":{{"action":"screenshot"}},"tool_response":{{"type":"image","source":{{"type":"base64","media_type":"image/png","data":"{blob}"}}}},"session_id":"s1"}}"#
    );
    assert!(sb.hook(&shot, false).status.success());
    assert!(
        sb.hook(
            r#"{"tool_name":"mcp__computer-use__computer","tool_input":{"action":"type","text":"42.50"},"tool_response":{},"session_id":"s1"}"#,
            false,
        )
        .status
        .success()
    );
    assert!(sb.run(&["rec", "stop"]).status.success());

    let span = std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl")))
        .unwrap();
    assert!(
        !span.contains("iVBORw0KGgo"),
        "the screenshot base64 must be dropped"
    );
    assert!(span.contains("stripped screenshot"));

    // The actions read cleanly in `show`.
    let show = stdout(&sb.run(&["show", &id]));
    assert!(show.contains("screenshot"));
    assert!(show.contains("type \"42.50\""), "got: {show}");
}

#[test]
fn a_typed_secret_is_redacted_from_the_distilled_skill() {
    // A Computer Use `type` of a token must not be promoted into the installed,
    // shareable SKILL.md (Inputs or Steps).
    let sb = Sandbox::new();
    let id = sb.record(
        "login flow",
        &[
            r#"{"tool_name":"mcp__computer-use__computer","tool_input":{"action":"type","text":"ghp_SUPERSECRETtoken123"},"tool_response":{}}"#,
        ],
    );
    assert!(sb.run(&["distill", &id]).status.success());
    let skill = sb.skill_md("galdr-login-flow");
    assert!(
        !skill.contains("ghp_SUPERSECRETtoken123"),
        "secret leaked into skill:\n{skill}"
    );
    assert!(skill.contains("[REDACTED]"));
}

#[test]
fn sensor_never_breaks_the_session() {
    let sb = Sandbox::new();

    // No active recording: a no-op, still exit 0.
    assert!(sb.hook(BASH_STATUS, false).status.success());

    assert!(sb.run(&["rec", "start", "demo"]).status.success());
    let id = sb.active_rec_id();

    // Active recording: appends and exits 0.
    assert!(sb.hook(BASH_STATUS, false).status.success());
    assert_eq!(sb.span_lines(&id), 1);

    // Forced internal failure: still exit 0, and nothing appended.
    let failed = sb.hook(BASH_STATUS, true);
    assert!(failed.status.success(), "the sensor must always exit 0");
    assert_eq!(sb.span_lines(&id), 1, "a failed hook must not append");
}

#[test]
fn recording_scopes_to_the_session_that_started_it() {
    // A single global `active` flag means every concurrent agent session's hook
    // sees this recording. The sensor must bind to the starting session and refuse
    // events from another session, so a parallel session in another project cannot
    // leak its tool calls into this span.
    let sb = Sandbox::new();
    assert!(sb.run(&["rec", "start", "scoped"]).status.success());
    let id = sb.active_rec_id();

    // First event carrying a session id binds the recording (no cwd → binds).
    assert!(
        sb.hook(
            r#"{"tool_name":"Bash","tool_input":{"command":"mine-1"},"tool_response":{},"session_id":"mine"}"#,
            false,
        )
        .status
        .success()
    );
    // A different session's event, in another directory, must be dropped.
    assert!(
        sb.hook(
            r#"{"tool_name":"Bash","tool_input":{"command":"leak"},"tool_response":{},"session_id":"other","cwd":"/elsewhere"}"#,
            false,
        )
        .status
        .success()
    );
    // The bound session keeps recording.
    assert!(
        sb.hook(
            r#"{"tool_name":"Read","tool_input":{"file_path":"/x"},"tool_response":{},"session_id":"mine"}"#,
            false,
        )
        .status
        .success()
    );

    assert_eq!(
        sb.span_lines(&id),
        2,
        "only the bound session's events record"
    );
    let span = std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl")))
        .unwrap();
    assert!(
        !span.contains("leak"),
        "the foreign session's command must not leak in: {span}"
    );
    assert!(!span.contains("\"other\""));
}

#[test]
fn record_list_show_work_without_a_daemon() {
    let sb = Sandbox::new();
    let id = sb.record(
        "demo task",
        &[
            BASH_STATUS,
            r#"{"tool_name":"Write","tool_input":{"file_path":"/tmp/out.md"},"tool_response":{}}"#,
        ],
    );

    let list = sb.run(&["list"]);
    assert!(list.status.success());
    let listing = stdout(&list);
    assert!(
        listing.contains("demo task"),
        "list shows the name: {listing}"
    );
    assert!(listing.contains("2 steps"), "list shows the step count");

    let show = sb.run(&["show", &id]);
    assert!(show.status.success());
    let detail = stdout(&show);
    assert!(detail.contains("Bash"));
    assert!(detail.contains("Write"));
    assert!(detail.contains("git status"));
}

#[test]
fn distill_from_installs_and_skills_lists_provenance() {
    let sb = Sandbox::new();
    let id = sb.record("demo", &[BASH_STATUS]);

    // Install a finished skill through the sanctioned --from path. A distilled
    // skill keeps its provenance line, so the rebuilt catalog can link it back.
    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-demo\ndescription: \"does a thing\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(install.status.success());

    let skills = sb.run(&["skills"]);
    assert!(skills.status.success());
    let listing = stdout(&skills);
    assert!(
        listing.contains("galdr-demo"),
        "skills lists the skill: {listing}"
    );
    // Provenance links to the recording, not flagged orphan.
    assert!(listing.contains(&id));
    assert!(!listing.contains("orphan"));
}

#[test]
fn reindex_rebuilds_the_catalog_from_disk() {
    let sb = Sandbox::new();
    sb.record("demo", &[BASH_STATUS]);

    let reindex = sb.run(&["reindex"]);
    assert!(reindex.status.success());
    assert!(stdout(&reindex).contains("catalog rebuilt"));
    // The catalog file now exists and was rebuilt from disk.
    assert!(sb.home().join(".galdr/catalog.sqlite").exists());

    let list = sb.run(&["list"]);
    assert!(list.status.success());
    assert!(stdout(&list).contains("demo"));
}

#[test]
fn human_events_reindex_show_distill_and_export() {
    let sb = Sandbox::new();
    write_human_recording(
        &sb,
        "01HUMAN",
        "human issue form",
        serde_json::json!({
            "policy": "redacted",
            "kind": "text",
            "chars": 24
        }),
    );

    let reindex = sb.run(&["reindex"]);
    assert!(reindex.status.success(), "{}", stderr(&reindex));

    let show = sb.run(&["show", "01HUMAN", "--json"]);
    assert!(show.status.success(), "{}", stderr(&show));
    let detail: serde_json::Value = serde_json::from_str(&stdout(&show)).unwrap();
    assert_eq!(detail["steps"][0]["event_kind"], "human");
    assert_eq!(
        detail["steps"][0]["summary"],
        "type into \"Issue title\" (text, 24 chars)"
    );

    let distill = sb.run(&["distill", "01HUMAN", "--fast"]);
    assert!(distill.status.success(), "{}", stderr(&distill));
    let skill = sb.skill_md("galdr-human-issue-form");
    assert!(skill.contains("browser workflow"), "{skill}");
    assert!(skill.contains("type into \"Issue title\""), "{skill}");
    assert!(skill.contains("Confirm the issue was saved."), "{skill}");

    write_human_recording(
        &sb,
        "01HUMANLIT",
        "human literal",
        serde_json::json!({
            "policy": "literal",
            "value": "Visible customer escalation"
        }),
    );
    let literal_distill = sb.run(&["distill", "01HUMANLIT", "--fast"]);
    assert!(
        literal_distill.status.success(),
        "{}",
        stderr(&literal_distill)
    );
    let literal_skill = sb.skill_md("galdr-human-literal");
    assert!(
        !literal_skill.contains("Visible customer escalation"),
        "literal typed text leaked into skill:\n{literal_skill}"
    );
    assert!(
        literal_skill
            .contains("- `<Issue title>` — text for Issue title at step 1 (27 chars recorded)"),
        "{literal_skill}"
    );

    let out = sb.home().join("human-export");
    let export = sb
        .cmd()
        .args(["export", "01HUMANLIT", "--out"])
        .arg(&out)
        .arg("--redact")
        .output()
        .unwrap();
    assert!(export.status.success(), "{}", stderr(&export));
    let raw = std::fs::read_to_string(out.join("raw.redacted.jsonl")).unwrap();
    assert!(!raw.contains("Visible customer escalation"), "{raw}");
    assert!(raw.contains(r#""policy":"redacted""#), "{raw}");
    assert!(raw.contains(r#""kind":"literal""#), "{raw}");
}

#[test]
fn observe_synthetic_records_a_human_trace() {
    let sb = Sandbox::new();
    let observed = sb.run(&[
        "observe",
        "synthetic",
        "synthetic human form",
        "--fixture",
        "browser-form",
    ]);
    assert!(observed.status.success(), "{}", stderr(&observed));
    let said = stdout(&observed);
    assert!(said.contains("observed \"synthetic human form\""), "{said}");

    let list = stdout(&sb.run(&["list"]));
    assert!(list.contains("synthetic human form"), "{list}");
    assert!(list.contains("4 steps"), "{list}");

    let show = sb.run(&["show", "synthetic human form", "--json"]);
    assert!(show.status.success(), "{}", stderr(&show));
    let detail: serde_json::Value = serde_json::from_str(&stdout(&show)).unwrap();
    assert_eq!(detail["recording"]["name"], "synthetic human form");
    assert_eq!(detail["steps"].as_array().unwrap().len(), 4);
    assert!(
        detail["steps"]
            .as_array()
            .unwrap()
            .iter()
            .all(|step| step["event_kind"] == "human")
    );
    assert_eq!(
        detail["steps"][0]["summary"],
        "navigate https://example.test/issues/new"
    );
    assert_eq!(
        detail["steps"][1]["summary"],
        "type into \"Issue title\" (text, 24 chars)"
    );
    assert_eq!(
        detail["steps"][2]["summary"],
        "select \"Priority\" = \"High\""
    );
    assert_eq!(
        detail["steps"][3]["summary"],
        "click button \"Create issue\""
    );

    let distill = sb.run(&["distill", "synthetic human form", "--fast"]);
    assert!(distill.status.success(), "{}", stderr(&distill));
    let skill = sb.skill_md("galdr-synthetic-human-form");
    assert!(skill.contains("browser workflow"), "{skill}");
    assert!(
        skill.contains("navigate https://example.test/issues/new"),
        "{skill}"
    );
    assert!(skill.contains("select \"Priority\" = \"High\""), "{skill}");
    assert!(
        skill.contains("Confirm the created issue page is open or a success message appears."),
        "{skill}"
    );
}

#[test]
fn observe_browser_collector_records_loopback_events() {
    let sb = Sandbox::new();
    let start = sb.run(&[
        "observe",
        "browser",
        "start",
        "browser collector",
        "--url",
        "https://example.test/form",
        "--no-open",
    ]);
    assert!(start.status.success(), "{}", stderr(&start));
    let port = active_browser_port(&sb);

    post_browser_event(
        port,
        serde_json::json!({
            "ts": "2026-06-30T00:00:00Z",
            "action": "human.browser.navigate",
            "source": {
                "kind": "browser",
                "url": "https://example.test/form",
                "title": "Demo form"
            }
        }),
    );
    post_browser_event(
        port,
        serde_json::json!({
            "ts": "2026-06-30T00:00:01Z",
            "action": "human.browser.input",
            "source": {
                "kind": "browser",
                "url": "https://example.test/form",
                "title": "Demo form"
            },
            "target": {
                "primary": {
                    "kind": "label",
                    "value": "Email"
                },
                "label": "Email"
            },
            "value": {
                "policy": "redacted",
                "kind": "text",
                "chars": 16
            }
        }),
    );

    let status = stdout(&sb.run(&["observe", "browser", "status"]));
    assert!(status.contains("events: 2"), "{status}");
    assert!(status.contains("server: up"), "{status}");

    let stop = sb.run(&["observe", "browser", "stop"]);
    assert!(stop.status.success(), "{}", stderr(&stop));
    let said = stdout(&stop);
    assert!(said.contains("stopped browser observation"), "{said}");
    assert!(said.contains("2 human steps"), "{said}");

    let show = sb.run(&["show", "browser collector", "--json"]);
    assert!(show.status.success(), "{}", stderr(&show));
    let detail: serde_json::Value = serde_json::from_str(&stdout(&show)).unwrap();
    assert_eq!(detail["steps"].as_array().unwrap().len(), 2);
    assert_eq!(detail["steps"][0]["event_kind"], "human");
    assert_eq!(
        detail["steps"][0]["summary"],
        "navigate https://example.test/form"
    );
    assert_eq!(
        detail["steps"][1]["summary"],
        "type into \"Email\" (text, 16 chars)"
    );
}

#[test]
fn recording_writes_keep_an_existing_catalog_current_without_a_daemon() {
    let sb = Sandbox::new();
    sb.record("first", &[BASH_STATUS]);
    assert!(sb.run(&["reindex"]).status.success());

    let second = sb.record(
        "second",
        &[r#"{"tool_name":"Read","tool_input":{"file_path":"/tmp/input.md"},"tool_response":{}}"#],
    );

    let list = sb.run(&["list"]);
    assert!(list.status.success());
    let listing = stdout(&list);
    assert!(
        listing.contains("second"),
        "list should not read a stale catalog: {listing}"
    );

    let show = sb.run(&["show", &second]);
    assert!(show.status.success());
    let detail = stdout(&show);
    assert!(
        detail.contains("/tmp/input.md"),
        "show should include the newly indexed step: {detail}"
    );
}

#[test]
fn skill_writes_keep_an_existing_catalog_current_without_a_daemon() {
    let sb = Sandbox::new();
    let id = sb.record("stale catalog", &[BASH_STATUS]);
    assert!(sb.run(&["reindex"]).status.success());

    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-stale-catalog\ndescription: \"stale catalog check\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(install.status.success());

    let skills = sb.run(&["skills"]);
    assert!(skills.status.success());
    let listing = stdout(&skills);
    assert!(
        listing.contains("galdr-stale-catalog"),
        "skills should not read a stale catalog: {listing}"
    );
    assert!(listing.contains(&id));
}

#[test]
fn draft_distill_keeps_an_existing_catalog_current_without_a_daemon() {
    let sb = Sandbox::new();
    let id = sb.record("draft catalog", &[BASH_STATUS]);
    assert!(sb.run(&["reindex"]).status.success());

    let draft = sb.run(&["distill", &id]);
    assert!(draft.status.success());

    let skills = sb.run(&["skills"]);
    assert!(skills.status.success());
    let listing = stdout(&skills);
    assert!(
        listing.contains("galdr-draft-catalog"),
        "draft distillation should update an existing catalog: {listing}"
    );
    assert!(listing.contains(&id));
}

#[test]
fn parametrize_emit_keeps_an_existing_catalog_current_without_a_daemon() {
    let sb = Sandbox::new();
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    let a = sb.record("ship", &[BASH_STATUS, &write("/repo-a/out.md")]);
    let b = sb.record("ship", &[BASH_STATUS, &write("/repo-b/out.md")]);
    assert!(sb.run(&["reindex"]).status.success());

    let emit = sb.run(&["parametrize", &a, &b, "--emit"]);
    assert!(emit.status.success());

    let skills = sb.run(&["skills"]);
    assert!(skills.status.success());
    let listing = stdout(&skills);
    assert!(
        listing.contains("galdr-ship-param"),
        "parametrize should update an existing catalog: {listing}"
    );
    assert!(listing.contains(&a));
}

#[test]
fn parametrize_emits_a_templated_skill() {
    let sb = Sandbox::new();
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    let a = sb.record("ship", &[BASH_STATUS, &write("/repo-a/out.md")]);
    let b = sb.record("ship", &[BASH_STATUS, &write("/repo-b/out.md")]);

    let emit = sb.run(&["parametrize", &a, &b, "--emit"]);
    assert!(
        emit.status.success(),
        "{}",
        String::from_utf8_lossy(&emit.stderr)
    );

    let skill = sb.skill_md("galdr-ship-param");
    assert!(skill.contains("## Parameters"));
    assert!(skill.contains("## Procedure (parametrized)"));
    assert!(skill.contains("{{OUT}}"), "the output path is templated");
    assert!(
        !skill.contains("LOW-CONFIDENCE"),
        "a clean alignment is high confidence"
    );
}

#[test]
fn parametrize_marks_divergent_recordings_low_confidence() {
    let sb = Sandbox::new();
    let a = sb.record(
        "task",
        &[
            BASH_STATUS,
            r#"{"tool_name":"Read","tool_input":{"file_path":"/a.rs"},"tool_response":{}}"#,
        ],
    );
    let b = sb.record(
        "task",
        &[r#"{"tool_name":"Glob","tool_input":{"pattern":"*.rs"},"tool_response":{}}"#],
    );

    assert!(sb.run(&["parametrize", &a, &b, "--emit"]).status.success());
    let skill = sb.skill_md("galdr-task-param");
    assert!(skill.contains("LOW-CONFIDENCE"));
    assert!(skill.contains("## Alignment notes"));
}

#[test]
fn distill_auto_falls_back_to_a_complete_skill_without_an_engine() {
    let sb = Sandbox::new();
    let id = sb.record("auto demo", &[BASH_STATUS]);

    // No MLX server and no Python mlx_lm: --auto must fall back to a usable, complete
    // skill (not a dead-end draft) and exit 0.
    let auto = sb.run(&["distill", &id, "--auto"]);
    assert!(
        auto.status.success(),
        "--auto must exit 0 even with no engine"
    );
    let skill = sb.skill_md("galdr-auto-demo");
    assert!(skill.contains("galdr-auto-demo"));
    // The fallback is complete: the open-standard anatomy, no draft markers.
    assert!(skill.contains("## When to use"));
    assert!(skill.contains("## Verification"));
    assert!(!skill.contains("[galdr DRAFT]"));
}

#[test]
fn diff_reports_constants_and_parameters() {
    let sb = Sandbox::new();
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    let a = sb.record("ship", &[BASH_STATUS, &write("/repo-a/out.md")]);
    let b = sb.record("ship", &[BASH_STATUS, &write("/repo-b/out.md")]);

    let diff = sb.run(&["diff", &a, &b]);
    assert!(diff.status.success());
    let report = stdout(&diff);
    assert!(report.contains("confidence: HIGH"));
    assert!(report.contains("OUT"), "the output path is a parameter");
    assert!(report.contains("Constants:"));
}

#[test]
fn suggest_surfaces_repeated_tasks_and_dedupes_distilled_ones() {
    let sb = Sandbox::new();
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    // Two runs of the same shape (Bash + a Write), different paths, plus a distinct
    // one-off that must not be reported as repeated.
    let a = sb.record("ship", &[BASH_STATUS, &write("/repo-a/out.md")]);
    let _b = sb.record("ship", &[BASH_STATUS, &write("/repo-b/out.md")]);
    let _c = sb.record("oneoff", &[BASH_STATUS]);

    let parse = |args: &[&str]| -> serde_json::Value {
        let out = sb.run(args);
        assert!(out.status.success(), "{args:?} failed");
        serde_json::from_str(&stdout(&out))
            .unwrap_or_else(|e| panic!("{args:?} did not emit valid JSON: {e}"))
    };

    // At the default threshold (2) only the repeated shape surfaces, counted twice.
    let opps = parse(&["suggest", "--json"]);
    let arr = opps.as_array().expect("an array of opportunities");
    assert_eq!(arr.len(), 1, "only the repeated shape is an opportunity");
    assert_eq!(arr[0]["count"], 2);
    let recs = arr[0]["recordings"].as_array().unwrap();
    assert_eq!(recs.len(), 2);

    // Distilling one run of the shape dedupes it out: nothing repeated remains.
    assert!(sb.run(&["distill", &a]).status.success());
    let after = parse(&["suggest", "--json"]);
    assert!(
        after.as_array().unwrap().is_empty(),
        "an installed skill dedupes its shape out of the opportunities"
    );
}

#[test]
fn bare_galdr_shows_a_friendly_overview() {
    // `galdr` with no subcommand is a human at a terminal — show a home screen, not a
    // clap usage error. Piped (not a TTY), the output is plain text with no ANSI codes.
    let sb = Sandbox::new();
    sb.record("demo-task", &[BASH_STATUS]);

    let out = sb.run(&[]);
    assert!(out.status.success(), "bare `galdr` must exit 0");
    let text = stdout(&out);
    assert!(text.contains("galdr"), "{text}");
    assert!(text.contains("next"), "shows next steps: {text}");
    assert!(text.contains("galdr rec start"), "{text}");
    assert!(
        text.contains("1 recordings"),
        "reflects the catalog: {text}"
    );
    assert!(
        !text.contains('\u{1b}'),
        "no ANSI escapes when piped: {text:?}"
    );
}

#[test]
fn recording_references_resolve_without_a_ulid() {
    // The human DX: never type a 26-char id. `distill`/`show` default to the most
    // recent recording and also accept a recording name.
    let sb = Sandbox::new();
    let older = sb.record("weekly-report", &[BASH_STATUS]);
    let newest = sb.record("ship-preview", &[BASH_STATUS]);

    // `galdr distill` with no argument distills the most recent recording.
    assert!(sb.run(&["distill"]).status.success());
    let skill = sb.skill_md("galdr-ship-preview");
    assert!(
        skill.contains(&newest),
        "the newest recording was distilled"
    );

    // `galdr show <name>` resolves by name (and is not the newest here).
    let shown = sb.run(&["show", "weekly-report", "--json"]);
    assert!(shown.status.success());
    let detail: serde_json::Value = serde_json::from_str(&stdout(&shown)).unwrap();
    assert_eq!(detail["recording"]["rec_id"], older.as_str());

    // The full id still works, and a miss fails with guidance, not a cryptic id error.
    assert!(sb.run(&["show", &newest]).status.success());
    let miss = sb.run(&["show", "does-not-exist"]);
    assert!(!miss.status.success());
    assert!(stderr(&miss).contains("galdr list"));
}

#[test]
fn suggest_and_bench_render_human_reports() {
    let sb = Sandbox::new();
    // Empty install: both report nothing to do, in words, without panicking.
    assert!(sb.run(&["suggest"]).status.success());
    assert!(stdout(&sb.run(&["suggest"])).contains("No repeated"));
    assert!(stdout(&sb.run(&["bench"])).contains("No replay outcomes"));

    // A repeated shape surfaces in the human suggest table.
    let write = |path: &str| {
        format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":"{path}"}},"tool_response":{{}}}}"#
        )
    };
    let id = sb.record("ship", &[BASH_STATUS, &write("/a/out.md")]);
    sb.record("ship", &[BASH_STATUS, &write("/b/out.md")]);
    let suggest = stdout(&sb.run(&["suggest"]));
    assert!(suggest.contains("Skill opportunities"), "{suggest}");
    assert!(suggest.contains("galdr distill"), "{suggest}");

    // A recorded outcome surfaces in the human bench table.
    let refined = sb.home().join("s.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-ship\ndescription: \"ship\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );
    assert!(
        sb.run(&[
            "outcome",
            "usage",
            "--skill",
            "galdr-ship",
            "--rec",
            &id,
            "--outcome",
            "success",
        ])
        .status
        .success()
    );
    let bench = stdout(&sb.run(&["bench"]));
    assert!(bench.contains("Replay reliability"), "{bench}");
    assert!(bench.contains("galdr-ship"), "{bench}");
}

#[test]
fn rec_control_rejects_double_start_and_orphan_stop() {
    let sb = Sandbox::new();
    // Stopping with nothing active is an error, not a silent success.
    let stop = sb.run(&["rec", "stop"]);
    assert!(!stop.status.success());
    assert!(stderr(&stop).contains("no active recording"));

    // Status with nothing active reports it cleanly (exit 0).
    let status = sb.run(&["rec", "status"]);
    assert!(status.status.success());
    assert!(stdout(&status).contains("no active recording"));

    // Concurrent recordings are allowed now: a second start also succeeds.
    assert!(sb.run(&["rec", "start", "one"]).status.success());
    assert!(sb.run(&["rec", "start", "two"]).status.success());
    let both = stdout(&sb.run(&["rec", "status"]));
    assert!(both.contains("2 active recordings"), "{both}");
    assert!(both.contains("one") && both.contains("two"), "{both}");

    // A bare stop with several active is refused, listing which to name.
    let ambiguous = sb.run(&["rec", "stop"]);
    assert!(!ambiguous.status.success());
    assert!(
        stderr(&ambiguous).contains("specify which"),
        "{}",
        stderr(&ambiguous)
    );

    // Stop by name closes exactly that one; the other stays active.
    assert!(sb.run(&["rec", "stop", "one"]).status.success());
    let after = stdout(&sb.run(&["rec", "status"]));
    assert!(after.contains("1 active recording"), "{after}");
    assert!(after.contains("two"), "{after}");

    // A bare stop now closes the sole remaining one; a further stop is an orphan error.
    assert!(sb.run(&["rec", "stop"]).status.success());
    assert!(!sb.run(&["rec", "stop"]).status.success());
}

#[test]
fn a_corrupt_active_flag_is_treated_as_not_recording() {
    let sb = Sandbox::new();
    // Establish ~/.galdr by starting and stopping once.
    assert!(sb.run(&["rec", "start", "seed"]).status.success());
    assert!(sb.run(&["rec", "stop"]).status.success());
    // Corrupt the active flag: the sensor and control must treat it as "no recording"
    // (the safe side), not crash.
    std::fs::write(sb.home().join(".galdr/active"), "}{ not json").unwrap();
    let status = sb.run(&["rec", "status"]);
    assert!(status.status.success());
    assert!(stdout(&status).contains("no active recording"));
    // And a fresh start works despite the garbage flag.
    assert!(sb.run(&["rec", "start", "fresh"]).status.success());
}

#[test]
fn list_is_empty_on_a_fresh_install() {
    let sb = Sandbox::new();
    let out = sb.run(&["list"]);
    assert!(out.status.success());
    assert!(stdout(&out).contains("no recordings yet"));
}

#[test]
fn bench_reports_replay_hit_rate_from_recorded_outcomes() {
    let sb = Sandbox::new();
    let id = sb.record("bench", &[BASH_STATUS]);
    let refined = sb.home().join("bench.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-bench\ndescription: \"bench task\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    assert!(
        sb.cmd()
            .args(["distill", &id, "--from"])
            .arg(&refined)
            .output()
            .unwrap()
            .status
            .success()
    );

    // Two recorded replays of the skill: one clean, one failed after a retry.
    let record_outcome = |outcome: &str, retries: &str| {
        sb.run(&[
            "outcome",
            "usage",
            "--skill",
            "galdr-bench",
            "--rec",
            &id,
            "--outcome",
            outcome,
            "--retries",
            retries,
        ])
    };
    assert!(record_outcome("success", "0").status.success());
    assert!(record_outcome("failed", "1").status.success());

    let out = sb.run(&["bench", "--json"]);
    assert!(out.status.success());
    let report: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    assert_eq!(report["total_replays"], 2);
    assert_eq!(report["overall_success_rate"], 0.5);
    let skill = report["skills"]
        .as_array()
        .unwrap()
        .iter()
        .find(|s| s["skill_name"] == "galdr-bench")
        .expect("galdr-bench in the report");
    assert_eq!(skill["uses"], 2);
    assert_eq!(skill["success"], 1);
    assert_eq!(skill["failed"], 1);
    assert_eq!(skill["success_rate"], 0.5);
    assert_eq!(skill["avg_retries"], 0.5);
}

#[test]
fn rec_status_and_capture_policy_work() {
    let sb = Sandbox::new();
    assert!(stdout(&sb.run(&["rec", "status"])).contains("no active recording"));

    std::fs::create_dir_all(sb.home().join(".galdr")).unwrap();
    std::fs::write(
        sb.home().join(".galdr/config.json"),
        r#"{"capture":{"deny_tools":["Secret"],"deny_cwd_prefixes":["/private"],"max_response_chars":12}}"#,
    )
    .unwrap();

    assert!(sb.run(&["rec", "start", "capture"]).status.success());
    let id = sb.active_rec_id();
    assert!(
        sb.hook(
            r#"{"tool_name":"Secret","tool_input":{"value":"x"},"tool_response":{"token":"abc"}}"#,
            false,
        )
        .status
        .success()
    );
    assert_eq!(sb.span_lines(&id), 0, "denied tools are not recorded");

    assert!(
        sb.hook(
            r#"{"tool_name":"Bash","tool_input":{"command":"echo hi"},"tool_response":{"stdout":"abcdefghijklmnopqrstuvwxyz"},"cwd":"/tmp"}"#,
            false,
        )
        .status
        .success()
    );
    assert_eq!(sb.span_lines(&id), 1);
    let span = std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl")))
        .unwrap();
    assert!(span.contains("galdr_truncated"));

    let status = stdout(&sb.run(&["rec", "status"]));
    assert!(status.contains("1 active recording"), "{status}");
    assert!(status.contains("capture"), "{status}");
    assert!(status.contains("steps: 1"), "{status}");
}

#[test]
fn skills_catalog_reports_status_readiness_and_delta() {
    let sb = Sandbox::new();
    let id = sb.record("readiness", &[BASH_STATUS]);

    // The default distill writes a faithful draft (status draft) until an agent
    // authors it and installs the final version with --from.
    assert!(sb.run(&["distill", &id]).status.success());
    let draft_listing = stdout(&sb.run(&["skills"]));
    assert!(draft_listing.contains("galdr-readiness"));
    assert!(draft_listing.contains("draft"));
    assert!(draft_listing.contains("readiness"));

    let refined = sb.home().join("refined.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-readiness\ndescription: \"readiness check\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(install.status.success());

    let final_listing = stdout(&sb.run(&["skills"]));
    assert!(final_listing.contains("final"));
    assert!(
        final_listing.contains("(+"),
        "readiness delta should show the final skill improved: {final_listing}"
    );

    let evaluations = stdout(&sb.run(&["evaluations", "--skill", "galdr-readiness"]));
    assert!(evaluations.contains("readiness_lint"));
    assert!(evaluations.contains("galdr-readiness"));
}

#[test]
fn outcome_usage_and_labels_survive_reindex() {
    let sb = Sandbox::new();
    let id = sb.record("outcome", &[BASH_STATUS]);
    let refined = sb.home().join("outcome.md");
    std::fs::write(
        &refined,
        format!(
            "---\nname: galdr-outcome\ndescription: \"outcome capture\"\n---\n\n## Provenance\n- rec_id: `{id}`\n\n## Goal\nx\n## Procedure\ny\n## Success criteria\nz\n"
        ),
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&refined)
        .output()
        .unwrap();
    assert!(install.status.success());

    let usage = sb.run(&[
        "outcome",
        "usage",
        "--skill",
        "galdr-outcome",
        "--rec",
        &id,
        "--task-kind",
        "smoke",
        "--outcome",
        "success",
        "--retries",
        "1",
        "--manual-interventions",
        "2",
        "--notes",
        "worked after one retry",
    ]);
    assert!(usage.status.success());
    assert!(stdout(&usage).contains("usage recorded"));

    let label = sb.run(&[
        "outcome",
        "label",
        "--skill",
        "galdr-outcome",
        "--rec",
        &id,
        "--evaluator",
        "human",
        "--label",
        "accepted",
        "--confidence",
        "0.9",
        "--notes",
        "reviewed",
    ]);
    assert!(label.status.success());
    assert!(stdout(&label).contains("outcome recorded"));

    let usage_log = sb.home().join(".galdr/outcomes/skill_usage.jsonl");
    let outcome_log = sb.home().join(".galdr/outcomes/skill_outcomes.jsonl");
    assert!(
        std::fs::read_to_string(usage_log)
            .unwrap()
            .contains("success")
    );
    assert!(
        std::fs::read_to_string(outcome_log)
            .unwrap()
            .contains("accepted")
    );

    assert!(sb.run(&["reindex"]).status.success());
    let listing = stdout(&sb.run(&["outcome", "list", "--skill", "galdr-outcome"]));
    assert!(listing.contains("success"));
    assert!(listing.contains("accepted"));
    assert!(listing.contains("interventions  2"));
}

#[test]
fn distill_from_rejects_unfinished_skills() {
    let sb = Sandbox::new();
    let id = sb.record("unfinished", &[BASH_STATUS]);
    let bad = sb.home().join("bad.md");
    std::fs::write(
        &bad,
        "---\nname: galdr-unfinished\ndescription: \"bad\"\n---\n\n## Goal\nx\n## Procedure\ny\n",
    )
    .unwrap();
    let install = sb
        .cmd()
        .args(["distill", &id, "--from"])
        .arg(&bad)
        .output()
        .unwrap();
    assert!(!install.status.success());
    assert!(String::from_utf8_lossy(&install.stderr).contains("Success criteria"));
}

#[test]
fn setup_claude_check_and_print_work_without_mutating_settings() {
    let sb = Sandbox::new();
    let missing = stdout(&sb.run(&["setup", "claude", "--check"]));
    assert!(missing.contains("settings not found"));

    let snippet = stdout(&sb.run(&["setup", "claude", "--print"]));
    assert!(snippet.contains("PostToolUse"));
    assert!(snippet.contains("galdr hook"));

    let settings = sb.home().join(".claude/settings.json");
    std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
    std::fs::write(&settings, snippet).unwrap();
    let configured = stdout(&sb.run(&["setup", "claude", "--check"]));
    assert!(configured.contains("is configured"));
}

#[test]
fn export_omits_raw_by_default_and_can_write_redacted_raw() {
    let sb = Sandbox::new();
    let id = sb.record(
        "export",
        &[r#"{"tool_name":"Bash","tool_input":{"command":"deploy","api_key":"secret-key"},"tool_response":{"token":"secret-token","ok":true}}"#],
    );

    let out = sb.home().join("export-default");
    let export = sb
        .cmd()
        .args(["export", &id, "--out"])
        .arg(&out)
        .output()
        .unwrap();
    assert!(export.status.success());
    assert!(out.join("recording.json").exists());
    assert!(out.join("steps.md").exists());
    assert!(out.join("skills.json").exists());
    assert!(out.join("usage.json").exists());
    assert!(out.join("outcomes.json").exists());
    assert!(!out.join("raw.jsonl").exists());

    let redacted = sb.home().join("export-redacted");
    let export = sb
        .cmd()
        .args(["export", &id, "--out"])
        .arg(&redacted)
        .arg("--redact")
        .output()
        .unwrap();
    assert!(export.status.success());
    let raw = std::fs::read_to_string(redacted.join("raw.redacted.jsonl")).unwrap();
    assert!(raw.contains("[REDACTED]"));
    assert!(!raw.contains("secret-token"));
    assert!(!raw.contains("secret-key"));
}

#[test]
fn doctor_passes_when_claude_hook_is_configured() {
    let sb = Sandbox::new();
    let settings = sb.home().join(".claude/settings.json");
    std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
    std::fs::write(
        &settings,
        r#"{"hooks":{"PostToolUse":[{"hooks":[{"type":"command","command":"galdr hook"}]}]}}"#,
    )
    .unwrap();
    // Keep the update check hermetic: read the "index" from a local fixture pinned to
    // this build's version, so doctor never touches the network and the update line is
    // deterministic ("up to date").
    let index = write_index_fixture(&sb, &[(env!("CARGO_PKG_VERSION"), false)]);
    let doctor = sb
        .cmd()
        .env("GALDR_INDEX_FILE", &index)
        .arg("doctor")
        .output()
        .unwrap();
    assert!(
        doctor.status.success(),
        "{}\n{}",
        stdout(&doctor),
        String::from_utf8_lossy(&doctor.stderr)
    );
    let said = stdout(&doctor);
    assert!(said.contains("doctor: ok"));
    assert!(
        said.contains(&format!("up to date (v{})", env!("CARGO_PKG_VERSION"))),
        "doctor should surface the update check: {said}"
    );
}

#[test]
fn upgrade_check_reports_up_to_date() {
    let sb = Sandbox::new();
    let index = write_index_fixture(
        &sb,
        &[("0.14.0", false), (env!("CARGO_PKG_VERSION"), false)],
    );
    let out = sb
        .cmd()
        .env("GALDR_INDEX_FILE", &index)
        .args(["upgrade", "--check"])
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    assert!(stdout(&out).contains("is up to date"), "{}", stdout(&out));
}

#[test]
fn upgrade_check_flags_a_newer_version_with_exit_10() {
    // A published version greater than this build: --check names it, points at the
    // command, and exits 10 — a distinct signal a script can branch on.
    let sb = Sandbox::new();
    let index = write_index_fixture(&sb, &[(env!("CARGO_PKG_VERSION"), false), ("9.9.9", false)]);
    let out = sb
        .cmd()
        .env("GALDR_INDEX_FILE", &index)
        .args(["upgrade", "--check"])
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(10), "{}", stderr(&out));
    let said = stdout(&out);
    assert!(said.contains("9.9.9"), "{said}");
    assert!(said.contains("galdr upgrade"), "{said}");
}

#[test]
fn upgrade_check_ignores_a_yanked_newer_version() {
    // The only newer version is yanked, so the live max equals this build: up to date.
    let sb = Sandbox::new();
    let index = write_index_fixture(&sb, &[(env!("CARGO_PKG_VERSION"), false), ("9.9.9", true)]);
    let out = sb
        .cmd()
        .env("GALDR_INDEX_FILE", &index)
        .args(["upgrade", "--check"])
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    assert!(stdout(&out).contains("is up to date"), "{}", stdout(&out));
}

#[test]
fn upgrade_check_reports_local_ahead() {
    // The published max is behind this build — the normal state when running from a
    // clone whose version bump has not shipped yet. Not an update, exit 0.
    let sb = Sandbox::new();
    let index = write_index_fixture(&sb, &[("0.0.1", false)]);
    let out = sb
        .cmd()
        .env("GALDR_INDEX_FILE", &index)
        .args(["upgrade", "--check"])
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    let said = stdout(&out);
    assert!(said.contains("ahead of crates.io"), "{said}");
    assert!(said.contains("v0.0.1"), "{said}");
}

#[test]
fn upgrade_check_is_soft_when_offline() {
    // A missing index fixture stands in for "no network": a note, exit 0 — never an
    // error. galdr's local-first contract makes offline a note, not a failure.
    let sb = Sandbox::new();
    let missing = sb.home().join("no-such-index.json");
    let out = sb
        .cmd()
        .env("GALDR_INDEX_FILE", &missing)
        .args(["upgrade", "--check"])
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(0), "{}", stderr(&out));
    assert!(stdout(&out).contains("offline"), "{}", stdout(&out));
}

#[test]
fn upgrade_rejects_an_invalid_from() {
    // A malformed `--from` is a usage error (exit 1) and never reaches the network.
    let sb = Sandbox::new();
    let out = sb
        .cmd()
        .env("GALDR_INDEX_FILE", sb.home().join("unused.json"))
        .args(["upgrade", "--check", "--from", "bogus"])
        .output()
        .unwrap();
    assert!(!out.status.success());
    assert!(stderr(&out).contains("--from"), "{}", stderr(&out));
}

/// Optional daemon round-trip. Kept robust (generous polling, guaranteed
/// teardown) but isolated to its own temp HOME so it never disturbs the others.
#[test]
fn daemon_indexes_and_answers_queries() {
    let sb = Sandbox::new();
    let pidfile = sb.home().join(".galdr/galdrd.pid");
    let socket = sb.home().join(".galdr/galdrd.sock");

    assert!(stdout(&sb.run(&["daemon", "status"])).contains("daemon stopped"));
    assert!(sb.run(&["daemon", "--detach"]).status.success());

    // A guard that kills the daemon on the way out, even if an assert fails.
    struct Guard(PathBuf);
    impl Drop for Guard {
        fn drop(&mut self) {
            if let Ok(pid) = std::fs::read_to_string(&self.0)
                && let Ok(pid) = pid.trim().parse::<i32>()
            {
                let _ = Command::new("kill")
                    .arg(pid.to_string())
                    .stdout(Stdio::null())
                    .stderr(Stdio::null())
                    .status();
            }
        }
    }
    let _guard = Guard(pidfile.clone());

    // Wait for the socket to appear (up to ~5s).
    let mut ready = false;
    for _ in 0..100 {
        if socket.exists() {
            ready = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    assert!(ready, "daemon socket never appeared");
    let status = stdout(&sb.run(&["daemon", "status"]));
    assert!(status.contains("daemon running"));
    // The daemon reports its version over the socket (so a stale daemon left running
    // from an older binary is detectable); it matches this build's version.
    assert!(
        status.contains(&format!("version: {}", env!("CARGO_PKG_VERSION"))),
        "daemon status should print the version: {status}"
    );

    sb.record("daemon demo", &[BASH_STATUS]);
    // Give the close notification a moment to be indexed.
    std::thread::sleep(std::time::Duration::from_millis(200));

    let list = sb.run(&["list"]);
    assert!(list.status.success());
    assert!(
        stdout(&list).contains("daemon demo"),
        "the daemon-backed catalog should list the recording"
    );

    let stop = sb.run(&["daemon", "stop"]);
    assert!(stop.status.success());
    assert!(stdout(&stop).contains("daemon stopped"));
}

#[cfg(target_os = "macos")]
#[test]
fn daemon_install_writes_loads_and_uninstalls_the_launchagent() {
    let sb = Sandbox::new();
    let (launchctl, log) = fake_launchctl(&sb);

    let install = sb
        .cmd()
        .env("GALDR_LAUNCHCTL", &launchctl)
        .args(["daemon", "install"])
        .output()
        .unwrap();
    assert!(install.status.success(), "{}", stderr(&install));

    // The plist landed under this HOME's LaunchAgents, wired to run this binary as a
    // daemon and to keep it alive.
    let plist = sb
        .home()
        .join("Library/LaunchAgents/dev.galdr.daemon.plist");
    assert!(plist.exists(), "the LaunchAgent plist must be written");
    let body = std::fs::read_to_string(&plist).unwrap();
    assert!(body.contains("<string>dev.galdr.daemon</string>"), "{body}");
    assert!(
        body.contains(bin()),
        "plist must point at this binary: {body}"
    );
    assert!(body.contains("<string>daemon</string>"), "{body}");
    assert!(body.contains("<key>KeepAlive</key>"), "{body}");
    assert!(body.contains("<key>RunAtLoad</key>"), "{body}");
    // The log directory was created, and a first install bootstraps the job.
    assert!(sb.home().join(".galdr/logs").is_dir(), "log dir must exist");
    let logged = std::fs::read_to_string(&log).unwrap();
    assert!(logged.contains("bootstrap"), "expected bootstrap: {logged}");

    // status now reports it as managed (plist present + the probe exits 0).
    let status = sb
        .cmd()
        .env("GALDR_LAUNCHCTL", &launchctl)
        .args(["daemon", "status"])
        .output()
        .unwrap();
    assert!(
        stdout(&status).contains("launchd: managed"),
        "{}",
        stdout(&status)
    );

    // uninstall unloads the job and removes the plist, but leaves logs/state.
    let uninstall = sb
        .cmd()
        .env("GALDR_LAUNCHCTL", &launchctl)
        .args(["daemon", "uninstall"])
        .output()
        .unwrap();
    assert!(uninstall.status.success(), "{}", stderr(&uninstall));
    assert!(!plist.exists(), "the plist must be removed on uninstall");
    assert!(
        sb.home().join(".galdr/logs").is_dir(),
        "uninstall must not delete logs/state"
    );
    let logged = std::fs::read_to_string(&log).unwrap();
    assert!(logged.contains("bootout"), "expected bootout: {logged}");
}

#[cfg(target_os = "macos")]
#[test]
fn daemon_status_reports_unmanaged_without_a_launchagent() {
    // No plist installed → unmanaged, and (by design) launchctl is never invoked, so
    // the check stays hermetic without any stand-in.
    let sb = Sandbox::new();
    let status = sb.run(&["daemon", "status"]);
    assert!(status.status.success());
    assert!(
        stdout(&status).contains("launchd: unmanaged"),
        "{}",
        stdout(&status)
    );
}

#[cfg(not(target_os = "macos"))]
#[test]
fn daemon_install_is_macos_only() {
    // launchd is macOS-only: the subcommand must fail with a clear message elsewhere.
    let sb = Sandbox::new();
    let out = sb.run(&["daemon", "install"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("macOS-only"), "{}", stderr(&out));
}

#[test]
fn concurrent_recordings_bind_and_isolate_by_session() {
    // The core of the concurrency feature: two agent sessions record at once, each
    // span receives only its own session's steps, and stopping one leaves the other
    // recording.
    let sb = Sandbox::new();
    for name in ["projA", "projB", "projC"] {
        std::fs::create_dir_all(sb.home().join(name)).unwrap();
    }
    // Canonicalize so the event `cwd` matches `origin_cwd` exactly: on macOS the
    // recording process's getcwd() resolves /var → /private/var, so an unresolved
    // temp path would never be seen as "under" the origin.
    let proj_a = std::fs::canonicalize(sb.home().join("projA")).unwrap();
    let proj_b = std::fs::canonicalize(sb.home().join("projB")).unwrap();
    let proj_c = std::fs::canonicalize(sb.home().join("projC")).unwrap();

    // Start two recordings, each from its own directory (distinct origin_cwd).
    assert!(
        sb.cmd()
            .current_dir(&proj_a)
            .args(["rec", "start", "alpha"])
            .status()
            .unwrap()
            .success()
    );
    assert!(
        sb.cmd()
            .current_dir(&proj_b)
            .args(["rec", "start", "beta"])
            .status()
            .unwrap()
            .success()
    );

    // A PostToolUse event bound to a session under a working directory.
    let event = |session: &str, cwd: &std::path::Path, cmd: &str| {
        format!(
            r#"{{"tool_name":"Bash","tool_input":{{"command":"{cmd}"}},"tool_response":{{}},"session_id":"{session}","cwd":"{}"}}"#,
            cwd.display()
        )
    };

    // sessA acts under projA → binds alpha; sessB under projB → binds beta. Interleaved.
    assert!(
        sb.hook(&event("sessA", &proj_a, "a-one"), false)
            .status
            .success()
    );
    assert!(
        sb.hook(&event("sessB", &proj_b, "b-one"), false)
            .status
            .success()
    );
    assert!(
        sb.hook(&event("sessB", &proj_b, "b-two"), false)
            .status
            .success()
    );
    assert!(
        sb.hook(&event("sessA", &proj_a, "a-two"), false)
            .status
            .success()
    );
    // A third session with no free recording to claim is dropped.
    assert!(
        sb.hook(&event("sessC", &proj_c, "c-one"), false)
            .status
            .success()
    );

    let alpha = sb.active_rec_id_by_name("alpha");
    let beta = sb.active_rec_id_by_name("beta");
    assert_ne!(alpha, beta);

    let span = |id: &str| {
        std::fs::read_to_string(sb.home().join(".galdr/spans").join(format!("{id}.jsonl"))).unwrap()
    };
    // Each span holds only its own session's steps.
    let a = span(&alpha);
    assert!(
        a.contains("a-one") && a.contains("a-two"),
        "alpha span: {a}"
    );
    assert!(
        !a.contains("b-one") && !a.contains("b-two") && !a.contains("c-one"),
        "alpha span leaked another session: {a}"
    );
    let b = span(&beta);
    assert!(b.contains("b-one") && b.contains("b-two"), "beta span: {b}");
    assert!(
        !b.contains("a-one") && !b.contains("c-one"),
        "beta span leaked another session: {b}"
    );
    assert_eq!(
        sb.span_lines(&alpha),
        2,
        "alpha recorded exactly its 2 steps"
    );
    assert_eq!(sb.span_lines(&beta), 2, "beta recorded exactly its 2 steps");

    // Stop alpha by name; beta keeps recording untouched.
    assert!(sb.run(&["rec", "stop", "alpha"]).status.success());
    let status = stdout(&sb.run(&["rec", "status"]));
    assert!(status.contains("1 active recording"), "{status}");
    assert!(status.contains("beta"), "{status}");
    // A further event from sessB still lands in beta.
    assert!(
        sb.hook(&event("sessB", &proj_b, "b-three"), false)
            .status
            .success()
    );
    assert_eq!(
        sb.span_lines(&beta),
        3,
        "beta kept recording after alpha stopped"
    );
    // alpha closed cleanly with its 2 steps.
    let list = stdout(&sb.run(&["list"]));
    assert!(
        list.contains("alpha"),
        "alpha should be a closed recording: {list}"
    );
}

#[test]
fn legacy_active_flag_is_migrated_without_losing_the_recording() {
    // An in-progress recording written under the old single ~/.galdr/active must
    // survive the upgrade: it is folded into active.d/ and keeps recording.
    let sb = Sandbox::new();
    std::fs::create_dir_all(sb.home().join(".galdr")).unwrap();
    std::fs::write(
        sb.home().join(".galdr/active"),
        r#"{"rec_id":"01LEGACY0000000000000000AA","name":"legacy-run","started_at":"2026-07-02T00:00:00Z","origin_cwd":null,"bound_session":null}"#,
    )
    .unwrap();

    // Any command that touches the active set migrates it.
    let status = stdout(&sb.run(&["rec", "status"]));
    assert!(status.contains("legacy-run"), "{status}");
    assert!(status.contains("01LEGACY0000000000000000AA"), "{status}");
    // The legacy file is gone and the new per-recording flag exists.
    assert!(
        !sb.home().join(".galdr/active").exists(),
        "legacy flag must be removed"
    );
    assert!(
        sb.home()
            .join(".galdr/active.d/01LEGACY0000000000000000AA.json")
            .exists(),
        "recording must be folded into active.d/"
    );
    // It still records (sessionless event lands in it) and stops cleanly.
    assert!(sb.hook(BASH_STATUS, false).status.success());
    assert_eq!(sb.span_lines("01LEGACY0000000000000000AA"), 1);
    assert!(sb.run(&["rec", "stop", "legacy-run"]).status.success());
}