change-capsule 0.1.2

Isolated Git worktree attempts for coding agents, sealed into portable verifiable receipts
Documentation
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
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use sha2::{Digest, Sha256};
use ulid::Ulid;

use crate::artifact::{ArtifactReader, ArtifactSink, PublishedArtifact};
use crate::error::{Error, Result, io};
use crate::git::{CommitPatch, Git, Repository};
use crate::model::{
    AUDIT_EVENT_CAP, AUDIT_SCHEMA_VERSION, ArtifactBundle, ArtifactDescriptor, ArtifactKind,
    AuditEvent, AuditEventKind, BUNDLE_SCHEMA_VERSION, BackupReport, Capsule, CapsuleHealth,
    CapsuleResult, CapsuleState, CapsuleStatus, CapsuleSummary, Checkpoint, CheckpointJournal,
    Cleanup, Evidence, ExportReport, Integration, MetricsSnapshot, RecoveryAction, ResultKind,
    ResultRef, SCHEMA_VERSION, StateInspection,
};
use crate::policy::{Policy, PolicyReport};
use crate::state::{StateStore, default_state_root};

const LABEL_CAP: usize = 256;
const LINK_KEY_CAP: usize = 64;
const LINK_VALUE_CAP: usize = 4096;
const MESSAGE_CAP: usize = 16 * 1024;
const EVIDENCE_COMMAND_CAP: usize = 16 * 1024;
const EVIDENCE_SUMMARY_CAP: usize = 64 * 1024;
const EVIDENCE_COUNT_CAP: usize = 64;
const EVIDENCE_TOTAL_BYTES_CAP: usize = 256 * 1024;
const CHECKPOINT_COUNT_CAP: usize = 128;
const DEFAULT_AUTHOR_NAME: &str = "Capsule";
const DEFAULT_AUTHOR_EMAIL: &str = "capsule@localhost";

/// Commit identity used for checkpoints and integration commits.
///
/// Always explicit: this crate never reads the ambient Git configuration to
/// decide who authored a change it creates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Author {
    /// Name recorded as both author and committer.
    pub name: String,
    /// Email recorded as both author and committer. Must contain `@`.
    pub email: String,
}

impl Default for Author {
    fn default() -> Self {
        Self {
            name: DEFAULT_AUTHOR_NAME.to_owned(),
            email: DEFAULT_AUTHOR_EMAIL.to_owned(),
        }
    }
}

/// Inputs for creating a capsule.
#[derive(Debug, Clone)]
pub struct CreateOptions {
    /// Any path inside the source Git repository.
    pub repository: PathBuf,
    /// Revision to pin, resolved to an immutable commit before work starts.
    pub base: String,
    /// Optional human-facing description of the attempt.
    pub label: Option<String>,
    /// Opaque caller metadata, at most 32 entries. No key is privileged.
    pub links: BTreeMap<String, String>,
}

impl CreateOptions {
    /// Options for a capsule based on the repository's current `HEAD`.
    pub fn new(repository: impl Into<PathBuf>) -> Self {
        Self {
            repository: repository.into(),
            base: "HEAD".to_owned(),
            label: None,
            links: BTreeMap::new(),
        }
    }
}

/// Inputs for committing the workspace's current state as a checkpoint.
#[derive(Debug, Clone)]
pub struct CheckpointOptions {
    /// Message for the checkpoint commit.
    pub message: String,
    /// Identity to record on the commit.
    pub author: Author,
}

/// A verification claim to attach to a capsule.
#[derive(Debug, Clone)]
pub struct EvidenceInput {
    /// Exact command the caller ran.
    pub command: String,
    /// Exit status the caller observed.
    pub exit_code: i32,
    /// Optional bounded summary of what happened.
    pub summary: Option<String>,
}

/// Requirements a capsule must satisfy before its result is sealed.
#[derive(Debug, Clone, Copy, Default)]
pub struct CloseOptions {
    /// Refuse to seal unless evidence exists and every exit code is zero.
    pub require_successful_evidence: bool,
}

/// Inputs for applying a sealed result to a target worktree.
#[derive(Debug, Clone)]
pub struct IntegrateOptions {
    /// Any path inside the destination worktree.
    ///
    /// It must belong to the same repository, be clean, and still be at the
    /// capsule's pinned base.
    pub target: PathBuf,
    /// Commit subject. Defaults to the capsule label, then a generated subject.
    pub message: Option<String>,
    /// Identity to record on the integration commit.
    pub author: Author,
}

/// Entry point for every capsule operation.
///
/// A manager owns one state directory and resolves the Git executable once when
/// opened. Instances are cheap; operations serialize across processes through
/// file locks, so several managers may safely share a state root.
///
/// # Example
///
/// ```no_run
/// use change_capsule::{CapsuleManager, CreateOptions};
///
/// let manager = CapsuleManager::open_default()?;
/// let capsule = manager.create(CreateOptions::new("."))?;
/// println!("work in {}", capsule.workspace_path.display());
/// # Ok::<(), change_capsule::Error>(())
/// ```
#[derive(Debug)]
pub struct CapsuleManager {
    store: StateStore,
    git: Git,
}

impl CapsuleManager {
    /// Open a manager on the default state directory.
    ///
    /// Honours `CAPSULE_HOME`, then the platform state directory.
    pub fn open_default() -> Result<Self> {
        Self::open(default_state_root()?)
    }

    /// Open a manager on an explicit state directory, creating it if needed.
    pub fn open(state_root: impl Into<PathBuf>) -> Result<Self> {
        let state_root = state_root.into();
        Ok(Self {
            store: StateStore::open(&state_root)?,
            git: Git::discover()?,
        })
    }

    /// Directory holding this manager's durable state.
    pub fn state_root(&self) -> &Path {
        self.store.root()
    }

    /// Read the effective policy; permissive defaults when none is installed.
    pub fn policy(&self) -> Result<Policy> {
        self.store.read_policy()
    }

    /// Replace the stored policy atomically.
    ///
    /// Repository roots are canonicalized and must be existing directories.
    pub fn set_policy(&self, mut policy: Policy) -> Result<Policy> {
        let _lock = self.store.lock_global()?;
        let _project_locks = self.store.lock_all_projects()?;
        for root in &mut policy.allowed_repository_roots {
            *root = canonical_existing(root)?;
            if !root.is_dir() {
                return Err(Error::PolicyViolation(format!(
                    "allowed repository root is not a directory: {}",
                    root.display()
                )));
            }
        }
        policy.allowed_repository_roots.sort();
        policy.allowed_repository_roots.dedup();
        policy.validate()?;
        self.store.write_policy(&policy)?;
        Ok(policy)
    }

    /// Evaluate current state against the effective policy without mutating it.
    pub fn policy_report(&self) -> Result<PolicyReport> {
        let _lock = self.store.lock_global()?;
        let _project_locks = self.store.lock_all_projects()?;
        let policy = self.store.read_policy()?;
        let capsules = self.store.list_capsules()?;
        let violations = self.policy_violations(&policy, &capsules)?;
        Ok(PolicyReport {
            compliant: violations.is_empty(),
            violations,
        })
    }

    /// Summarize stored records, including ones whose schema is unsupported.
    pub fn inspect_state(&self) -> Result<StateInspection> {
        self.store.inspect()
    }

    /// Copy durable manifests, results, patches, and policy to a new directory.
    ///
    /// Live workspaces and Git object databases are deliberately excluded.
    /// `backup.json` is written last as the completion marker.
    pub fn backup_state(&self, destination: impl AsRef<Path>) -> Result<BackupReport> {
        self.store.backup(destination.as_ref())
    }

    /// Retained lifecycle events for one capsule, oldest first.
    pub fn audit_events(&self, id: &str) -> Result<Vec<AuditEvent>> {
        Ok(self.show(id)?.audit_events)
    }

    /// Retained lifecycle events across all capsules, merged in time order.
    pub fn audit_log(&self) -> Result<Vec<AuditEvent>> {
        let _lock = self.store.lock_global()?;
        let _project_locks = self.store.lock_all_projects()?;
        let mut sequenced = Vec::new();
        for capsule in self.store.list_capsules()? {
            for (sequence, event) in capsule.audit_events.into_iter().enumerate() {
                sequenced.push((capsule.id.clone(), sequence, event));
            }
        }
        sequenced.sort_by(|left, right| {
            left.2
                .occurred_at_unix
                .cmp(&right.2.occurred_at_unix)
                .then_with(|| left.0.cmp(&right.0))
                .then_with(|| left.1.cmp(&right.1))
        });
        Ok(sequenced.into_iter().map(|(_, _, event)| event).collect())
    }

    /// Compute an instantaneous snapshot of aggregate counters.
    pub fn metrics(&self) -> Result<MetricsSnapshot> {
        let _lock = self.store.lock_global()?;
        let _project_locks = self.store.lock_all_projects()?;
        let capsules = self.store.list_capsules()?;
        let mut states = BTreeMap::new();
        let mut live_capsules = 0_u64;
        let mut sealed_results = 0_u64;
        let mut result_patch_bytes = 0_u64;
        let mut audit_events = 0_u64;
        let mut audit_events_dropped = 0_u64;
        for capsule in &capsules {
            *states
                .entry(state_name(capsule.state).to_owned())
                .or_insert(0) += 1;
            if capsule.state != CapsuleState::Dropped {
                live_capsules += 1;
            }
            if let Some(result) = &capsule.result {
                sealed_results += 1;
                result_patch_bytes = result_patch_bytes.saturating_add(result.patch_bytes);
            }
            audit_events = audit_events.saturating_add(capsule.audit_events.len() as u64);
            audit_events_dropped =
                audit_events_dropped.saturating_add(capsule.audit_events_dropped);
        }
        Ok(MetricsSnapshot {
            observed_at_unix: now()?,
            capsules: capsules.len() as u64,
            live_capsules,
            sealed_results,
            result_patch_bytes,
            state_bytes: self.store.state_bytes()?,
            workspace_bytes: self.store.workspace_bytes()?,
            audit_events,
            audit_events_dropped,
            states,
        })
    }

    /// Describe the sealed artifacts of a closed capsule.
    ///
    /// Revalidates the seal first, so descriptors always match live bytes.
    pub fn artifacts(&self, id: &str) -> Result<ArtifactBundle> {
        self.artifact_snapshot(id).map(|(bundle, _, _)| bundle)
    }

    /// Open one sealed artifact as a bounded reader over a validated snapshot.
    pub fn open_artifact(&self, id: &str, kind: ArtifactKind) -> Result<ArtifactReader> {
        let (_, result, patch) = self.artifact_snapshot(id)?;
        Ok(ArtifactReader::new(match kind {
            ArtifactKind::ResultManifest => result,
            ArtifactKind::ResultPatch => patch,
        }))
    }

    /// Stream every sealed artifact into a caller-provided sink.
    pub fn publish_artifacts<S: ArtifactSink + ?Sized>(
        &self,
        id: &str,
        sink: &mut S,
    ) -> Result<Vec<PublishedArtifact>> {
        let (bundle, result, patch) = self.artifact_snapshot(id)?;
        let mut result = Some(result);
        let mut patch = Some(patch);
        let mut published = Vec::with_capacity(bundle.artifacts.len());
        for descriptor in bundle.artifacts {
            let bytes = match descriptor.kind {
                ArtifactKind::ResultManifest => result.take(),
                ArtifactKind::ResultPatch => patch.take(),
            }
            .ok_or_else(|| {
                Error::UnsafeState(format!(
                    "artifact bundle contains duplicate kind {:?}",
                    descriptor.kind
                ))
            })?;
            let mut source = ArtifactReader::new(bytes);
            let uri = sink.put(&descriptor, &mut source)?;
            published.push(PublishedArtifact { descriptor, uri });
        }
        Ok(published)
    }

    /// Write a sealed result to a new directory as a portable receipt.
    ///
    /// Produces `result.json`, `result.patch`, and finally `bundle.json` as the
    /// completion marker. Verify the directory later with
    /// [`verify_bundle`](crate::verify_bundle).
    pub fn export_artifacts(
        &self,
        id: &str,
        destination: impl AsRef<Path>,
    ) -> Result<ExportReport> {
        let (bundle, result, patch) = self.artifact_snapshot(id)?;
        let destination = self.store.external_destination(destination.as_ref())?;
        let mut exported_bundle = bundle.clone();
        for descriptor in &mut exported_bundle.artifacts {
            // Reference artifacts relative to the bundle rather than by absolute
            // path. A receipt is meant to travel: an exporting machine's
            // directory layout is meaningless to whoever verifies it later, and
            // embedding it would publish that layout in any repository or
            // artifact store the receipt is committed to.
            descriptor.uri = descriptor.name.clone();
        }
        let mut manifest =
            serde_json::to_vec_pretty(&exported_bundle).map_err(|source| Error::Json {
                path: PathBuf::from("bundle.json"),
                source,
            })?;
        manifest.push(b'\n');
        StateStore::export_artifacts(
            &destination,
            &[
                ("bundle.json", &manifest),
                ("result.json", &result),
                ("result.patch", &patch),
            ],
        )?;
        Ok(ExportReport {
            bundle: exported_bundle,
            output_directory: destination,
        })
    }

    /// Create a capsule and its isolated worktree from a pinned commit.
    pub fn create(&self, options: CreateOptions) -> Result<Capsule> {
        validate_create_options(&options)?;
        let repository = self.git.repository(&options.repository)?;
        if self.git.sparse_checkout(&repository.worktree)? {
            return Err(Error::InvalidInput(
                "cannot create a capsule from a sparse-checkout worktree; disable sparse checkout first"
                    .to_owned(),
            ));
        }
        let base_commit = self
            .git
            .resolve_commit(&repository.worktree, &options.base)?;
        let project_key = project_key(&repository.common_dir)?;
        let _global_lock = self.store.lock_global()?;
        let _lock = self.store.lock_project(&project_key)?;
        let policy = self.store.read_policy()?;
        let capsules = self.store.list_capsules()?;
        self.enforce_create_policy(&policy, &capsules, &repository)?;
        let id = format!("cap-{}", Ulid::new().to_string().to_ascii_lowercase());
        let branch = format!("capsule/{}", &id[4..]);
        let workspace_path = self.store.workspace_path(&project_key, &id)?;
        self.store.prepare_capsule(&id, &project_key)?;
        let created_at = now()?;
        let mut capsule = Capsule {
            schema_version: SCHEMA_VERSION,
            id,
            label: options.label,
            links: options.links,
            state: CapsuleState::Creating,
            source_worktree: repository.worktree.clone(),
            repository_common_dir: repository.common_dir.clone(),
            workspace_git_dir: None,
            workspace_path,
            project_key,
            branch,
            base_commit,
            created_at_unix: created_at,
            updated_at_unix: created_at,
            checkpoints: Vec::new(),
            checkpoint: None,
            evidence: Vec::new(),
            audit_events: Vec::new(),
            audit_events_dropped: 0,
            result: None,
            integration: None,
            cleanup: None,
            closed_at_unix: None,
            dropped_at_unix: None,
        };
        self.store.write_capsule(&capsule)?;
        self.git.add_worktree(
            &repository.worktree,
            &capsule.workspace_path,
            &capsule.branch,
            &capsule.base_commit,
        )?;
        capsule.workspace_git_dir = Some(self.git.repository(&capsule.workspace_path)?.git_dir);
        self.validate_owned_worktree(&capsule)?;
        capsule.state = CapsuleState::Active;
        capsule.updated_at_unix = now()?;
        let base_commit = capsule.base_commit.clone();
        append_event(
            &mut capsule,
            AuditEventKind::Created,
            Some(CapsuleState::Creating),
            CapsuleState::Active,
            BTreeMap::from([("base_commit".to_owned(), base_commit)]),
        )?;
        self.store.write_capsule(&capsule)?;
        Ok(capsule)
    }

    /// Summarize every durable capsule record, ordered by identifier.
    pub fn list(&self) -> Result<Vec<CapsuleSummary>> {
        let _lock = self.store.lock_global()?;
        Ok(self
            .store
            .list_capsules()?
            .iter()
            .map(CapsuleSummary::from)
            .collect())
    }

    /// Read one capsule manifest, revalidating its identity fields.
    pub fn show(&self, id: &str) -> Result<Capsule> {
        self.store
            .read_capsule(id)
            .map_err(|error| not_found(id, error))
    }

    /// Filesystem directory a capsule's attempt works in.
    pub fn workspace_path(&self, id: &str) -> Result<PathBuf> {
        Ok(self.show(id)?.workspace_path)
    }

    /// Inspect a capsule's workspace health, changes, and seal state.
    pub fn status(&self, id: &str) -> Result<CapsuleStatus> {
        let capsule = self.show(id)?;
        self.status_for(capsule)
    }

    /// Complete patch from the pinned base: sealed if closed, live if active.
    pub fn diff(&self, id: &str) -> Result<Vec<u8>> {
        let capsule = self.show(id)?;
        match capsule.state {
            CapsuleState::Closed | CapsuleState::Integrating | CapsuleState::Integrated => self
                .sealed_artifacts(&capsule)
                .and_then(|(matches, _, patch)| {
                    if matches {
                        Ok(patch)
                    } else {
                        Err(Error::ResultDrift(capsule.id.clone()))
                    }
                }),
            CapsuleState::Dropping | CapsuleState::Dropped if capsule.result.is_some() => self
                .sealed_artifacts(&capsule)
                .and_then(|(matches, _, patch)| {
                    if matches {
                        Ok(patch)
                    } else {
                        Err(Error::ResultDrift(capsule.id.clone()))
                    }
                }),
            CapsuleState::Active | CapsuleState::Checkpointing => {
                self.validate_owned_worktree(&capsule)?;
                let snapshot = self.snapshot(&capsule)?;
                Ok(snapshot.patch)
            }
            CapsuleState::Creating | CapsuleState::Orphaned => {
                Err(invalid_state(&capsule, "active or a sealed result"))
            }
            CapsuleState::Dropping | CapsuleState::Dropped => Ok(Vec::new()),
        }
    }

    /// Read a sealed result, failing on drift.
    pub fn result(&self, id: &str) -> Result<CapsuleResult> {
        let capsule = self.show(id)?;
        if capsule.result.is_none() {
            return Err(invalid_state(
                &capsule,
                "closed, integrating, integrated, or dropped result",
            ));
        }
        let (matches, result, _) = self.sealed_artifacts(&capsule)?;
        if !matches {
            return Err(Error::ResultDrift(capsule.id));
        }
        Ok(result)
    }

    /// Path to the sealed patch file, after confirming it still matches its seal.
    pub fn result_patch_path(&self, id: &str) -> Result<PathBuf> {
        let capsule = self.show(id)?;
        if capsule.result.is_none() {
            return Err(invalid_state(&capsule, "a sealed result"));
        }
        let (matches, _, _) = self.sealed_artifacts(&capsule)?;
        if !matches {
            return Err(Error::ResultDrift(capsule.id));
        }
        Ok(self.store.capsule_dir(id)?.join("result.patch"))
    }

    /// Commit the workspace's current state as a durable checkpoint.
    ///
    /// The commit is built through a private index and journaled before the
    /// capsule branch advances, so an interrupted checkpoint is recoverable.
    pub fn checkpoint(&self, id: &str, options: CheckpointOptions) -> Result<Checkpoint> {
        validate_message(&options.message, "checkpoint message")?;
        validate_author(&options.author)?;
        let mut capsule = self.show(id)?;
        let _global_lock = self.store.lock_global()?;
        let _lock = self.store.lock_project(&capsule.project_key)?;
        capsule = self.store.read_capsule(id)?;
        require_state(&capsule, CapsuleState::Active, "active")?;
        let policy = self.enforce_capsule_policy(&capsule)?;
        self.validate_owned_worktree(&capsule)?;
        let head_before = self.git.head(&capsule.workspace_path)?;
        let checkpoint_snapshot = self.snapshot_against(&capsule, &head_before)?;
        let (ignored_paths, ignored_bytes) =
            self.ignored_usage_for_policy(&policy, &capsule.workspace_path)?;
        if checkpoint_snapshot.patch.is_empty() {
            return Err(Error::InvalidInput("nothing to checkpoint".to_owned()));
        }
        let index = self.store.temporary_index(&capsule.id)?;
        let head_after = self.git.commit_patch(&CommitPatch {
            worktree: &capsule.workspace_path,
            base: &head_before,
            patch: &checkpoint_snapshot.patch,
            index: index.path(),
            message: &options.message,
            name: &options.author.name,
            email: &options.author.email,
        })?;
        let prepared =
            self.git
                .commit_snapshot(&capsule.workspace_path, &head_before, &head_after)?;
        if self.git.parents(&capsule.workspace_path, &head_after)? != [head_before.clone()]
            || prepared.patch != checkpoint_snapshot.patch
            || prepared.changed_paths != checkpoint_snapshot.changed_paths
        {
            return Err(Error::UnsafeState(
                "prepared checkpoint commit does not reproduce the workspace snapshot".to_owned(),
            ));
        }
        let result_snapshot =
            self.git
                .commit_snapshot(&capsule.workspace_path, &capsule.base_commit, &head_after)?;
        Self::enforce_result_policy(
            &policy,
            result_snapshot.patch.len() as u64,
            result_snapshot.changed_paths.len(),
            ignored_paths,
            ignored_bytes,
        )?;
        // Prove the manifest can still record this checkpoint before the branch
        // advances. Failing afterwards would strand the capsule in
        // `Checkpointing`, and every recovery attempt would fail the same way.
        let started_at = now()?;
        let journal = CheckpointJournal {
            head_before: head_before.clone(),
            head_after: head_after.clone(),
            patch_sha256: sha256_hex(&checkpoint_snapshot.patch),
            message: options.message,
            author_name: options.author.name,
            author_email: options.author.email,
            started_at_unix: started_at,
        };
        Self::project_checkpoint(&capsule, &journal)?;
        self.git.create_ref(
            &capsule.workspace_path,
            &checkpoint_ref(&capsule),
            &head_after,
        )?;
        capsule.state = CapsuleState::Checkpointing;
        capsule.checkpoint = Some(journal);
        capsule.updated_at_unix = started_at;
        self.store.write_capsule(&capsule)?;

        let checkpoint = self.finish_checkpoint(&mut capsule)?.ok_or_else(|| {
            Error::UnsafeState("checkpoint side effect was not observable".to_owned())
        })?;
        capsule.updated_at_unix = now()?;
        append_event(
            &mut capsule,
            AuditEventKind::Checkpointed,
            Some(CapsuleState::Checkpointing),
            CapsuleState::Active,
            BTreeMap::from([("commit".to_owned(), checkpoint.commit.clone())]),
        )?;
        self.store.write_capsule(&capsule)?;
        Ok(checkpoint)
    }

    /// Attach a verification claim to an active capsule.
    ///
    /// Bounded to 64 records and 256 KiB of text per capsule.
    pub fn add_evidence(&self, id: &str, input: EvidenceInput) -> Result<Evidence> {
        validate_bounded_text(
            &input.command,
            EVIDENCE_COMMAND_CAP,
            "evidence command",
            false,
        )?;
        if let Some(summary) = &input.summary {
            validate_bounded_text(summary, EVIDENCE_SUMMARY_CAP, "evidence summary", true)?;
        }
        let mut capsule = self.show(id)?;
        let _global_lock = self.store.lock_global()?;
        let _lock = self.store.lock_project(&capsule.project_key)?;
        capsule = self.store.read_capsule(id)?;
        require_state(&capsule, CapsuleState::Active, "active")?;
        self.enforce_capsule_policy(&capsule)?;
        if capsule.evidence.len() >= EVIDENCE_COUNT_CAP {
            return Err(Error::InvalidInput(format!(
                "a capsule retains at most {EVIDENCE_COUNT_CAP} evidence records"
            )));
        }
        let stored_evidence_bytes: usize = capsule
            .evidence
            .iter()
            .map(|item| item.command.len() + item.summary.as_ref().map_or(0, String::len))
            .sum();
        let pending_bytes = input.command.len() + input.summary.as_ref().map_or(0, String::len);
        if stored_evidence_bytes.saturating_add(pending_bytes) > EVIDENCE_TOTAL_BYTES_CAP {
            return Err(Error::InvalidInput(format!(
                "total evidence payload would exceed the {EVIDENCE_TOTAL_BYTES_CAP}-byte capsule bound"
            )));
        }
        let evidence = Evidence {
            command: input.command,
            exit_code: input.exit_code,
            summary: input.summary,
            recorded_at_unix: now()?,
        };
        // The byte caps above count raw input; JSON escaping can still inflate
        // it, so confirm the encoded manifest fits before recording anything.
        let mut projected = capsule.clone();
        projected.evidence.push(evidence.clone());
        crate::state::ensure_manifest_capacity(&projected)?;
        capsule.evidence.push(evidence.clone());
        capsule.updated_at_unix = now()?;
        let evidence_index = capsule.evidence.len() - 1;
        append_event(
            &mut capsule,
            AuditEventKind::EvidenceAdded,
            Some(CapsuleState::Active),
            CapsuleState::Active,
            BTreeMap::from([
                ("evidence_index".to_owned(), evidence_index.to_string()),
                (
                    "command_sha256".to_owned(),
                    sha256_hex(evidence.command.as_bytes()),
                ),
                ("exit_code".to_owned(), evidence.exit_code.to_string()),
            ]),
        )?;
        self.store.write_capsule(&capsule)?;
        Ok(evidence)
    }

    /// Seal the capsule into an immutable result and patch.
    ///
    /// Captures committed, staged, unstaged, deleted, and non-ignored untracked
    /// content as one complete change against the pinned base.
    pub fn close(&self, id: &str, options: CloseOptions) -> Result<CapsuleResult> {
        let mut capsule = self.show(id)?;
        let _global_lock = self.store.lock_global()?;
        let _lock = self.store.lock_project(&capsule.project_key)?;
        capsule = self.store.read_capsule(id)?;
        require_state(&capsule, CapsuleState::Active, "active")?;
        let policy = self.enforce_capsule_policy(&capsule)?;
        self.validate_owned_worktree(&capsule)?;
        if options.require_successful_evidence
            && (capsule.evidence.is_empty()
                || capsule.evidence.iter().any(|item| item.exit_code != 0))
        {
            return Err(Error::InvalidInput(
                "successful evidence is required, but evidence is absent or contains failures"
                    .to_owned(),
            ));
        }
        let snapshot = self.snapshot(&capsule)?;
        let ignored_paths = self.git.ignored_paths(&capsule.workspace_path)?;
        let (ignored_bytes, ignored_content_sha256) =
            ignored_content_inventory(&capsule.workspace_path, &ignored_paths)?;
        Self::enforce_result_policy(
            &policy,
            snapshot.patch.len() as u64,
            snapshot.changed_paths.len(),
            ignored_paths.len(),
            ignored_bytes,
        )?;
        let head = self.git.head(&capsule.workspace_path)?;
        let clean = self.git.clean(&capsule.workspace_path)?;
        let kind = if snapshot.patch.is_empty() {
            ResultKind::NoChange
        } else if clean {
            ResultKind::Commit
        } else {
            ResultKind::Patch
        };
        let sealed_at = now()?;
        let digest = sha256_hex(&snapshot.patch);
        let result = CapsuleResult {
            schema_version: SCHEMA_VERSION,
            capsule_id: capsule.id.clone(),
            label: capsule.label.clone(),
            links: capsule.links.clone(),
            kind,
            base_commit: capsule.base_commit.clone(),
            head_commit: head.clone(),
            patch_sha256: digest.clone(),
            patch_bytes: snapshot.patch.len() as u64,
            changed_paths: snapshot.changed_paths.clone(),
            ignored_bytes,
            ignored_content_sha256: Some(ignored_content_sha256),
            ignored_paths,
            checkpoints: capsule.checkpoints.clone(),
            evidence: capsule.evidence.clone(),
            created_at_unix: capsule.created_at_unix,
            sealed_at_unix: sealed_at,
        };
        let result_digest = result_sha256(&result)?;
        self.store.write_patch(id, &snapshot.patch)?;
        self.store.write_result(id, &result)?;
        capsule.result = Some(ResultRef {
            kind,
            head_commit: head,
            patch_sha256: digest,
            result_sha256: result_digest,
            patch_bytes: snapshot.patch.len() as u64,
            changed_paths: snapshot.changed_paths.len(),
            sealed_at_unix: sealed_at,
        });
        capsule.state = CapsuleState::Closed;
        capsule.closed_at_unix = Some(sealed_at);
        capsule.updated_at_unix = sealed_at;
        append_event(
            &mut capsule,
            AuditEventKind::Closed,
            Some(CapsuleState::Active),
            CapsuleState::Closed,
            BTreeMap::from([
                ("patch_sha256".to_owned(), result.patch_sha256.clone()),
                ("patch_bytes".to_owned(), result.patch_bytes.to_string()),
            ]),
        )?;
        self.store.write_capsule(&capsule)?;
        Ok(result)
    }

    /// Apply a sealed result to a clean target still at the pinned base.
    ///
    /// The candidate commit is built in a private index, checked for one exact
    /// parent and byte-identical reproduction of the sealed patch, protected by
    /// a namespaced ref, and only then fast-forwarded. Never rebases, merges,
    /// resolves conflicts, or pushes.
    pub fn integrate(&self, id: &str, options: &IntegrateOptions) -> Result<Capsule> {
        validate_author(&options.author)?;
        if let Some(message) = &options.message {
            validate_message(message, "integration message")?;
        }
        let mut capsule = self.show(id)?;
        let _global_lock = self.store.lock_global()?;
        let _lock = self.store.lock_project(&capsule.project_key)?;
        capsule = self.store.read_capsule(id)?;
        require_state(&capsule, CapsuleState::Closed, "closed")?;
        let policy = self.enforce_capsule_policy(&capsule)?;
        self.ensure_sealed(&capsule)?;
        let (target, target_before, target_head_ref) =
            self.validate_integration_target(&capsule, &options.target)?;
        let result = self.store.read_result(id)?;
        let patch = self.store.read_patch(id)?;
        let (ignored_paths, ignored_bytes) =
            self.ignored_usage_for_policy(&policy, &capsule.workspace_path)?;
        Self::enforce_result_policy(
            &policy,
            patch.len() as u64,
            result.changed_paths.len(),
            ignored_paths,
            ignored_bytes,
        )?;
        self.start_integration(
            &mut capsule,
            &target,
            &target_before,
            target_head_ref,
            options,
        )?;

        let proposed_head = match self.prepare_integration(&capsule, &target, &result, &patch) {
            Ok(head) => head,
            Err(error) => {
                self.abort_integration(&mut capsule, &error)?;
                return Err(error);
            }
        };
        if proposed_head != target_before {
            self.git
                .create_ref(&target.worktree, &integration_ref(&capsule), &proposed_head)?;
        }
        capsule
            .integration
            .as_mut()
            .ok_or_else(|| Error::UnsafeState("integration record disappeared".to_owned()))?
            .target_head_after = Some(proposed_head.clone());
        capsule.updated_at_unix = now()?;
        self.store.write_capsule(&capsule)?;

        let current_target = self.git.repository(&target.worktree)?;
        if current_target.common_dir != capsule.repository_common_dir
            || current_target.git_dir != target.git_dir
            || self.git.head_ref(&current_target.worktree)?
                != capsule
                    .integration
                    .as_ref()
                    .ok_or_else(|| Error::UnsafeState("integration record disappeared".to_owned()))?
                    .target_head_ref
            || !self.git.clean(&current_target.worktree)?
            || self.git.head(&current_target.worktree)? != target_before
        {
            return Err(Error::ForeignWorktree(target.worktree));
        }
        if proposed_head != target_before {
            self.git.fast_forward(&target.worktree, &proposed_head)?;
        }

        let integrated_at = now()?;
        let integration = capsule
            .integration
            .as_mut()
            .ok_or_else(|| Error::UnsafeState("integration record disappeared".to_owned()))?;
        integration.integrated_at_unix = Some(integrated_at);
        capsule.state = CapsuleState::Integrated;
        capsule.updated_at_unix = integrated_at;
        if proposed_head != target_before {
            self.git.delete_ref_if_matches(
                &target.worktree,
                &integration_ref(&capsule),
                &proposed_head,
            )?;
        }
        append_event(
            &mut capsule,
            AuditEventKind::Integrated,
            Some(CapsuleState::Integrating),
            CapsuleState::Integrated,
            BTreeMap::from([("target_head_after".to_owned(), proposed_head)]),
        )?;
        self.store.write_capsule(&capsule)?;
        Ok(capsule)
    }

    fn start_integration(
        &self,
        capsule: &mut Capsule,
        target: &Repository,
        target_before: &str,
        target_head_ref: String,
        options: &IntegrateOptions,
    ) -> Result<()> {
        let started_at = now()?;
        capsule.state = CapsuleState::Integrating;
        capsule.integration = Some(Integration {
            target_worktree: target.worktree.clone(),
            target_git_dir: target.git_dir.clone(),
            target_head_ref,
            target_head_before: target_before.to_owned(),
            target_head_after: None,
            commit_message: options.message.clone().unwrap_or_else(|| {
                capsule
                    .label
                    .as_ref()
                    .map_or_else(|| format!("Integrate capsule {}", capsule.id), Clone::clone)
            }),
            author_name: options.author.name.clone(),
            author_email: options.author.email.clone(),
            started_at_unix: started_at,
            integrated_at_unix: None,
        });
        capsule.updated_at_unix = started_at;
        append_event(
            capsule,
            AuditEventKind::IntegrationStarted,
            Some(CapsuleState::Closed),
            CapsuleState::Integrating,
            BTreeMap::from([
                (
                    "target_worktree_sha256".to_owned(),
                    sha256_hex(target.worktree.to_string_lossy().as_bytes()),
                ),
                ("target_head_before".to_owned(), target_before.to_owned()),
            ]),
        )?;
        self.store.write_capsule(capsule)
    }

    fn abort_integration(&self, capsule: &mut Capsule, error: &Error) -> Result<()> {
        capsule.state = CapsuleState::Closed;
        capsule.integration = None;
        capsule.updated_at_unix = now()?;
        append_event(
            capsule,
            AuditEventKind::IntegrationAborted,
            Some(CapsuleState::Integrating),
            CapsuleState::Closed,
            BTreeMap::from([("error".to_owned(), bounded_error(error))]),
        )?;
        self.store.write_capsule(capsule)
    }

    /// Remove a capsule's owned worktree and branch, keeping its durable record.
    ///
    /// Refuses paths that no longer prove they are the worktree this capsule
    /// created, even when `force` is set.
    pub fn drop_capsule(&self, id: &str, force: bool) -> Result<Capsule> {
        let mut capsule = self.show(id)?;
        let _global_lock = self.store.lock_global()?;
        let _lock = self.store.lock_project(&capsule.project_key)?;
        capsule = self.store.read_capsule(id)?;
        if capsule.state == CapsuleState::Dropped {
            return Ok(capsule);
        }
        if capsule.state == CapsuleState::Dropping {
            self.finish_cleanup(&mut capsule)?;
            capsule.updated_at_unix = now()?;
            append_event(
                &mut capsule,
                AuditEventKind::Recovered,
                Some(CapsuleState::Dropping),
                CapsuleState::Dropped,
                BTreeMap::from([(
                    "action".to_owned(),
                    "completed cleanup requested before restart".to_owned(),
                )]),
            )?;
            self.store.write_capsule(&capsule)?;
            return Ok(capsule);
        }
        if matches!(
            capsule.state,
            CapsuleState::Creating | CapsuleState::Checkpointing | CapsuleState::Integrating
        ) && !force
        {
            return Err(invalid_state(
                &capsule,
                "closed, integrated, orphaned, or --force",
            ));
        }
        if capsule.state == CapsuleState::Active && !force {
            return Err(Error::UnsealedChanges(id.to_owned()));
        }
        let previous_state = capsule.state;
        let require_sealed = matches!(
            capsule.state,
            CapsuleState::Closed | CapsuleState::Integrated
        ) && !force;
        if require_sealed {
            self.ensure_sealed(&capsule)?;
        }

        let execution_root = self.execution_root(&capsule)?;
        let branch_head = self.git.branch_head(&execution_root, &capsule.branch)?;
        if capsule.workspace_path.exists() {
            if capsule.workspace_git_dir.is_none() && capsule.state == CapsuleState::Creating {
                capsule.workspace_git_dir =
                    Some(self.git.repository(&capsule.workspace_path)?.git_dir);
            }
            self.validate_owned_worktree(&capsule)?;
            let workspace_head = self.git.head(&capsule.workspace_path)?;
            if branch_head.as_deref() != Some(workspace_head.as_str()) {
                return Err(Error::ForeignWorktree(capsule.workspace_path.clone()));
            }
        } else if require_sealed {
            return Err(Error::ForeignWorktree(capsule.workspace_path.clone()));
        } else if let Some(record) = self.registered_record(&capsule)? {
            Self::validate_registered_record(&capsule, &record, branch_head.as_deref())?;
        } else if branch_head
            .as_deref()
            .is_some_and(|head| !recorded_capsule_head(&capsule, head))
        {
            return Err(Error::ForeignWorktree(capsule.workspace_path.clone()));
        }

        let started_at = now()?;
        capsule.state = CapsuleState::Dropping;
        capsule.cleanup = Some(Cleanup {
            branch_head,
            require_sealed,
            started_at_unix: started_at,
        });
        capsule.updated_at_unix = started_at;
        append_event(
            &mut capsule,
            AuditEventKind::CleanupStarted,
            Some(previous_state),
            CapsuleState::Dropping,
            BTreeMap::from([
                ("force".to_owned(), force.to_string()),
                ("require_sealed".to_owned(), require_sealed.to_string()),
            ]),
        )?;
        self.store.write_capsule(&capsule)?;

        self.finish_cleanup(&mut capsule)?;
        capsule.updated_at_unix = now()?;
        append_event(
            &mut capsule,
            AuditEventKind::Dropped,
            Some(CapsuleState::Dropping),
            CapsuleState::Dropped,
            BTreeMap::new(),
        )?;
        self.store.write_capsule(&capsule)?;
        Ok(capsule)
    }

    /// Reconcile interrupted lifecycle transitions.
    ///
    /// Completes only transitions whose worktree identity, refs, commit parents,
    /// patch digests, and journals all agree; anything ambiguous is left for
    /// explicit inspection. Safe to call at process startup.
    pub fn recover(&self) -> Result<Vec<RecoveryAction>> {
        let _global_lock = self.store.lock_global()?;
        let capsules = self.store.list_capsules()?;
        let mut actions = Vec::new();
        for listed in capsules {
            let _project_lock = self.store.lock_project(&listed.project_key)?;
            let mut capsule = self.store.read_capsule(&listed.id)?;
            let previous = capsule.state;
            let action = match capsule.state {
                CapsuleState::Creating => Some(self.recover_creating(&mut capsule)?),
                CapsuleState::Checkpointing => self.recover_checkpointing(&mut capsule)?,
                CapsuleState::Active => self.recover_active(&mut capsule)?,
                CapsuleState::Integrating => self.recover_integrating(&mut capsule)?,
                CapsuleState::Dropping => Some(self.finish_cleanup(&mut capsule)?),
                CapsuleState::Closed
                | CapsuleState::Integrated
                | CapsuleState::Orphaned
                | CapsuleState::Dropped => None,
            };
            if let Some(action) = action {
                capsule.updated_at_unix = now()?;
                let recovered_state = capsule.state;
                append_event(
                    &mut capsule,
                    AuditEventKind::Recovered,
                    Some(previous),
                    recovered_state,
                    BTreeMap::from([("action".to_owned(), action.clone())]),
                )?;
                self.store.write_capsule(&capsule)?;
                actions.push(RecoveryAction {
                    capsule_id: capsule.id.clone(),
                    previous_state: previous,
                    state: capsule.state,
                    action,
                });
            }
        }
        Ok(actions)
    }

    fn policy_violations(&self, policy: &Policy, capsules: &[Capsule]) -> Result<Vec<String>> {
        policy.validate()?;
        let mut violations = Vec::new();
        let capsule_count = capsules.len() as u64;
        let live_count = capsules
            .iter()
            .filter(|capsule| capsule.state != CapsuleState::Dropped)
            .count() as u64;
        check_limit(
            &mut violations,
            "capsule records",
            capsule_count,
            policy.max_capsules,
        );
        check_limit(
            &mut violations,
            "live capsules",
            live_count,
            policy.max_live_capsules,
        );
        if policy.max_state_bytes.is_some() {
            check_limit(
                &mut violations,
                "state bytes",
                self.store.state_bytes()?,
                policy.max_state_bytes,
            );
        }
        if policy.max_workspace_bytes.is_some() {
            check_limit(
                &mut violations,
                "workspace bytes",
                self.store.workspace_bytes()?,
                policy.max_workspace_bytes,
            );
        }
        let observed_at = now()?;
        for capsule in capsules {
            violations.extend(self.capsule_policy_violations(policy, capsule, observed_at));
        }
        Ok(violations)
    }

    fn capsule_policy_violations(
        &self,
        policy: &Policy,
        capsule: &Capsule,
        observed_at: u64,
    ) -> Vec<String> {
        let mut violations = Vec::new();
        if !repository_allowed(policy, &capsule.source_worktree) {
            violations.push(format!(
                "capsule {} repository is outside allowed roots: {}",
                capsule.id,
                capsule.source_worktree.display()
            ));
        }
        if capsule.state != CapsuleState::Dropped {
            if let Some(limit) = policy.max_capsule_age_seconds {
                let age = observed_at.saturating_sub(capsule.created_at_unix);
                if age > limit {
                    violations.push(format!(
                        "capsule {} age {age} seconds exceeds limit {limit}",
                        capsule.id
                    ));
                }
            }
        }
        if let Some(reference) = &capsule.result {
            self.sealed_capsule_policy_violations(policy, capsule, reference, &mut violations);
        } else {
            self.active_capsule_policy_violations(policy, capsule, &mut violations);
        }
        violations
    }

    fn sealed_capsule_policy_violations(
        &self,
        policy: &Policy,
        capsule: &Capsule,
        reference: &ResultRef,
        violations: &mut Vec<String>,
    ) {
        check_capsule_limit(
            violations,
            &capsule.id,
            "patch bytes",
            reference.patch_bytes,
            Some(policy.max_patch_bytes),
        );
        check_capsule_limit(
            violations,
            &capsule.id,
            "changed paths",
            reference.changed_paths as u64,
            policy.max_changed_paths,
        );
        let result = match self.sealed_artifacts(capsule) {
            Ok((true, result, _)) => result,
            Ok((false, _, _)) => {
                violations.push(format!(
                    "capsule {} sealed result artifacts do not match their manifest",
                    capsule.id
                ));
                return;
            }
            Err(error) => {
                violations.push(format!(
                    "capsule {} result cannot be inspected: {error}",
                    capsule.id
                ));
                return;
            }
        };
        if policy.max_ignored_paths.is_none() && policy.max_ignored_bytes.is_none() {
            return;
        }
        let (ignored_paths, ignored_bytes) = if capsule.workspace_path.exists() {
            if let Err(error) = self.validate_owned_worktree(capsule) {
                violations.push(format!(
                    "capsule {} workspace cannot be inspected: {error}",
                    capsule.id
                ));
                (result.ignored_paths.len() as u64, result.ignored_bytes)
            } else {
                match self.git.ignored_paths(&capsule.workspace_path) {
                    Ok(paths) => {
                        let bytes = if policy.max_ignored_bytes.is_some() {
                            match ignored_usage(&capsule.workspace_path, &paths) {
                                Ok(bytes) => bytes,
                                Err(error) => {
                                    violations.push(format!(
                                        "capsule {} ignored bytes cannot be inspected: {error}",
                                        capsule.id
                                    ));
                                    result.ignored_bytes
                                }
                            }
                        } else {
                            0
                        };
                        (paths.len() as u64, bytes)
                    }
                    Err(error) => {
                        violations.push(format!(
                            "capsule {} ignored paths cannot be inspected: {error}",
                            capsule.id
                        ));
                        (result.ignored_paths.len() as u64, result.ignored_bytes)
                    }
                }
            }
        } else {
            (result.ignored_paths.len() as u64, result.ignored_bytes)
        };
        check_capsule_limit(
            violations,
            &capsule.id,
            "ignored paths",
            ignored_paths,
            policy.max_ignored_paths,
        );
        check_capsule_limit(
            violations,
            &capsule.id,
            "ignored bytes",
            ignored_bytes,
            policy.max_ignored_bytes,
        );
    }

    fn active_capsule_policy_violations(
        &self,
        policy: &Policy,
        capsule: &Capsule,
        violations: &mut Vec<String>,
    ) {
        if !matches!(
            capsule.state,
            CapsuleState::Active | CapsuleState::Checkpointing
        ) {
            return;
        }
        if let Err(error) = self.validate_owned_worktree(capsule) {
            violations.push(format!(
                "capsule {} active result usage cannot be inspected: {error}",
                capsule.id
            ));
            return;
        }
        match self.snapshot(capsule) {
            Ok(snapshot) => {
                check_capsule_limit(
                    violations,
                    &capsule.id,
                    "patch bytes",
                    snapshot.patch.len() as u64,
                    Some(policy.max_patch_bytes),
                );
                check_capsule_limit(
                    violations,
                    &capsule.id,
                    "changed paths",
                    snapshot.changed_paths.len() as u64,
                    policy.max_changed_paths,
                );
            }
            Err(error) => violations.push(format!(
                "capsule {} active result usage cannot be inspected: {error}",
                capsule.id
            )),
        }
        if policy.max_ignored_paths.is_none() && policy.max_ignored_bytes.is_none() {
            return;
        }
        match self.git.ignored_paths(&capsule.workspace_path) {
            Ok(ignored) => {
                check_capsule_limit(
                    violations,
                    &capsule.id,
                    "ignored paths",
                    ignored.len() as u64,
                    policy.max_ignored_paths,
                );
                if policy.max_ignored_bytes.is_some() {
                    match ignored_usage(&capsule.workspace_path, &ignored) {
                        Ok(bytes) => check_capsule_limit(
                            violations,
                            &capsule.id,
                            "ignored bytes",
                            bytes,
                            policy.max_ignored_bytes,
                        ),
                        Err(error) => violations.push(format!(
                            "capsule {} ignored bytes cannot be inspected: {error}",
                            capsule.id
                        )),
                    }
                }
            }
            Err(error) => violations.push(format!(
                "capsule {} ignored paths cannot be inspected: {error}",
                capsule.id
            )),
        }
    }

    fn enforce_create_policy(
        &self,
        policy: &Policy,
        capsules: &[Capsule],
        repository: &Repository,
    ) -> Result<()> {
        policy.validate()?;
        if !repository_allowed(policy, &repository.worktree) {
            return Err(Error::PolicyViolation(format!(
                "repository is outside allowed roots: {}",
                repository.worktree.display()
            )));
        }
        enforce_next_limit(
            "capsule records",
            capsules.len() as u64,
            policy.max_capsules,
        )?;
        enforce_next_limit(
            "live capsules",
            capsules
                .iter()
                .filter(|capsule| capsule.state != CapsuleState::Dropped)
                .count() as u64,
            policy.max_live_capsules,
        )?;
        if policy.max_state_bytes.is_some() {
            enforce_limit(
                "state bytes",
                self.store.state_bytes()?,
                policy.max_state_bytes,
            )?;
        }
        if policy.max_workspace_bytes.is_some() {
            enforce_limit(
                "workspace bytes",
                self.store.workspace_bytes()?,
                policy.max_workspace_bytes,
            )?;
        }
        Ok(())
    }

    fn enforce_capsule_policy(&self, capsule: &Capsule) -> Result<Policy> {
        let policy = self.store.read_policy()?;
        if !repository_allowed(&policy, &capsule.source_worktree) {
            return Err(Error::PolicyViolation(format!(
                "capsule repository is outside allowed roots: {}",
                capsule.source_worktree.display()
            )));
        }
        if let Some(limit) = policy.max_capsule_age_seconds {
            let age = now()?.saturating_sub(capsule.created_at_unix);
            if age > limit {
                return Err(Error::PolicyViolation(format!(
                    "capsule age {age} seconds exceeds limit {limit}"
                )));
            }
        }
        if policy.max_state_bytes.is_some() {
            enforce_limit(
                "state bytes",
                self.store.state_bytes()?,
                policy.max_state_bytes,
            )?;
        }
        if policy.max_workspace_bytes.is_some() {
            enforce_limit(
                "workspace bytes",
                self.store.workspace_bytes()?,
                policy.max_workspace_bytes,
            )?;
        }
        Ok(policy)
    }

    /// Ignored-content usage is measured only when a policy limit makes it
    /// relevant; the byte walk uses file metadata rather than reading content.
    fn ignored_usage_for_policy(&self, policy: &Policy, workspace: &Path) -> Result<(usize, u64)> {
        if policy.max_ignored_paths.is_none() && policy.max_ignored_bytes.is_none() {
            return Ok((0, 0));
        }
        let paths = self.git.ignored_paths(workspace)?;
        let bytes = if policy.max_ignored_bytes.is_some() {
            ignored_usage(workspace, &paths)?
        } else {
            0
        };
        Ok((paths.len(), bytes))
    }

    /// Confirm both manifests a checkpoint persists still fit.
    ///
    /// A checkpoint writes the manifest twice: once carrying the journal before
    /// the branch moves, and once carrying the finished checkpoint afterwards.
    /// The journaled form is the larger of the two, so checking only the final
    /// form would still let the first write fail and strand the capsule.
    fn project_checkpoint(capsule: &Capsule, journal: &CheckpointJournal) -> Result<()> {
        if capsule.checkpoints.len() >= CHECKPOINT_COUNT_CAP {
            return Err(Error::InvalidInput(format!(
                "a capsule retains at most {CHECKPOINT_COUNT_CAP} checkpoints; close this capsule and start another"
            )));
        }
        let mut journaled = capsule.clone();
        journaled.state = CapsuleState::Checkpointing;
        journaled.checkpoint = Some(journal.clone());
        crate::state::ensure_manifest_capacity(&journaled)?;

        let mut completed = capsule.clone();
        completed.state = CapsuleState::Active;
        completed.checkpoint = None;
        completed.checkpoints.push(Checkpoint {
            commit: journal.head_after.clone(),
            message: journal.message.clone(),
            author_name: journal.author_name.clone(),
            author_email: journal.author_email.clone(),
            created_at_unix: journal.started_at_unix,
        });
        append_event(
            &mut completed,
            AuditEventKind::Checkpointed,
            Some(CapsuleState::Checkpointing),
            CapsuleState::Active,
            BTreeMap::from([("commit".to_owned(), journal.head_after.clone())]),
        )?;
        crate::state::ensure_manifest_capacity(&completed)
    }

    fn enforce_result_policy(
        policy: &Policy,
        patch_bytes: u64,
        changed_paths: usize,
        ignored_paths: usize,
        ignored_bytes: u64,
    ) -> Result<()> {
        enforce_limit("patch bytes", patch_bytes, Some(policy.max_patch_bytes))?;
        enforce_limit(
            "changed paths",
            changed_paths as u64,
            policy.max_changed_paths,
        )?;
        enforce_limit(
            "ignored paths",
            ignored_paths as u64,
            policy.max_ignored_paths,
        )?;
        enforce_limit("ignored bytes", ignored_bytes, policy.max_ignored_bytes)
    }

    fn status_for(&self, capsule: Capsule) -> Result<CapsuleStatus> {
        if capsule.state == CapsuleState::Dropped {
            return Ok(CapsuleStatus {
                capsule,
                health: CapsuleHealth::Dropped,
                head_commit: None,
                dirty: None,
                changed_paths: Vec::new(),
                ignored_paths: Vec::new(),
                commits_ahead: None,
                sealed: None,
            });
        }
        if capsule.state == CapsuleState::Creating {
            return Ok(CapsuleStatus {
                capsule,
                health: CapsuleHealth::IncompleteCreation,
                head_commit: None,
                dirty: None,
                changed_paths: Vec::new(),
                ignored_paths: Vec::new(),
                commits_ahead: None,
                sealed: None,
            });
        }
        if !capsule.workspace_path.exists() {
            return Ok(CapsuleStatus {
                capsule,
                health: CapsuleHealth::MissingWorktree,
                head_commit: None,
                dirty: None,
                changed_paths: Vec::new(),
                ignored_paths: Vec::new(),
                commits_ahead: None,
                sealed: None,
            });
        }
        if self.validate_owned_worktree(&capsule).is_err() {
            return Ok(CapsuleStatus {
                capsule,
                health: CapsuleHealth::ForeignWorktree,
                head_commit: None,
                dirty: None,
                changed_paths: Vec::new(),
                ignored_paths: Vec::new(),
                commits_ahead: None,
                sealed: None,
            });
        }
        let snapshot = self.snapshot(&capsule)?;
        let ignored_paths = self.git.ignored_paths(&capsule.workspace_path)?;
        let head = self.git.head(&capsule.workspace_path)?;
        let dirty = !self.git.clean(&capsule.workspace_path)?;
        let commits_ahead = self
            .git
            .commits_ahead(&capsule.workspace_path, &capsule.base_commit)?;
        let sealed = capsule
            .result
            .as_ref()
            .map(|_| self.seal_matches(&capsule, &snapshot, &head))
            .transpose()?;
        let health = if sealed == Some(false)
            && matches!(
                capsule.state,
                CapsuleState::Closed
                    | CapsuleState::Integrating
                    | CapsuleState::Integrated
                    | CapsuleState::Dropping
            ) {
            CapsuleHealth::DriftedAfterClose
        } else if capsule.state == CapsuleState::Creating {
            CapsuleHealth::IncompleteCreation
        } else if capsule.state == CapsuleState::Checkpointing {
            CapsuleHealth::IncompleteCheckpoint
        } else {
            CapsuleHealth::Healthy
        };
        Ok(CapsuleStatus {
            capsule,
            health,
            head_commit: Some(head),
            dirty: Some(dirty),
            changed_paths: snapshot.changed_paths,
            ignored_paths,
            commits_ahead: Some(commits_ahead),
            sealed,
        })
    }

    fn validate_integration_target(
        &self,
        capsule: &Capsule,
        path: &Path,
    ) -> Result<(Repository, String, String)> {
        let target = self.git.repository(path)?;
        if target.common_dir != capsule.repository_common_dir {
            return Err(Error::ForeignWorktree(target.worktree));
        }
        if target.worktree == capsule.workspace_path {
            return Err(Error::InvalidInput(
                "cannot integrate a capsule into its own workspace".to_owned(),
            ));
        }
        if self.git.sparse_checkout(&target.worktree)?
            || self.git.hidden_index_entries(&target.worktree)?
        {
            return Err(Error::InvalidInput(
                "integration target uses sparse-checkout, skip-worktree, or assume-unchanged entries; restore a full checkout first"
                    .to_owned(),
            ));
        }
        if !self.git.clean(&target.worktree)? {
            return Err(Error::DirtyIntegrationTarget(target.worktree));
        }
        let head = self.git.head(&target.worktree)?;
        let head_ref = self.git.head_ref(&target.worktree)?;
        if head != capsule.base_commit {
            return Err(Error::InvalidInput(format!(
                "integration target HEAD {head} does not equal pinned base {}; update or recreate the capsule explicitly",
                capsule.base_commit
            )));
        }
        Ok((target, head, head_ref))
    }

    fn prepare_integration(
        &self,
        capsule: &Capsule,
        target: &Repository,
        result: &CapsuleResult,
        patch: &[u8],
    ) -> Result<String> {
        if result.kind == ResultKind::NoChange {
            return self.git.head(&target.worktree);
        }
        let integration = capsule
            .integration
            .as_ref()
            .ok_or_else(|| Error::UnsafeState("integration record disappeared".to_owned()))?;
        let message = format!(
            "{}\n\nChange-Capsule: {}",
            integration.commit_message, capsule.id
        );
        let index = self.store.temporary_index(&capsule.id)?;
        let commit = self.git.commit_patch(&CommitPatch {
            worktree: &target.worktree,
            base: &capsule.base_commit,
            patch,
            index: index.path(),
            message: &message,
            name: &integration.author_name,
            email: &integration.author_email,
        })?;
        let parents = self.git.parents(&target.worktree, &commit)?;
        if parents != [capsule.base_commit.clone()] {
            return Err(Error::UnsafeState(format!(
                "prepared integration commit {commit} does not have exactly the pinned base as parent"
            )));
        }
        let prepared = self
            .git
            .commit_snapshot(&target.worktree, &capsule.base_commit, &commit)?;
        if prepared.patch != patch || prepared.changed_paths != result.changed_paths {
            return Err(Error::UnsafeState(
                "prepared integration commit does not reproduce the sealed result".to_owned(),
            ));
        }
        Ok(commit)
    }

    fn ensure_sealed(&self, capsule: &Capsule) -> Result<()> {
        capsule
            .result
            .as_ref()
            .ok_or_else(|| invalid_state(capsule, "a sealed result"))?;
        self.validate_owned_worktree(capsule)?;
        let snapshot = self.snapshot(capsule)?;
        let head = self.git.head(&capsule.workspace_path)?;
        if !self.seal_matches(capsule, &snapshot, &head)? {
            return Err(Error::ResultDrift(capsule.id.clone()));
        }
        Ok(())
    }

    fn seal_matches(
        &self,
        capsule: &Capsule,
        snapshot: &crate::git::Snapshot,
        head: &str,
    ) -> Result<bool> {
        let (artifacts_match, result, stored_patch) = match self.sealed_artifacts(capsule) {
            Ok(artifacts) => artifacts,
            Err(Error::ResultDrift(_)) => return Ok(false),
            Err(error) => return Err(error),
        };
        // The ignored-content inventory sealed at close is provenance, not a gate:
        // ignored files are exactly the content the repository declared irrelevant,
        // so their later churn must not invalidate an otherwise intact result.
        Ok(artifacts_match
            && result.head_commit == head
            && result.patch_sha256 == sha256_hex(&snapshot.patch)
            && result.patch_bytes == snapshot.patch.len() as u64
            && result.changed_paths == snapshot.changed_paths
            && stored_patch == snapshot.patch)
    }

    fn artifact_snapshot(&self, id: &str) -> Result<(ArtifactBundle, Vec<u8>, Vec<u8>)> {
        let capsule = self.show(id)?;
        if capsule.result.is_none() {
            return Err(invalid_state(&capsule, "a sealed result"));
        }
        let (matches, _, result_bytes, patch) = self.sealed_artifact_snapshot(&capsule)?;
        if !matches {
            return Err(Error::ResultDrift(capsule.id));
        }
        let result_digest = sha256_hex(&result_bytes);
        let patch_digest = sha256_hex(&patch);
        let bundle = ArtifactBundle {
            schema_version: BUNDLE_SCHEMA_VERSION,
            capsule_id: id.to_owned(),
            artifacts: vec![
                artifact_descriptor(
                    ArtifactKind::ResultManifest,
                    "result.json",
                    "application/json",
                    &self.store.capsule_dir(id)?.join("result.json"),
                    &result_digest,
                    result_bytes.len() as u64,
                )?,
                artifact_descriptor(
                    ArtifactKind::ResultPatch,
                    "result.patch",
                    "application/vnd.git.patch",
                    &self.store.capsule_dir(id)?.join("result.patch"),
                    &patch_digest,
                    patch.len() as u64,
                )?,
            ],
        };
        Ok((bundle, result_bytes, patch))
    }

    fn sealed_artifacts(&self, capsule: &Capsule) -> Result<(bool, CapsuleResult, Vec<u8>)> {
        let (matches, result, _, patch) = self.sealed_artifact_snapshot(capsule)?;
        Ok((matches, result, patch))
    }

    fn sealed_artifact_snapshot(
        &self,
        capsule: &Capsule,
    ) -> Result<(bool, CapsuleResult, Vec<u8>, Vec<u8>)> {
        let Some(reference) = capsule.result.as_ref() else {
            return Err(invalid_state(capsule, "a sealed result"));
        };
        let (result, result_bytes) = self
            .store
            .read_result_artifact(&capsule.id)
            .map_err(|error| artifact_error(&capsule.id, error))?;
        let stored_patch = self
            .store
            .read_patch(&capsule.id)
            .map_err(|error| artifact_error(&capsule.id, error))?;
        let stored_digest = sha256_hex(&stored_patch);
        let matches = reference.kind == result.kind
            && reference.head_commit == result.head_commit
            && reference.patch_sha256 == stored_digest
            && reference.patch_sha256 == result.patch_sha256
            && reference.result_sha256 == result_sha256(&result)?
            && reference.patch_bytes == stored_patch.len() as u64
            && reference.patch_bytes == result.patch_bytes
            && reference.changed_paths == result.changed_paths.len()
            && reference.sealed_at_unix == result.sealed_at_unix
            && result.schema_version == SCHEMA_VERSION
            && result.capsule_id == capsule.id
            && result.label == capsule.label
            && result.links == capsule.links
            && result.base_commit == capsule.base_commit
            && result.checkpoints == capsule.checkpoints
            && result.evidence == capsule.evidence
            && result.created_at_unix == capsule.created_at_unix;
        Ok((matches, result, result_bytes, stored_patch))
    }

    fn snapshot(&self, capsule: &Capsule) -> Result<crate::git::Snapshot> {
        self.snapshot_against(capsule, &capsule.base_commit)
    }

    fn snapshot_against(&self, capsule: &Capsule, base: &str) -> Result<crate::git::Snapshot> {
        if self.git.sparse_checkout(&capsule.workspace_path)?
            || self.git.hidden_index_entries(&capsule.workspace_path)?
        {
            return Err(Error::InvalidInput(
                "sparse-checkout, skip-worktree, or assume-unchanged index entries cannot produce a complete capsule snapshot; restore a full checkout first"
                    .to_owned(),
            ));
        }
        if self.git.dirty_submodules(&capsule.workspace_path)? {
            return Err(Error::InvalidInput(
                "dirty submodule worktrees cannot be represented by a top-level capsule patch; commit or clean them first"
                    .to_owned(),
            ));
        }
        let index = self.store.temporary_index(&capsule.id)?;
        self.git
            .snapshot(&capsule.workspace_path, base, index.path())
    }

    fn validate_owned_worktree(&self, capsule: &Capsule) -> Result<()> {
        let repository = self
            .git
            .repository(&capsule.workspace_path)
            .map_err(|_| Error::ForeignWorktree(capsule.workspace_path.clone()))?;
        if repository.common_dir != capsule.repository_common_dir
            || capsule.workspace_git_dir.as_ref() != Some(&repository.git_dir)
            || repository.worktree != canonical_existing(&capsule.workspace_path)?
            || self.git.branch(&capsule.workspace_path)? != capsule.branch
        {
            return Err(Error::ForeignWorktree(capsule.workspace_path.clone()));
        }
        let record = self
            .registered_record(capsule)?
            .ok_or_else(|| Error::ForeignWorktree(capsule.workspace_path.clone()))?;
        let head = self.git.head(&capsule.workspace_path)?;
        Self::validate_registered_record(capsule, &record, Some(&head))?;
        Ok(())
    }

    fn registered_record(&self, capsule: &Capsule) -> Result<Option<crate::git::WorktreeRecord>> {
        let execution_root = self.execution_root(capsule)?;
        let records = self.git.registered_worktrees(&execution_root)?;
        Ok(records
            .into_iter()
            .find(|record| same_path_existing_or_clean(&record.path, &capsule.workspace_path)))
    }

    fn validate_registered_record(
        capsule: &Capsule,
        record: &crate::git::WorktreeRecord,
        expected_head: Option<&str>,
    ) -> Result<()> {
        if record.branch.as_deref() != Some(capsule.branch.as_str())
            || record.bare
            || record.head.as_deref() != expected_head
        {
            return Err(Error::ForeignWorktree(capsule.workspace_path.clone()));
        }
        Ok(())
    }

    fn finish_cleanup(&self, capsule: &mut Capsule) -> Result<String> {
        let cleanup = capsule.cleanup.clone().ok_or_else(|| {
            Error::UnsafeState("dropping capsule has no cleanup journal".to_owned())
        })?;
        let execution_root = self.execution_root(capsule)?;
        let expected_head = cleanup.branch_head.as_deref();

        if capsule.workspace_path.exists() {
            self.validate_owned_worktree(capsule)?;
            let workspace_head = self.git.head(&capsule.workspace_path)?;
            if expected_head != Some(workspace_head.as_str()) {
                return Err(Error::ForeignWorktree(capsule.workspace_path.clone()));
            }
            if cleanup.require_sealed {
                self.ensure_sealed(capsule)?;
            }
            self.git
                .remove_worktree(&execution_root, &capsule.workspace_path, true)?;
        } else if let Some(record) = self.registered_record(capsule)? {
            Self::validate_registered_record(capsule, &record, expected_head)?;
            self.git.prune(&execution_root)?;
            if self.registered_record(capsule)?.is_some() {
                return Err(Error::ForeignWorktree(capsule.workspace_path.clone()));
            }
        }

        match expected_head {
            Some(head) => {
                self.git
                    .delete_branch_if_matches(&execution_root, &capsule.branch, head)?;
            }
            None => {
                if self
                    .git
                    .branch_head(&execution_root, &capsule.branch)?
                    .is_some()
                {
                    return Err(Error::UnsafeState(format!(
                        "refusing to delete branch {} created after cleanup began",
                        capsule.branch
                    )));
                }
            }
        }
        self.git.prune(&execution_root)?;
        for pending_ref in [checkpoint_ref(capsule), integration_ref(capsule)] {
            if let Some(commit) = self.git.ref_head(&execution_root, &pending_ref)? {
                self.git
                    .delete_ref_if_matches(&execution_root, &pending_ref, &commit)?;
            }
        }
        let dropped_at = now()?;
        capsule.state = CapsuleState::Dropped;
        capsule.checkpoint = None;
        capsule.cleanup = None;
        capsule.dropped_at_unix = Some(dropped_at);
        Ok("completed journaled worktree and branch cleanup".to_owned())
    }

    fn execution_root(&self, capsule: &Capsule) -> Result<PathBuf> {
        for path in [&capsule.source_worktree, &capsule.workspace_path] {
            if path.exists()
                && self
                    .git
                    .repository(path)
                    .is_ok_and(|repository| repository.common_dir == capsule.repository_common_dir)
            {
                return Ok(path.clone());
            }
        }
        if capsule.repository_common_dir.exists()
            && canonical_existing(&capsule.repository_common_dir)? == capsule.repository_common_dir
        {
            return Ok(capsule.repository_common_dir.clone());
        }
        Err(Error::ForeignWorktree(capsule.workspace_path.clone()))
    }

    fn recover_creating(&self, capsule: &mut Capsule) -> Result<String> {
        if capsule.workspace_path.exists() {
            if capsule.workspace_git_dir.is_none() {
                capsule.workspace_git_dir = self
                    .git
                    .repository(&capsule.workspace_path)
                    .ok()
                    .map(|repository| repository.git_dir);
            }
            if self.validate_owned_worktree(capsule).is_ok() {
                self.git
                    .reset_hard(&capsule.workspace_path, &capsule.base_commit)?;
                capsule.state = CapsuleState::Active;
                return Ok("completed an interrupted workspace creation".to_owned());
            }
        }
        capsule.state = CapsuleState::Orphaned;
        Ok(
            "marked an incomplete creation orphaned for explicit inspection or forced cleanup"
                .to_owned(),
        )
    }

    fn recover_checkpointing(&self, capsule: &mut Capsule) -> Result<Option<String>> {
        Ok(self
            .finish_checkpoint(capsule)?
            .map(|checkpoint| format!("completed interrupted checkpoint {}", checkpoint.commit)))
    }

    fn finish_checkpoint(&self, capsule: &mut Capsule) -> Result<Option<Checkpoint>> {
        let journal = capsule.checkpoint.clone().ok_or_else(|| {
            Error::UnsafeState("checkpointing capsule has no checkpoint journal".to_owned())
        })?;
        self.validate_owned_worktree(capsule)?;
        let parents = self
            .git
            .parents(&capsule.workspace_path, &journal.head_after)?;
        let committed = self.git.commit_snapshot(
            &capsule.workspace_path,
            &journal.head_before,
            &journal.head_after,
        )?;
        if parents != [journal.head_before.clone()]
            || sha256_hex(&committed.patch) != journal.patch_sha256
        {
            return Err(Error::UnsafeState(
                "checkpoint journal does not match its prepared commit".to_owned(),
            ));
        }

        let head = self.git.head(&capsule.workspace_path)?;
        let pending_ref = checkpoint_ref(capsule);
        let pending_head = self.git.ref_head(&capsule.workspace_path, &pending_ref)?;
        if head == journal.head_before {
            match pending_head.as_deref() {
                Some(head) if head == journal.head_after => {}
                None => self.git.create_ref(
                    &capsule.workspace_path,
                    &pending_ref,
                    &journal.head_after,
                )?,
                Some(_) => {
                    return Err(Error::UnsafeState(
                        "checkpoint pending ref points to an unexpected commit".to_owned(),
                    ));
                }
            }
            self.git.advance_branch(
                &capsule.workspace_path,
                &capsule.branch,
                &journal.head_after,
                &journal.head_before,
            )?;
        } else if head == journal.head_after {
            if pending_head.as_deref().is_some_and(|value| value != head) {
                return Err(Error::UnsafeState(
                    "checkpoint pending ref points to an unexpected commit".to_owned(),
                ));
            }
            self.git
                .reset_index(&capsule.workspace_path, &journal.head_after)?;
        } else {
            return Ok(None);
        }
        if pending_head.is_some() {
            self.git.delete_ref_if_matches(
                &capsule.workspace_path,
                &pending_ref,
                &journal.head_after,
            )?;
        }

        if capsule
            .checkpoints
            .iter()
            .any(|checkpoint| checkpoint.commit == journal.head_after)
        {
            return Err(Error::UnsafeState(
                "checkpoint journal duplicates an existing checkpoint".to_owned(),
            ));
        }
        let checkpoint = Checkpoint {
            commit: journal.head_after,
            message: journal.message,
            author_name: journal.author_name,
            author_email: journal.author_email,
            created_at_unix: journal.started_at_unix,
        };
        capsule.checkpoints.push(checkpoint.clone());
        capsule.checkpoint = None;
        capsule.state = CapsuleState::Active;
        Ok(Some(checkpoint))
    }

    fn recover_active(&self, capsule: &mut Capsule) -> Result<Option<String>> {
        if capsule.workspace_path.exists() && self.validate_owned_worktree(capsule).is_ok() {
            let pending_ref = checkpoint_ref(capsule);
            if let Some(commit) = self.git.ref_head(&capsule.workspace_path, &pending_ref)? {
                self.git
                    .delete_ref_if_matches(&capsule.workspace_path, &pending_ref, &commit)?;
                return Ok(Some(
                    "removed a prepared checkpoint ref left before its journal was written"
                        .to_owned(),
                ));
            }
            return Ok(None);
        }
        capsule.state = CapsuleState::Orphaned;
        Ok(Some(
            "marked an active capsule orphaned because its owned worktree is missing or foreign"
                .to_owned(),
        ))
    }

    fn integration_matches_result(
        &self,
        target: &Repository,
        integration: &Integration,
        result: &CapsuleResult,
        stored_patch: &[u8],
        head: &str,
    ) -> Result<bool> {
        if head == integration.target_head_before {
            return Ok(result.kind == ResultKind::NoChange
                && result.patch_bytes == 0
                && result.changed_paths.is_empty()
                && stored_patch.is_empty());
        }
        let parents = self.git.parents(&target.worktree, head)?;
        let snapshot =
            self.git
                .commit_snapshot(&target.worktree, &integration.target_head_before, head)?;
        Ok(parents == [integration.target_head_before.clone()]
            && snapshot.patch == stored_patch
            && snapshot.changed_paths == result.changed_paths)
    }

    fn recovery_integration_target(
        &self,
        capsule: &Capsule,
        integration: &Integration,
    ) -> Result<Option<Repository>> {
        if !integration.target_worktree.exists() {
            return Ok(None);
        }
        let Ok(target) = self.git.repository(&integration.target_worktree) else {
            return Ok(None);
        };
        if target.common_dir != capsule.repository_common_dir
            || target.git_dir != integration.target_git_dir
            || self.git.head_ref(&target.worktree)? != integration.target_head_ref
            || self.git.sparse_checkout(&target.worktree)?
            || self.git.hidden_index_entries(&target.worktree)?
            || !self.git.clean(&target.worktree)?
        {
            return Ok(None);
        }
        Ok(Some(target))
    }

    fn recover_integrating(&self, capsule: &mut Capsule) -> Result<Option<String>> {
        let Some(integration) = capsule.integration.clone() else {
            capsule.state = CapsuleState::Orphaned;
            return Ok(Some(
                "marked an integration orphaned because its journal record is missing".to_owned(),
            ));
        };
        let Some(target) = self.recovery_integration_target(capsule, &integration)? else {
            return Ok(None);
        };
        let head = self.git.head(&target.worktree)?;
        let pending_ref = integration_ref(capsule);
        let pending_ref_head = self.git.ref_head(&target.worktree, &pending_ref)?;
        if integration.target_head_after.is_none() {
            if head != integration.target_head_before {
                return Ok(None);
            }
            if let Some(prepared) = pending_ref_head {
                self.git
                    .delete_ref_if_matches(&target.worktree, &pending_ref, &prepared)?;
            }
            capsule.state = CapsuleState::Closed;
            capsule.integration = None;
            return Ok(Some(
                "removed a prepared integration ref left before its journal update".to_owned(),
            ));
        }
        let (artifacts_match, result, stored_patch) = self.sealed_artifacts(capsule)?;
        if !artifacts_match {
            return Ok(None);
        }
        let pending = integration
            .target_head_after
            .as_deref()
            .filter(|head| *head != integration.target_head_before);
        if let Some(head) = pending {
            if self
                .git
                .ref_head(&target.worktree, &pending_ref)?
                .is_some_and(|value| value != head)
            {
                return Err(Error::UnsafeState(
                    "integration pending ref points to an unexpected commit".to_owned(),
                ));
            }
        }
        if integration.target_head_after.as_deref() == Some(head.as_str()) {
            if !self.integration_matches_result(
                &target,
                &integration,
                &result,
                &stored_patch,
                &head,
            )? {
                return Ok(None);
            }
            let completed_at = now()?;
            if let Some(record) = capsule.integration.as_mut() {
                record.integrated_at_unix = Some(completed_at);
            }
            capsule.state = CapsuleState::Integrated;
            if let Some(pending) = pending {
                self.git
                    .delete_ref_if_matches(&target.worktree, &pending_ref, pending)?;
            }
            return Ok(Some(
                "finalized an integration whose exact Git commit completed before the journal update"
                    .to_owned(),
            ));
        }
        if head == integration.target_head_before {
            if let Some(pending) = pending {
                if self
                    .git
                    .ref_head(&target.worktree, &pending_ref)?
                    .as_deref()
                    != Some(pending)
                {
                    return Ok(None);
                }
            }
            capsule.state = CapsuleState::Closed;
            capsule.integration = None;
            if let Some(pending) = pending {
                self.git
                    .delete_ref_if_matches(&target.worktree, &pending_ref, pending)?;
            }
            return Ok(Some(
                "restored a pre-side-effect interrupted integration to closed".to_owned(),
            ));
        }
        Ok(None)
    }
}

fn artifact_descriptor(
    kind: ArtifactKind,
    name: &str,
    media_type: &str,
    path: &Path,
    digest: &str,
    bytes: u64,
) -> Result<ArtifactDescriptor> {
    Ok(ArtifactDescriptor {
        kind,
        name: name.to_owned(),
        media_type: media_type.to_owned(),
        uri: file_uri(path)?,
        content_address: format!("sha256:{digest}"),
        sha256: digest.to_owned(),
        bytes,
    })
}

fn file_uri(path: &Path) -> Result<String> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|error| io(".", error))?
            .join(path)
    };
    let text = absolute
        .to_str()
        .ok_or_else(|| Error::NonUtf8Path(absolute.clone()))?;
    #[cfg(windows)]
    let (prefix, normalized) = {
        let normalized = text.replace('\\', "/");
        if normalized.starts_with("//") {
            ("file:", normalized)
        } else {
            ("file:///", normalized)
        }
    };
    #[cfg(not(windows))]
    let (prefix, normalized) = ("file://", text.to_owned());
    let mut encoded = String::with_capacity(normalized.len() + prefix.len());
    encoded.push_str(prefix);
    for byte in normalized.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b':' | b'-' | b'.' | b'_' | b'~') {
            encoded.push(char::from(byte));
        } else {
            use std::fmt::Write as _;
            write!(encoded, "%{byte:02X}")
                .map_err(|_| Error::UnsafeState("failed to encode artifact URI".to_owned()))?;
        }
    }
    Ok(encoded)
}

fn bounded_error(error: &Error) -> String {
    error
        .to_string()
        .chars()
        .take(512)
        .map(|character| {
            if character.is_control() {
                ' '
            } else {
                character
            }
        })
        .collect()
}

fn append_event(
    capsule: &mut Capsule,
    kind: AuditEventKind,
    previous_state: Option<CapsuleState>,
    state: CapsuleState,
    attributes: BTreeMap<String, String>,
) -> Result<()> {
    let occurred_at_unix = now()?.max(
        capsule
            .audit_events
            .last()
            .map_or(capsule.created_at_unix, |event| event.occurred_at_unix),
    );
    if capsule.audit_events.len() >= AUDIT_EVENT_CAP {
        capsule.audit_events.remove(0);
        capsule.audit_events_dropped = capsule.audit_events_dropped.saturating_add(1);
    }
    capsule.audit_events.push(AuditEvent {
        schema_version: AUDIT_SCHEMA_VERSION,
        event_id: format!("evt-{}", Ulid::new().to_string().to_ascii_lowercase()),
        occurred_at_unix,
        kind,
        capsule_id: Some(capsule.id.clone()),
        project_key: Some(capsule.project_key.clone()),
        previous_state,
        state: Some(state),
        attributes,
    });
    Ok(())
}

fn state_name(state: CapsuleState) -> &'static str {
    match state {
        CapsuleState::Creating => "creating",
        CapsuleState::Checkpointing => "checkpointing",
        CapsuleState::Active => "active",
        CapsuleState::Closed => "closed",
        CapsuleState::Integrating => "integrating",
        CapsuleState::Integrated => "integrated",
        CapsuleState::Dropping => "dropping",
        CapsuleState::Orphaned => "orphaned",
        CapsuleState::Dropped => "dropped",
    }
}

fn repository_allowed(policy: &Policy, repository: &Path) -> bool {
    policy.allowed_repository_roots.is_empty()
        || policy
            .allowed_repository_roots
            .iter()
            .any(|root| repository.starts_with(root))
}

fn enforce_limit(name: &str, observed: u64, limit: Option<u64>) -> Result<()> {
    if let Some(limit) = limit {
        if observed > limit {
            return Err(Error::PolicyViolation(format!(
                "{name} {observed} exceeds limit {limit}"
            )));
        }
    }
    Ok(())
}

fn enforce_next_limit(name: &str, observed: u64, limit: Option<u64>) -> Result<()> {
    if let Some(limit) = limit {
        let next = observed.saturating_add(1);
        if next > limit {
            return Err(Error::PolicyViolation(format!(
                "creating a capsule would make {name} {next}, exceeding limit {limit}"
            )));
        }
    }
    Ok(())
}

fn check_limit(violations: &mut Vec<String>, name: &str, observed: u64, limit: Option<u64>) {
    if let Some(limit) = limit {
        if observed > limit {
            violations.push(format!("{name} {observed} exceeds limit {limit}"));
        }
    }
}

fn check_capsule_limit(
    violations: &mut Vec<String>,
    id: &str,
    name: &str,
    observed: u64,
    limit: Option<u64>,
) {
    if let Some(limit) = limit {
        if observed > limit {
            violations.push(format!(
                "capsule {id} {name} {observed} exceeds limit {limit}"
            ));
        }
    }
}

fn safe_ignored_relative(ignored: &str) -> Result<&Path> {
    let relative = Path::new(ignored.trim_end_matches('/'));
    if relative.components().any(|component| {
        matches!(
            component,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    }) {
        return Err(Error::UnsafeState(format!(
            "Git returned an unsafe ignored path: {ignored:?}"
        )));
    }
    Ok(relative)
}

fn ignored_content_inventory(workspace: &Path, ignored_paths: &[String]) -> Result<(u64, String)> {
    let mut digest = Sha256::new();
    let mut total = 0_u64;
    let mut seen = BTreeSet::new();
    for ignored in ignored_paths {
        let relative = safe_ignored_relative(ignored)?;
        inventory_path(workspace, relative, &mut seen, &mut total, &mut digest)?;
    }
    Ok((total, hex::encode(digest.finalize())))
}

fn ignored_usage(workspace: &Path, ignored_paths: &[String]) -> Result<u64> {
    let mut total = 0_u64;
    let mut seen = BTreeSet::new();
    for ignored in ignored_paths {
        let relative = safe_ignored_relative(ignored)?;
        usage_path(workspace, relative, &mut seen, &mut total)?;
    }
    Ok(total)
}

fn usage_path(
    workspace: &Path,
    relative: &Path,
    seen: &mut BTreeSet<PathBuf>,
    total: &mut u64,
) -> Result<()> {
    if !seen.insert(relative.to_path_buf()) {
        return Ok(());
    }
    let path = workspace.join(relative);
    let metadata = fs::symlink_metadata(&path).map_err(|error| io(&path, error))?;
    if metadata.is_dir() && !metadata.file_type().is_symlink() {
        let mut entries = fs::read_dir(&path)
            .map_err(|error| io(&path, error))?
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|error| io(&path, error))?;
        entries.sort_by_key(std::fs::DirEntry::file_name);
        for entry in entries {
            usage_path(workspace, &relative.join(entry.file_name()), seen, total)?;
        }
        return Ok(());
    }
    *total = total
        .checked_add(metadata.len())
        .ok_or_else(|| Error::UnsafeState("ignored byte count overflowed".to_owned()))?;
    Ok(())
}

fn inventory_path(
    workspace: &Path,
    relative: &Path,
    seen: &mut BTreeSet<PathBuf>,
    total: &mut u64,
    digest: &mut Sha256,
) -> Result<()> {
    if !seen.insert(relative.to_path_buf()) {
        return Ok(());
    }
    let path = workspace.join(relative);
    let metadata = fs::symlink_metadata(&path).map_err(|error| io(&path, error))?;
    let relative_bytes = relative
        .to_str()
        .ok_or_else(|| Error::NonUtf8Path(relative.to_path_buf()))?
        .as_bytes();
    digest.update((relative_bytes.len() as u64).to_be_bytes());
    digest.update(relative_bytes);
    if metadata.file_type().is_symlink() {
        digest.update(b"link");
        let target = fs::read_link(&path).map_err(|error| io(&path, error))?;
        let target = target
            .to_str()
            .ok_or_else(|| Error::NonUtf8Path(target.clone()))?
            .as_bytes();
        digest.update((target.len() as u64).to_be_bytes());
        digest.update(target);
        *total = total
            .checked_add(metadata.len())
            .ok_or_else(|| Error::UnsafeState("ignored byte count overflowed".to_owned()))?;
        return Ok(());
    }
    if metadata.is_file() {
        let mut file = File::open(&path).map_err(|error| io(&path, error))?;
        let opened = file.metadata().map_err(|error| io(&path, error))?;
        if !opened.is_file() || opened.len() != metadata.len() {
            return Err(Error::UnsafeState(format!(
                "ignored file changed while it was inspected: {}",
                path.display()
            )));
        }
        let expected = opened.len();
        digest.update(b"file");
        digest.update(expected.to_be_bytes());
        let mut observed = 0_u64;
        let mut buffer = vec![0_u8; 64 * 1024];
        loop {
            let read = file.read(&mut buffer).map_err(|error| io(&path, error))?;
            if read == 0 {
                break;
            }
            observed = observed
                .checked_add(read as u64)
                .ok_or_else(|| Error::UnsafeState("ignored byte count overflowed".to_owned()))?;
            if observed > expected {
                return Err(Error::UnsafeState(format!(
                    "ignored file changed while it was inspected: {}",
                    path.display()
                )));
            }
            digest.update(&buffer[..read]);
        }
        if observed != expected
            || file.metadata().map_err(|error| io(&path, error))?.len() != expected
        {
            return Err(Error::UnsafeState(format!(
                "ignored file changed while it was inspected: {}",
                path.display()
            )));
        }
        *total = total
            .checked_add(observed)
            .ok_or_else(|| Error::UnsafeState("ignored byte count overflowed".to_owned()))?;
        return Ok(());
    }
    if metadata.is_dir() {
        digest.update(b"dir");
        let mut entries = fs::read_dir(&path)
            .map_err(|error| io(&path, error))?
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|error| io(&path, error))?;
        entries.sort_by_key(std::fs::DirEntry::file_name);
        for entry in entries {
            inventory_path(
                workspace,
                &relative.join(entry.file_name()),
                seen,
                total,
                digest,
            )?;
        }
    }
    Ok(())
}

fn artifact_error(id: &str, error: Error) -> Error {
    match error {
        Error::Io { ref source, .. } if source.kind() == std::io::ErrorKind::NotFound => {
            Error::ResultDrift(id.to_owned())
        }
        Error::Json { .. } | Error::UnsafeState(_) | Error::SchemaVersion { .. } => {
            Error::ResultDrift(id.to_owned())
        }
        other => other,
    }
}

fn recorded_capsule_head(capsule: &Capsule, head: &str) -> bool {
    head == capsule.base_commit
        || capsule
            .checkpoints
            .iter()
            .any(|checkpoint| checkpoint.commit == head)
        || capsule
            .result
            .as_ref()
            .is_some_and(|result| result.head_commit == head)
        || capsule.checkpoint.as_ref().is_some_and(|checkpoint| {
            checkpoint.head_before == head || checkpoint.head_after == head
        })
}

fn checkpoint_ref(capsule: &Capsule) -> String {
    format!("refs/change-capsule/{}/checkpoint", capsule.id)
}

fn integration_ref(capsule: &Capsule) -> String {
    format!("refs/change-capsule/{}/integration", capsule.id)
}

fn validate_create_options(options: &CreateOptions) -> Result<()> {
    if let Some(label) = &options.label {
        validate_bounded_text(label, LABEL_CAP, "label", false)?;
    }
    if options.links.len() > 32 {
        return Err(Error::InvalidInput(
            "at most 32 links are allowed".to_owned(),
        ));
    }
    for (key, value) in &options.links {
        let valid_key = !key.is_empty()
            && key.len() <= LINK_KEY_CAP
            && key
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));
        if !valid_key {
            return Err(Error::InvalidInput(format!("invalid link key: {key:?}")));
        }
        validate_bounded_text(value, LINK_VALUE_CAP, "link value", false)?;
    }
    Ok(())
}

fn validate_author(author: &Author) -> Result<()> {
    validate_bounded_text(&author.name, 256, "author name", false)?;
    validate_bounded_text(&author.email, 512, "author email", false)?;
    if !author.email.contains('@') {
        return Err(Error::InvalidInput(
            "author email must contain '@'".to_owned(),
        ));
    }
    Ok(())
}

fn validate_message(message: &str, label: &str) -> Result<()> {
    validate_bounded_text(message, MESSAGE_CAP, label, true)
}

fn validate_bounded_text(value: &str, cap: usize, label: &str, multiline: bool) -> Result<()> {
    if value.trim().is_empty() || value.len() > cap || value.contains('\0') {
        return Err(Error::InvalidInput(format!(
            "{label} must contain 1-{cap} bytes without NUL"
        )));
    }
    if value
        .chars()
        .any(|character| character.is_control() && !(multiline && matches!(character, '\n' | '\t')))
    {
        return Err(Error::InvalidInput(format!(
            "{label} contains unsupported control characters"
        )));
    }
    Ok(())
}

fn require_state(capsule: &Capsule, expected: CapsuleState, label: &str) -> Result<()> {
    if capsule.state == expected {
        Ok(())
    } else {
        Err(invalid_state(capsule, label))
    }
}

fn invalid_state(capsule: &Capsule, expected: &str) -> Error {
    Error::InvalidState {
        id: capsule.id.clone(),
        state: format!("{:?}", capsule.state).to_ascii_lowercase(),
        expected: expected.to_owned(),
    }
}

fn not_found(id: &str, error: Error) -> Error {
    match error {
        Error::Io { ref source, .. } if source.kind() == std::io::ErrorKind::NotFound => {
            Error::NotFound(id.to_owned())
        }
        other => other,
    }
}

fn now() -> Result<u64> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .map_err(|_| Error::InvalidInput("system clock is before the Unix epoch".to_owned()))
}

fn project_key(common_dir: &Path) -> Result<String> {
    let path = common_dir
        .to_str()
        .ok_or_else(|| Error::NonUtf8Path(common_dir.to_path_buf()))?;
    let digest = Sha256::digest(path.as_bytes());
    Ok(hex::encode(&digest[..12]))
}

fn result_sha256(result: &CapsuleResult) -> Result<String> {
    let bytes = serde_json::to_vec(result).map_err(|source| Error::Json {
        path: PathBuf::from("result digest"),
        source,
    })?;
    Ok(sha256_hex(&bytes))
}

fn sha256_hex(bytes: &[u8]) -> String {
    hex::encode(Sha256::digest(bytes))
}

fn canonical_existing(path: &Path) -> Result<PathBuf> {
    crate::path::canonicalize(path).map_err(|error| io(path, error))
}

fn same_path_existing_or_clean(left: &Path, right: &Path) -> bool {
    match (
        crate::path::canonicalize(left),
        crate::path::canonicalize(right),
    ) {
        (Ok(left), Ok(right)) => left == right,
        _ => clean_absolute(left) == clean_absolute(right),
    }
}

fn clean_absolute(path: &Path) -> Option<PathBuf> {
    if path.is_absolute() {
        Some(path.to_path_buf())
    } else {
        std::env::current_dir().ok().map(|cwd| cwd.join(path))
    }
}