File size: 60,816 Bytes
aec61e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SQLite persistence layer for the Change.org offline clone (R3 backend).

Shared Phase-4 contract:

* Database lives under ``CLAWBENCH_DATA_DIR`` (default: the site-local
  ``data/`` directory, i.e. ``materials/change/data`` — always OUTSIDE
  the ``clone/`` candidate root so uvicorn --reload never loops).
* WAL journal mode; ordered migrations recorded in ``schema_migrations``
  (version, name, applied_at): ``0001`` initial schema -> ``0002``
  additive comments table + optimistic petition row version -> ``0003``
  topic-partitioned publish commands and versioned/idempotent updates.
* Deterministic seed: captured petitions (real titles / decision-maker
  targets / signature baselines from the 2026-07-25 capture) stored as
  ORDINARY rows — including one victory and one closed petition so the
  status rejection paths run against real data.  No petition-ID
  branching exists anywhere in this module.
* Sessions are persisted server-side (sessions table) so login state
  survives a process restart.
* Signature counts are server-derived: captured baseline + COUNT of
  real signature rows; the next-goal milestone comes from the generic
  Change.org goal ladder (…7,500 -> 10,000 -> 15,000…).

Comment policy (documented decision): the 2026-07-25 captured evidence
(browser text + network captures under source-current/) contains no
petition-detail comment surface, so it neither proves nor disproves a
sign-before-comment rule.  We mirror the generic Change.org product
behavior — comments are "reasons for signing" authored by supporters —
so commenting requires the account to have signed the petition first.

Everything here is a deterministic local fixture pinned to the frozen
clock 2026-07-25T12:00:00-04:00; nothing touches production Change.org.
"""

from __future__ import annotations

import hashlib
import os
import secrets
import sqlite3
from contextlib import closing
from pathlib import Path
from typing import Any

DB_FILENAME = "websitebench-change.sqlite3"
LEGACY_DB_FILENAME = "change.sqlite3"
FROZEN_CLOCK = "2026-07-25T12:00:00-04:00"

# The site directory is two levels above clone/backend/.
_SITE_DIR = Path(__file__).resolve().parents[2]
DEFAULT_DATA_DIR = _SITE_DIR / "data"

# Generic Change.org signature goal ladder (site-wide product rule; the
# next milestone is derived from the current count, never stored).
GOAL_LADDER: tuple[int, ...] = (
    5, 10, 25, 50, 100, 200, 500, 1_000, 1_500, 2_500, 5_000, 7_500,
    10_000, 15_000,
    25_000, 35_000, 50_000, 75_000, 100_000, 150_000, 200_000, 300_000,
    500_000, 1_000_000,
)

PETITION_STATUSES = ("open", "victory", "closed")


def next_goal(count: int) -> int:
    """Smallest ladder milestone strictly above ``count`` (generic rule)."""
    for goal in GOAL_LADDER:
        if count < goal:
            return goal
    # Beyond the fixed ladder Change.org steps in 500k increments.
    return ((count // 500_000) + 1) * 500_000


def data_dir() -> Path:
    """Resolve the site-isolated data directory from the environment."""
    override = os.environ.get("WEBSITEBENCH_DATA_DIR")
    if override:
        return Path(override)
    return DEFAULT_DATA_DIR


def db_path() -> Path:
    return data_dir() / DB_FILENAME


def legacy_db_path() -> Path:
    return data_dir() / LEGACY_DB_FILENAME


# ---------------------------------------------------------------------------
# Migrations: ordered 0001 (initial schema) -> 0002 (additive change)
# ---------------------------------------------------------------------------

MIGRATION_0001_NAME = "initial-schema"
MIGRATION_0001 = """
CREATE TABLE accounts (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TEXT NOT NULL
);
CREATE TABLE sessions (
    token TEXT PRIMARY KEY,
    account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    created_at TEXT NOT NULL
);
CREATE TABLE petitions (
    slug TEXT PRIMARY KEY,
    title TEXT NOT NULL,
    target TEXT NOT NULL,
    body TEXT NOT NULL,
    owner_id TEXT NOT NULL REFERENCES accounts(id),
    status TEXT NOT NULL DEFAULT 'open'
        CHECK (status IN ('open', 'victory', 'closed')),
    baseline_signatures INTEGER NOT NULL DEFAULT 0,
    path TEXT NOT NULL DEFAULT 'scratch',
    created_seq INTEGER NOT NULL,
    created_at TEXT NOT NULL
);
CREATE TABLE signatures (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    petition_slug TEXT NOT NULL REFERENCES petitions(slug)
        ON DELETE CASCADE,
    account_id TEXT NOT NULL REFERENCES accounts(id),
    display_name TEXT NOT NULL,
    display_publicly INTEGER NOT NULL DEFAULT 0,
    reason TEXT NOT NULL DEFAULT '',
    signed_at TEXT NOT NULL,
    UNIQUE (petition_slug, account_id)
);
CREATE TABLE supporter_updates (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    petition_slug TEXT NOT NULL REFERENCES petitions(slug)
        ON DELETE CASCADE,
    body TEXT NOT NULL,
    author_id TEXT NOT NULL REFERENCES accounts(id),
    posted_at TEXT NOT NULL
);
"""

MIGRATION_0002_NAME = "comments-and-petition-row-version"
MIGRATION_0002 = """
CREATE TABLE comments (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    petition_slug TEXT NOT NULL REFERENCES petitions(slug)
        ON DELETE CASCADE,
    author_id TEXT NOT NULL REFERENCES accounts(id),
    body TEXT NOT NULL,
    posted_at TEXT NOT NULL
);
ALTER TABLE petitions ADD COLUMN row_version INTEGER NOT NULL DEFAULT 1;
"""

MIGRATION_0003_NAME = "mutation-command-identities"
MIGRATION_0003 = """
CREATE TABLE publish_commands (
    owner_id TEXT NOT NULL REFERENCES accounts(id),
    topic_id TEXT NOT NULL,
    draft_version INTEGER NOT NULL,
    petition_slug TEXT NOT NULL REFERENCES petitions(slug)
        ON DELETE CASCADE,
    idempotency_key TEXT NOT NULL,
    request_fingerprint TEXT NOT NULL,
    created_at TEXT NOT NULL,
    PRIMARY KEY (owner_id, topic_id, idempotency_key)
);
ALTER TABLE supporter_updates
    ADD COLUMN idempotency_key TEXT NOT NULL DEFAULT '';
ALTER TABLE supporter_updates
    ADD COLUMN request_fingerprint TEXT NOT NULL DEFAULT '';
ALTER TABLE supporter_updates
    ADD COLUMN petition_version INTEGER NOT NULL DEFAULT 1;
CREATE UNIQUE INDEX supporter_updates_command_identity
    ON supporter_updates(author_id, idempotency_key)
    WHERE idempotency_key <> '';
CREATE TABLE transient_failures (
    operation TEXT NOT NULL,
    owner_id TEXT NOT NULL REFERENCES accounts(id),
    partition_id TEXT NOT NULL,
    idempotency_key TEXT NOT NULL,
    failed_at TEXT NOT NULL,
    PRIMARY KEY (operation, owner_id, partition_id, idempotency_key)
);
"""

MIGRATION_0004_NAME = "fullstack-auth-and-command-journals"
MIGRATION_0004 = """
CREATE TABLE petition_drafts (
    owner_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    topic_id TEXT NOT NULL,
    draft_version INTEGER NOT NULL,
    status TEXT NOT NULL CHECK (status IN ('draft','published')),
    petition_slug TEXT REFERENCES petitions(slug) ON DELETE SET NULL,
    updated_at TEXT NOT NULL,
    PRIMARY KEY (owner_id, topic_id)
);
CREATE TABLE capability_commands (
    capability_id TEXT NOT NULL,
    owner_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    entity_id TEXT NOT NULL,
    idempotency_key TEXT NOT NULL,
    request_fingerprint TEXT NOT NULL,
    result_code TEXT NOT NULL,
    result_version INTEGER,
    created_at TEXT NOT NULL,
    PRIMARY KEY (capability_id, owner_id, idempotency_key)
);
CREATE TABLE capability_version_journal (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    capability_id TEXT NOT NULL,
    entity_id TEXT NOT NULL,
    entity_version INTEGER NOT NULL,
    actor_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    command_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    UNIQUE (capability_id, entity_id, entity_version)
);
"""

MIGRATION_0005_NAME = "growth-notifications-sharing-and-discovery"
MIGRATION_0005 = """
ALTER TABLE accounts ADD COLUMN email_verified INTEGER NOT NULL DEFAULT 1;
ALTER TABLE petitions ADD COLUMN moderation_status TEXT NOT NULL DEFAULT 'approved'
    CHECK (moderation_status IN ('approved', 'rejected', 'hidden'));

CREATE TABLE organization_targets (
    id TEXT PRIMARY KEY,
    petition_slug TEXT NOT NULL UNIQUE REFERENCES petitions(slug)
        ON DELETE CASCADE,
    owner_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    type TEXT NOT NULL CHECK (type IN ('organization','government','person','other')),
    name TEXT NOT NULL,
    normalized_name TEXT NOT NULL,
    location TEXT NOT NULL DEFAULT '',
    contact_label TEXT NOT NULL DEFAULT '',
    row_version INTEGER NOT NULL DEFAULT 1,
    idempotency_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    UNIQUE (owner_id, idempotency_key)
);

CREATE TABLE follows (
    account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    object_type TEXT NOT NULL CHECK (object_type IN ('petition','organization','topic')),
    object_id TEXT NOT NULL,
    row_version INTEGER NOT NULL DEFAULT 1,
    idempotency_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    PRIMARY KEY (account_id, object_type, object_id),
    UNIQUE (account_id, idempotency_key)
);

CREATE TABLE notification_preferences (
    account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
    in_app_enabled INTEGER NOT NULL DEFAULT 1,
    email_mode TEXT NOT NULL DEFAULT 'off'
        CHECK (email_mode IN ('off','immediate','digest')),
    petition_updates INTEGER NOT NULL DEFAULT 1,
    organization_updates INTEGER NOT NULL DEFAULT 1,
    topic_recommendations INTEGER NOT NULL DEFAULT 1,
    growth_tips INTEGER NOT NULL DEFAULT 1,
    double_opt_in INTEGER NOT NULL DEFAULT 0,
    row_version INTEGER NOT NULL DEFAULT 1,
    updated_at TEXT NOT NULL
);

CREATE TABLE notifications (
    id TEXT PRIMARY KEY,
    account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    category TEXT NOT NULL,
    event_type TEXT NOT NULL,
    object_type TEXT NOT NULL,
    object_id TEXT NOT NULL,
    title TEXT NOT NULL,
    body TEXT NOT NULL,
    dedupe_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    read_at TEXT,
    UNIQUE (account_id, dedupe_key)
);
CREATE INDEX notifications_account_cursor
    ON notifications(account_id, created_at DESC, id DESC);

CREATE TABLE activity_events (
    id TEXT PRIMARY KEY,
    account_id TEXT REFERENCES accounts(id) ON DELETE SET NULL,
    event_type TEXT NOT NULL,
    object_type TEXT NOT NULL,
    object_id TEXT NOT NULL,
    metadata_json TEXT NOT NULL DEFAULT '{}',
    attribution_token TEXT,
    idempotency_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    UNIQUE (event_type, object_type, object_id, idempotency_key)
);

CREATE TABLE share_links (
    token TEXT PRIMARY KEY,
    petition_slug TEXT NOT NULL REFERENCES petitions(slug) ON DELETE CASCADE,
    owner_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    channel TEXT NOT NULL CHECK (channel IN ('copy','email','facebook','x','whatsapp','other')),
    idempotency_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    expires_at TEXT NOT NULL,
    UNIQUE (owner_id, petition_slug, idempotency_key)
);
CREATE TABLE share_clicks (
    id TEXT PRIMARY KEY,
    token TEXT NOT NULL REFERENCES share_links(token) ON DELETE CASCADE,
    visitor_hash TEXT NOT NULL,
    clicked_at TEXT NOT NULL,
    UNIQUE (token, visitor_hash)
);
CREATE TABLE share_attributions (
    account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    token TEXT NOT NULL REFERENCES share_links(token) ON DELETE CASCADE,
    event_type TEXT NOT NULL CHECK (event_type IN ('login','signature')),
    converted_at TEXT NOT NULL,
    PRIMARY KEY (account_id, token, event_type)
);

CREATE TABLE growth_recommendations (
    id TEXT PRIMARY KEY,
    petition_slug TEXT NOT NULL REFERENCES petitions(slug) ON DELETE CASCADE,
    owner_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    rule_id TEXT NOT NULL,
    milestone INTEGER NOT NULL,
    title TEXT NOT NULL,
    rationale TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'active'
        CHECK (status IN ('active','dismissed','completed')),
    created_at TEXT NOT NULL,
    UNIQUE (petition_slug, rule_id, milestone)
);

CREATE TABLE moderation_rules (
    id TEXT NOT NULL,
    version INTEGER NOT NULL,
    kind TEXT NOT NULL CHECK (kind IN ('keyword','pattern')),
    pattern TEXT NOT NULL,
    reason TEXT NOT NULL,
    active INTEGER NOT NULL DEFAULT 1,
    created_at TEXT NOT NULL,
    PRIMARY KEY (id, version)
);
CREATE TABLE moderation_results (
    id TEXT PRIMARY KEY,
    subject_type TEXT NOT NULL,
    subject_id TEXT NOT NULL,
    actor_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    rule_id TEXT,
    rule_version INTEGER,
    decision TEXT NOT NULL CHECK (decision IN ('approved','rejected','hidden')),
    reasons_json TEXT NOT NULL DEFAULT '[]',
    idempotency_key TEXT NOT NULL,
    created_at TEXT NOT NULL,
    UNIQUE (actor_id, subject_type, idempotency_key)
);

CREATE TABLE mail_outbox (
    id TEXT PRIMARY KEY,
    account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    notification_id TEXT REFERENCES notifications(id) ON DELETE CASCADE,
    category TEXT NOT NULL,
    recipient_email TEXT NOT NULL,
    template_id TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'LOCAL_ONLY'
        CHECK (status IN ('LOCAL_ONLY','SMTP_PENDING','SMTP_SENT','SMTP_FAILED')),
    idempotency_key TEXT NOT NULL UNIQUE,
    attempt_count INTEGER NOT NULL DEFAULT 0,
    last_error TEXT,
    created_at TEXT NOT NULL,
    sent_at TEXT
);

CREATE TABLE email_suppressions (
    normalized_email TEXT PRIMARY KEY,
    reason TEXT NOT NULL CHECK (reason IN ('unsubscribe','complaint','hard-bounce')),
    created_at TEXT NOT NULL
);

CREATE TABLE daily_analytics_aggregates (
    day TEXT NOT NULL,
    petition_slug TEXT NOT NULL REFERENCES petitions(slug) ON DELETE CASCADE,
    metric TEXT NOT NULL,
    value INTEGER NOT NULL DEFAULT 0,
    updated_at TEXT NOT NULL,
    PRIMARY KEY (day, petition_slug, metric)
);

CREATE VIRTUAL TABLE petition_search USING fts5(
    slug UNINDEXED,
    title,
    body,
    target,
    topic,
    location,
    organization,
    status UNINDEXED,
    tokenize='unicode61 remove_diacritics 2'
);
"""

MIGRATION_0006_NAME = "membership-and-contribution-payments"
MIGRATION_0006 = """
CREATE TABLE memberships (
    id TEXT PRIMARY KEY,
    owner_key TEXT NOT NULL,
    account_id TEXT REFERENCES accounts(id) ON DELETE SET NULL,
    amount_minor INTEGER NOT NULL CHECK (amount_minor > 0),
    currency TEXT NOT NULL CHECK (currency = 'CAD'),
    status TEXT NOT NULL CHECK (status IN ('active','cancelled')),
    payment_flow_id TEXT NOT NULL UNIQUE,
    payment_attempt_id TEXT NOT NULL UNIQUE,
    row_version INTEGER NOT NULL DEFAULT 1,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);

CREATE INDEX memberships_owner_idx
    ON memberships(owner_key, status, created_at);

CREATE TABLE contributions (
    id TEXT PRIMARY KEY,
    owner_key TEXT NOT NULL,
    account_id TEXT REFERENCES accounts(id) ON DELETE SET NULL,
    amount_minor INTEGER NOT NULL CHECK (amount_minor > 0),
    currency TEXT NOT NULL CHECK (currency = 'CAD'),
    status TEXT NOT NULL CHECK (status = 'completed'),
    payment_flow_id TEXT NOT NULL UNIQUE,
    payment_attempt_id TEXT NOT NULL UNIQUE,
    created_at TEXT NOT NULL
);

CREATE INDEX contributions_owner_idx
    ON contributions(owner_key, created_at);

CREATE TABLE stripe_checkout_sessions (
    provider_session_id TEXT PRIMARY KEY,
    payment_flow_id TEXT NOT NULL UNIQUE,
    owner_key TEXT NOT NULL,
    payment_kind TEXT NOT NULL
        CHECK (payment_kind IN ('membership','contribution')),
    amount_minor INTEGER NOT NULL CHECK (amount_minor > 0),
    currency TEXT NOT NULL CHECK (currency = 'CAD'),
    fingerprint TEXT NOT NULL,
    status TEXT NOT NULL
        CHECK (status IN ('created','completed','failed')),
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);
"""

MIGRATIONS: tuple[tuple[str, str, str], ...] = (
    ("0001", MIGRATION_0001_NAME, MIGRATION_0001),
    ("0002", MIGRATION_0002_NAME, MIGRATION_0002),
    ("0003", MIGRATION_0003_NAME, MIGRATION_0003),
    ("0004", MIGRATION_0004_NAME, MIGRATION_0004),
    ("0005", MIGRATION_0005_NAME, MIGRATION_0005),
    ("0006", MIGRATION_0006_NAME, MIGRATION_0006),
)

HEAD_MIGRATION_ID = MIGRATIONS[-1][0]


def connect(*, create: bool = True) -> sqlite3.Connection:
    """Open the fixture database in WAL mode with dict-like rows."""
    path = db_path()
    if create:
        path.parent.mkdir(parents=True, exist_ok=True)
    connection = sqlite3.connect(str(path))
    connection.row_factory = sqlite3.Row
    connection.execute("PRAGMA journal_mode=WAL")
    connection.execute("PRAGMA foreign_keys=ON")
    connection.execute("PRAGMA busy_timeout=5000")
    return connection


def applied_migrations(connection: sqlite3.Connection) -> list[str]:
    connection.execute(
        "CREATE TABLE IF NOT EXISTS schema_migrations ("
        "version TEXT PRIMARY KEY, name TEXT NOT NULL, "
        "applied_at TEXT NOT NULL)"
    )
    rows = connection.execute(
        "SELECT version FROM schema_migrations ORDER BY version"
    ).fetchall()
    return [row["version"] for row in rows]


def apply_migrations(
    connection: sqlite3.Connection, *, upto: str = HEAD_MIGRATION_ID
) -> list[str]:
    """Apply ordered migrations up to ``upto``; return newly applied ids."""
    done = set(applied_migrations(connection))
    applied: list[str] = []
    for version, name, sql in MIGRATIONS:
        if version in done:
            continue
        if version > upto:
            break
        connection.executescript(sql)
        connection.execute(
            "INSERT INTO schema_migrations (version, name, applied_at) "
            "VALUES (?, ?, ?)",
            (version, name, FROZEN_CLOCK),
        )
        applied.append(version)
    versions = applied_migrations(connection)
    sqlite_version = max((int(version) for version in versions), default=0)
    connection.execute(f"PRAGMA user_version={sqlite_version}")
    connection.commit()
    return applied


# ---------------------------------------------------------------------------
# Deterministic seed — captured petitions as ordinary rows
# ---------------------------------------------------------------------------

SEED_ACCOUNTS: tuple[dict[str, str], ...] = (
    {
        "id": "taylor-brooks-fixture",
        "name": "Taylor Brooks",
        "email": "taylor.brooks@example.test",
    },
    {
        "id": "jordan-rivera-fixture",
        "name": "Jordan Rivera",
        "email": "jordan.rivera@example.test",
    },
    # Fixture-local starter identities for the captured petitions below
    # (the 2026-07-25 capture froze petition titles/targets/counts but
    # not starter accounts, so these are ordinary synthetic accounts).
    {
        "id": "morgan-lee-fixture",
        "name": "Morgan Lee",
        "email": "morgan.lee@example.test",
    },
    {
        "id": "casey-alvarez-fixture",
        "name": "Casey Alvarez",
        "email": "casey.alvarez@example.test",
    },
    {
        "id": "riley-chen-fixture",
        "name": "Riley Chen",
        "email": "riley.chen@example.test",
    },
    {
        "id": "dana-whitfield-fixture",
        "name": "Dana Whitfield",
        "email": "dana.whitfield@example.test",
    },
    {
        "id": "sam-porter-fixture",
        "name": "Sam Porter",
        "email": "sam.porter@example.test",
    },
    {
        "id": "climate-starter-fixture",
        "name": "Climate Justice Initiative",
        "email": "climate.starter@example.test",
    },
    {
        "id": "avery-xie-visual-fixture",
        "name": "Avery Xie",
        "email": "avery.xie.visual@example.test",
    },
)

# Ordinary petition rows.  Titles, targets, and signature baselines for
# rows 2-6 are the captured 2026-07-25 source facts (home/browse cards);
# statuses reflect the captured badges (Victory!) plus one closed row so
# closed-state rejections exercise real data.  Backend logic NEVER
# branches on any of these values.
SEED_PETITIONS: tuple[dict[str, Any], ...] = (
    {
        "slug": "ea1-dfs-controlled-test-petition",
        "title": "EA1 DFS controlled test petition",
        "target": "Change.org controlled test team",
        "body": (
            "This is controlled test content for observing the petition "
            "creation workflow. It does not contact or name any unrelated "
            "person or organisation."
        ),
        "owner_id": "avery-xie-visual-fixture",
        "status": "open",
        "baseline_signatures": 1,
        "path": "scratch",
        # A negative sequence is the generic no-media fixture marker. The
        # public detail renderer uses the standard text-only layout rather
        # than inventing a fallback image for petitions without media.
        "created_seq": -1,
    },
    {
        "slug": "demand-climate-justice-for-a-greener-and-fairer-future",
        "title": "Demand climate justice for a greener and fairer future",
        "target": "National and local leaders",
        "body": (
            "Climate change is not just an abstract issue; it is personal, "
            "tangible, and happening right now. We call on leaders to enact "
            "fair climate policy that protects communities and the planet."
        ),
        "owner_id": "climate-starter-fixture",
        "status": "open",
        "baseline_signatures": 1_828,
        "path": "scratch",
        "created_seq": 6,
    },
    {
        "slug": "keep-riverdale-community-garden-open",
        "title": "Keep the Riverdale community garden open year-round",
        "target": "Riverdale Parks Department",
        "body": (
            "The Riverdale community garden feeds forty families and "
            "anchors the neighborhood. We ask the Parks Department to "
            "keep it open through the winter season."
        ),
        "owner_id": "jordan-rivera-fixture",
        "status": "open",
        "baseline_signatures": 3,
        "path": "scratch",
        "created_seq": 0,
    },
    {
        "slug": "shut-down-the-abusive-provo-canyon-school",
        "title": "Shut down the abusive Provo Canyon School",
        "target": "Utah Department of Human Services",
        "body": (
            "Survivors continue to report abusive treatment at Provo "
            "Canyon School. We ask the Utah Department of Human "
            "Services to shut the facility down."
        ),
        "owner_id": "morgan-lee-fixture",
        "status": "open",
        "baseline_signatures": 211_291,
        "path": "scratch",
        "created_seq": 1,
    },
    {
        "slug": "nashville-zoo-says-no-to-proposed-data-center",
        "title": "Nashville Zoo Says No to Proposed Data Center",
        "target": "Nashville Metro Council",
        "body": (
            "A proposed data center would border the Nashville Zoo and "
            "threaten its animals with constant noise and light. We ask "
            "the Metro Council to reject the proposal."
        ),
        "owner_id": "casey-alvarez-fixture",
        "status": "open",
        "baseline_signatures": 564_843,
        "path": "scratch",
        "created_seq": 2,
    },
    {
        "slug": "audit-california-wildfire-spending",
        "title": (
            "Audit California's Wildfire Spending Before the Next Fire "
            "Season Claims More Homes"
        ),
        "target": "California State Auditor",
        "body": (
            "Billions have been budgeted for wildfire prevention, yet "
            "communities keep burning. We ask the California State "
            "Auditor to audit wildfire spending before the next fire "
            "season."
        ),
        "owner_id": "riley-chen-fixture",
        "status": "open",
        "baseline_signatures": 7_854,
        "path": "scratch",
        "created_seq": 3,
    },
    {
        "slug": "free-the-indigenous-teen-facing-life-in-prison",
        "title": (
            "How a community group freed an indigenous teen facing life "
            "in prison"
        ),
        "target": "California Board of Parole Hearings",
        "body": (
            "A community group organized to free an indigenous teenager "
            "who faced life in prison. The campaign succeeded — this "
            "petition is preserved as a victory."
        ),
        "owner_id": "dana-whitfield-fixture",
        "status": "victory",
        "baseline_signatures": 610_813,
        "path": "scratch",
        "created_seq": 4,
    },
    {
        "slug": "save-bothell-high-school-sro-program",
        "title": "Save Bothell High School's SRO program with Officer Ware",
        "target": "Northshore School District Board",
        "body": (
            "Officer Ware kept Bothell High School students safe for "
            "years. The district ended the SRO program and closed this "
            "petition to new signatures."
        ),
        "owner_id": "sam-porter-fixture",
        "status": "closed",
        "baseline_signatures": 5_510,
        "path": "scratch",
        "created_seq": 5,
    },
)


def seed(connection: sqlite3.Connection) -> None:
    """Idempotently insert the deterministic seed rows."""
    for account in SEED_ACCOUNTS:
        connection.execute(
            "INSERT OR IGNORE INTO accounts (id, name, email, created_at) "
            "VALUES (:id, :name, :email, :created_at)",
            {**account, "created_at": FROZEN_CLOCK},
        )
    for petition in SEED_PETITIONS:
        connection.execute(
            "INSERT OR IGNORE INTO petitions "
            "(slug, title, target, body, owner_id, status, "
            " baseline_signatures, path, created_seq, created_at, "
            " row_version) "
            "VALUES (:slug, :title, :target, :body, :owner_id, :status, "
            " :baseline_signatures, :path, :created_seq, :created_at, 1)",
            {**petition, "created_at": FROZEN_CLOCK},
        )
        target_id = "target-" + hashlib.sha256(
            petition["slug"].encode("utf-8")
        ).hexdigest()[:20]
        connection.execute(
            "INSERT OR IGNORE INTO organization_targets "
            "(id, petition_slug, owner_id, type, name, normalized_name, "
            " location, contact_label, row_version, idempotency_key, "
            " created_at, updated_at) VALUES (?, ?, ?, 'organization', "
            " ?, ?, '', 'Decision maker', 1, ?, ?, ?)",
            (
                target_id,
                petition["slug"],
                petition["owner_id"],
                petition["target"],
                " ".join(petition["target"].casefold().split()),
                f"seed:{petition['slug']}",
                FROZEN_CLOCK,
                FROZEN_CLOCK,
            ),
        )
        search_values = (
            petition["title"],
            petition["body"],
            petition["target"],
            petition["title"],
            "",
            petition["target"],
            petition["status"],
        )
        search_row = connection.execute(
            "SELECT title,body,target,topic,location,organization,status "
            "FROM petition_search WHERE slug=?",
            (petition["slug"],),
        ).fetchone()
        if search_row is None or tuple(search_row) != search_values:
            connection.execute(
                "DELETE FROM petition_search WHERE slug=?",
                (petition["slug"],),
            )
            connection.execute(
                "INSERT INTO petition_search "
                "(slug,title,body,target,topic,location,organization,status) "
                "VALUES (?,?,?,?,?,?,?,?)",
                (petition["slug"], *search_values),
            )
    for account in SEED_ACCOUNTS:
        connection.execute(
            "INSERT OR IGNORE INTO notification_preferences "
            "(account_id, updated_at) VALUES (?, ?)",
            (account["id"], FROZEN_CLOCK),
        )
    for rule in (
        (
            "threat-against-person",
            1,
            "pattern",
            r"credible\s+threat\s+against",
            "Petitions may not contain a credible threat against a person.",
        ),
        (
            "publish-private-contact",
            1,
            "keyword",
            "publish private contact details",
            "Petitions may not publish private contact details.",
        ),
    ):
        connection.execute(
            "INSERT OR IGNORE INTO moderation_rules "
            "(id, version, kind, pattern, reason, active, created_at) "
            "VALUES (?, ?, ?, ?, ?, 1, ?)",
            (*rule, FROZEN_CLOCK),
        )
    connection.commit()


def reset_to_seed() -> dict[str, int]:
    """Wipe every table and restore the deterministic seed; return counts."""
    with closing(connect()) as connection:
        apply_migrations(connection)
        for table in (
            "local_auth_mail_outbox",
            "local_auth_registration_flows",
            "local_auth_password_reset_flows",
            "local_auth_sessions",
            "local_auth_mail_rate_limits",
            "local_auth_accounts",
            "stripe_checkout_sessions",
            "contributions",
            "memberships",
            "daily_analytics_aggregates",
            "email_suppressions",
            "mail_outbox",
            "moderation_results",
            "moderation_rules",
            "growth_recommendations",
            "share_attributions",
            "share_clicks",
            "share_links",
            "activity_events",
            "notifications",
            "notification_preferences",
            "follows",
            "organization_targets",
            "petition_search",
            "capability_version_journal",
            "capability_commands",
            "petition_drafts",
            "transient_failures",
            "publish_commands",
            "comments",
            "supporter_updates",
            "signatures",
            "sessions",
            "petitions",
            "accounts",
        ):
            if connection.execute(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
                (table,),
            ).fetchone():
                connection.execute(f"DELETE FROM {table}")
        connection.execute(
            "DELETE FROM sqlite_sequence WHERE name IN "
            "('signatures', 'supporter_updates', 'comments')"
        )
        connection.commit()
        seed(connection)
        counts = {
            table: int(
                connection.execute(
                    f"SELECT COUNT(*) AS n FROM {table}"
                ).fetchone()["n"]
            )
            for table in (
                "accounts",
                "petitions",
                "signatures",
                "comments",
                "supporter_updates",
                "publish_commands",
                "transient_failures",
                "sessions",
                "organization_targets",
                "follows",
                "notifications",
                "activity_events",
                "share_links",
                "share_clicks",
                "share_attributions",
                "growth_recommendations",
                "moderation_results",
                "moderation_rules",
                "mail_outbox",
                "memberships",
                "contributions",
                "stripe_checkout_sessions",
            )
        }
        for table in (
            "local_auth_accounts",
            "local_auth_sessions",
            "local_auth_registration_flows",
            "local_auth_password_reset_flows",
            "local_auth_mail_outbox",
            "local_auth_mail_rate_limits",
            "petition_drafts",
            "capability_commands",
            "capability_version_journal",
        ):
            if connection.execute(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
                (table,),
            ).fetchone():
                counts[table] = int(
                    connection.execute(
                        f"SELECT COUNT(*) AS n FROM {table}"
                    ).fetchone()["n"]
                )
    return counts


def ensure_ready() -> None:
    """Migrate to head and seed; safe to call on every process start."""
    with closing(connect()) as connection:
        apply_migrations(connection)
        seed(connection)


def db_info() -> dict[str, Any]:
    with closing(connect()) as connection:
        journal_mode = connection.execute("PRAGMA journal_mode").fetchone()[0]
        applied = applied_migrations(connection)
    return {
        "engine": "sqlite3",
        "path": str(db_path()),
        "journal_mode": str(journal_mode).lower(),
        "schema_migrations": applied,
        "head_migration": HEAD_MIGRATION_ID,
        "at_head": bool(applied and applied[-1] == HEAD_MIGRATION_ID),
    }


# ---------------------------------------------------------------------------
# Accounts + persisted sessions
# ---------------------------------------------------------------------------


def _account_dict(row: sqlite3.Row) -> dict[str, str]:
    return {"id": row["id"], "name": row["name"], "email": row["email"]}


def get_account(account_id: str) -> dict[str, str] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT id, name, email FROM accounts WHERE id = ?",
            (account_id,),
        ).fetchone()
    return _account_dict(row) if row else None


def get_account_by_email(email: str) -> dict[str, str] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT id, name, email FROM accounts WHERE email = ?",
            (email.strip().casefold(),),
        ).fetchone()
    return _account_dict(row) if row else None


def _account_id_from_email(email: str) -> str:
    local = email.split("@", 1)[0]
    slug = "".join(
        ch if ch.isalnum() else "-" for ch in local.casefold()
    ).strip("-")
    while "--" in slug:
        slug = slug.replace("--", "-")
    return f"{slug}-fixture"


def _account_name_from_email(email: str) -> str:
    local = email.split("@", 1)[0]
    parts = [p for p in local.replace("_", ".").replace("-", ".").split(".") if p]
    return " ".join(part.capitalize() for part in parts) or "Fixture Member"


def ensure_account(email: str) -> dict[str, str]:
    """Load or deterministically provision the account for ``email``."""
    normalized = email.strip().casefold()
    existing = get_account_by_email(normalized)
    if existing is not None:
        return existing
    account = {
        "id": _account_id_from_email(normalized),
        "name": _account_name_from_email(normalized),
        "email": normalized,
    }
    with closing(connect()) as connection:
        connection.execute(
            "INSERT OR IGNORE INTO accounts (id, name, email, created_at) "
            "VALUES (:id, :name, :email, :created_at)",
            {**account, "created_at": FROZEN_CLOCK},
        )
        connection.commit()
    return account


def create_session(account_id: str) -> str:
    token = secrets.token_urlsafe(32)
    with closing(connect()) as connection:
        connection.execute(
            "INSERT INTO sessions (token, account_id, created_at) "
            "VALUES (?, ?, ?)",
            (token, account_id, FROZEN_CLOCK),
        )
        connection.commit()
    return token


def session_account_id(token: str | None) -> str | None:
    if not token:
        return None
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT account_id FROM sessions WHERE token = ?", (token,)
        ).fetchone()
    return row["account_id"] if row else None


def delete_session(token: str | None) -> None:
    if not token:
        return
    with closing(connect()) as connection:
        connection.execute("DELETE FROM sessions WHERE token = ?", (token,))
        connection.commit()


def session_count() -> int:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT COUNT(*) AS n FROM sessions"
        ).fetchone()
    return int(row["n"])


# ---------------------------------------------------------------------------
# Petitions (counts derived from baseline + real signature rows)
# ---------------------------------------------------------------------------

_PETITION_SELECT = (
    "SELECT p.slug, p.title, p.target, p.body, p.owner_id, p.status, "
    "p.baseline_signatures, p.path, p.created_seq, p.created_at, "
    "p.row_version, a.name AS owner_name "
    "FROM petitions p JOIN accounts a ON a.id = p.owner_id "
)


def _petition_dict(
    connection: sqlite3.Connection, row: sqlite3.Row
) -> dict[str, Any]:
    slug = row["slug"]
    signature_rows = int(
        connection.execute(
            "SELECT COUNT(*) AS n FROM signatures WHERE petition_slug = ?",
            (slug,),
        ).fetchone()["n"]
    )
    updates = [
        {
            "id": int(update["id"]),
            "body": update["body"],
            "posted_at": update["posted_at"],
            "author": update["author_name"],
            "idempotency_key": update["idempotency_key"],
            "petition_version": int(update["petition_version"]),
        }
        for update in connection.execute(
            "SELECT u.id, u.body, u.posted_at, u.idempotency_key, "
            "u.petition_version, a.name AS author_name "
            "FROM supporter_updates u JOIN accounts a ON a.id = u.author_id "
            "WHERE u.petition_slug = ? ORDER BY u.id",
            (slug,),
        ).fetchall()
    ]
    comments = [
        {
            "id": int(comment["id"]),
            "body": comment["body"],
            "posted_at": comment["posted_at"],
            "author": comment["author_name"],
        }
        for comment in connection.execute(
            "SELECT c.id, c.body, c.posted_at, a.name AS author_name "
            "FROM comments c JOIN accounts a ON a.id = c.author_id "
            "WHERE c.petition_slug = ? ORDER BY c.id",
            (slug,),
        ).fetchall()
    ]
    count = int(row["baseline_signatures"]) + signature_rows
    return {
        "slug": slug,
        "title": row["title"],
        "target": row["target"],
        "body": row["body"],
        "owner": row["owner_id"],
        "owner_name": row["owner_name"],
        "status": row["status"],
        "path": row["path"],
        "signatures": count,
        "next_goal": next_goal(count),
        "row_version": int(row["row_version"]),
        "created_seq": int(row["created_seq"]),
        "created_at": row["created_at"],
        "updates": updates,
        "comments": comments,
    }


def get_petition(slug: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            _PETITION_SELECT + "WHERE p.slug = ?", (slug,)
        ).fetchone()
        if row is None:
            return None
        return _petition_dict(connection, row)


def list_petitions() -> list[dict[str, Any]]:
    with closing(connect()) as connection:
        rows = connection.execute(
            _PETITION_SELECT + "ORDER BY p.created_seq DESC, p.slug ASC"
        ).fetchall()
        return [_petition_dict(connection, row) for row in rows]


def petition_count() -> int:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT COUNT(*) AS n FROM petitions"
        ).fetchone()
    return int(row["n"])


def most_recent_for_owner(owner_id: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            _PETITION_SELECT
            + "WHERE p.owner_id = ? "
            "ORDER BY p.created_seq DESC, p.slug ASC LIMIT 1",
            (owner_id,),
        ).fetchone()
        if row is None:
            return None
        return _petition_dict(connection, row)


def list_petitions_for_owner(owner_id: str) -> list[dict[str, Any]]:
    """Return one owner's petitions in the exact frozen dashboard order."""
    with closing(connect()) as connection:
        rows = connection.execute(
            _PETITION_SELECT
            + "WHERE p.owner_id = ? "
            "ORDER BY p.created_seq DESC, p.slug ASC",
            (owner_id,),
        ).fetchall()
        return [_petition_dict(connection, row) for row in rows]


def execute_publish_command(
    *,
    topic_id: str,
    draft_version: int,
    slug: str,
    title: str,
    target: str,
    body: str,
    owner_id: str,
    path: str,
    idempotency_key: str,
    request_fingerprint: str,
) -> tuple[str, dict[str, Any] | None]:
    """Apply one topic-partitioned publish command atomically.

    Returns ``created``, ``replay``, ``idempotency-conflict``, or
    ``slug-conflict`` plus the petition when one exists.
    """
    with closing(connect()) as connection:
        connection.execute("BEGIN IMMEDIATE")
        existing_command = connection.execute(
            "SELECT petition_slug, draft_version, request_fingerprint "
            "FROM publish_commands "
            "WHERE owner_id = ? AND topic_id = ? AND idempotency_key = ?",
            (owner_id, topic_id, idempotency_key),
        ).fetchone()
        if existing_command is not None:
            petition = get_petition(existing_command["petition_slug"])
            if (
                int(existing_command["draft_version"]) == draft_version
                and existing_command["petition_slug"] == slug
                and existing_command["request_fingerprint"]
                == request_fingerprint
            ):
                return "replay", petition
            return "idempotency-conflict", petition

        slug_row = connection.execute(
            "SELECT owner_id FROM petitions WHERE slug = ?", (slug,)
        ).fetchone()
        if slug_row is not None:
            return "slug-conflict", get_petition(slug)

        next_seq = int(
            connection.execute(
                "SELECT COALESCE(MAX(created_seq), -1) + 1 AS n "
                "FROM petitions"
            ).fetchone()["n"]
        )
        connection.execute(
            "INSERT INTO petitions "
            "(slug, title, target, body, owner_id, status, "
            " baseline_signatures, path, created_seq, created_at, "
            " row_version) "
            "VALUES (?, ?, ?, ?, ?, 'open', 0, ?, ?, ?, 1)",
            (
                slug,
                title,
                target,
                body,
                owner_id,
                path,
                next_seq,
                FROZEN_CLOCK,
            ),
        )
        owner_name = connection.execute(
            "SELECT name FROM accounts WHERE id = ?", (owner_id,)
        ).fetchone()["name"]
        connection.execute(
            "INSERT INTO signatures "
            "(petition_slug, account_id, display_name, display_publicly, "
            " reason, signed_at) VALUES (?, ?, ?, 1, '', ?)",
            (slug, owner_id, owner_name, FROZEN_CLOCK),
        )
        connection.execute(
            "INSERT INTO publish_commands "
            "(owner_id, topic_id, draft_version, petition_slug, "
            " idempotency_key, request_fingerprint, created_at) "
            "VALUES (?, ?, ?, ?, ?, ?, ?)",
            (
                owner_id,
                topic_id,
                draft_version,
                slug,
                idempotency_key,
                request_fingerprint,
                FROZEN_CLOCK,
            ),
        )
        connection.execute(
            "INSERT INTO petition_drafts "
            "(owner_id,topic_id,draft_version,status,petition_slug,updated_at) "
            "VALUES (?,? ,?,'published',?,?) "
            "ON CONFLICT(owner_id,topic_id) DO UPDATE SET "
            "draft_version=excluded.draft_version,status='published',"
            "petition_slug=excluded.petition_slug,updated_at=excluded.updated_at",
            (owner_id, topic_id, draft_version, slug, FROZEN_CLOCK),
        )
        connection.execute(
            "INSERT INTO capability_commands "
            "(capability_id,owner_id,entity_id,idempotency_key,"
            "request_fingerprint,result_code,result_version,created_at) "
            "VALUES ('petition-publishing',?,?,?,?, 'created',1,?)",
            (
                owner_id,
                slug,
                f"{topic_id}:{idempotency_key}",
                request_fingerprint,
                FROZEN_CLOCK,
            ),
        )
        connection.execute(
            "INSERT INTO capability_version_journal "
            "(capability_id,entity_id,entity_version,actor_id,command_key,"
            "created_at) VALUES ('petition-publishing',?,1,?,?,?)",
            (slug, owner_id, idempotency_key, FROZEN_CLOCK),
        )
        connection.commit()
    return "created", get_petition(slug)


def insert_petition(
    *,
    slug: str,
    title: str,
    target: str,
    body: str,
    owner_id: str,
    path: str,
) -> dict[str, Any]:
    """Insert a new open petition; the creator signs their own petition."""
    with closing(connect()) as connection:
        next_seq = int(
            connection.execute(
                "SELECT COALESCE(MAX(created_seq), -1) + 1 AS n "
                "FROM petitions"
            ).fetchone()["n"]
        )
        connection.execute(
            "INSERT INTO petitions "
            "(slug, title, target, body, owner_id, status, "
            " baseline_signatures, path, created_seq, created_at, "
            " row_version) "
            "VALUES (?, ?, ?, ?, ?, 'open', 0, ?, ?, ?, 1)",
            (slug, title, target, body, owner_id, path, next_seq,
             FROZEN_CLOCK),
        )
        owner_name = connection.execute(
            "SELECT name FROM accounts WHERE id = ?", (owner_id,)
        ).fetchone()["name"]
        connection.execute(
            "INSERT OR IGNORE INTO signatures "
            "(petition_slug, account_id, display_name, display_publicly, "
            " reason, signed_at) VALUES (?, ?, ?, 1, '', ?)",
            (slug, owner_id, owner_name, FROZEN_CLOCK),
        )
        connection.commit()
    petition = get_petition(slug)
    assert petition is not None
    return petition


# ---------------------------------------------------------------------------
# Signatures (one per account per open petition; idempotent duplicates)
# ---------------------------------------------------------------------------


def _signature_dict(row: sqlite3.Row) -> dict[str, Any]:
    return {
        "id": int(row["id"]),
        "petition_slug": row["petition_slug"],
        "account_id": row["account_id"],
        "display_name": row["display_name"],
        "display_publicly": bool(row["display_publicly"]),
        "reason": row["reason"],
        "signed_at": row["signed_at"],
    }


def get_signature(slug: str, account_id: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM signatures "
            "WHERE petition_slug = ? AND account_id = ?",
            (slug, account_id),
        ).fetchone()
    return _signature_dict(row) if row else None


def get_signature_by_id(signature_id: int) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM signatures WHERE id = ?", (signature_id,)
        ).fetchone()
    return _signature_dict(row) if row else None


def add_signature(
    *,
    slug: str,
    account_id: str,
    display_name: str,
    display_publicly: bool,
    reason: str,
) -> tuple[dict[str, Any], bool]:
    """Insert the account's signature; return (signature, created).

    Duplicate signs are idempotent: the existing row is returned
    unchanged and ``created`` is False (no counter inflation).
    """
    with closing(connect()) as connection:
        connection.execute("BEGIN IMMEDIATE")
        existing_row = connection.execute(
            "SELECT * FROM signatures WHERE petition_slug=? AND account_id=?",
            (slug, account_id),
        ).fetchone()
        if existing_row is not None:
            connection.rollback()
            return _signature_dict(existing_row), False
        petition = connection.execute(
            "SELECT row_version FROM petitions WHERE slug=?",
            (slug,),
        ).fetchone()
        if petition is None:
            connection.rollback()
            raise LookupError(slug)
        old_version = int(petition["row_version"])
        connection.execute(
            "INSERT INTO signatures "
            "(petition_slug, account_id, display_name, display_publicly, "
            " reason, signed_at) VALUES (?, ?, ?, ?, ?, ?)",
            (slug, account_id, display_name, int(display_publicly),
             reason, FROZEN_CLOCK),
        )
        connection.execute(
            "UPDATE petitions SET row_version=row_version+1 "
            "WHERE slug=? AND row_version=?",
            (slug, old_version),
        )
        command_key = f"sign:{slug}"
        fingerprint = hashlib.sha256(
            "\x1f".join(
                (
                    slug,
                    account_id,
                    display_name,
                    "1" if display_publicly else "0",
                    reason,
                )
            ).encode("utf-8")
        ).hexdigest()
        connection.execute(
            "INSERT INTO capability_commands "
            "(capability_id,owner_id,entity_id,idempotency_key,"
            "request_fingerprint,result_code,result_version,created_at) "
            "VALUES ('petition-signature-comment',?,?,?,?, 'created',?,?)",
            (
                account_id,
                slug,
                command_key,
                fingerprint,
                old_version + 1,
                FROZEN_CLOCK,
            ),
        )
        connection.execute(
            "INSERT INTO capability_version_journal "
            "(capability_id,entity_id,entity_version,actor_id,command_key,"
            "created_at) VALUES ('petition-signature-comment',?,?,?,?,?)",
            (
                slug,
                old_version + 1,
                account_id,
                command_key,
                FROZEN_CLOCK,
            ),
        )
        connection.commit()
    signature = get_signature(slug, account_id)
    assert signature is not None
    return signature, True


def update_signature(
    signature_id: int, *, display_publicly: bool, reason: str
) -> None:
    with closing(connect()) as connection:
        connection.execute(
            "UPDATE signatures SET display_publicly = ?, reason = ? "
            "WHERE id = ?",
            (int(display_publicly), reason, signature_id),
        )
        connection.commit()


def signature_row_count(slug: str) -> int:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT COUNT(*) AS n FROM signatures WHERE petition_slug = ?",
            (slug,),
        ).fetchone()
    return int(row["n"])


# ---------------------------------------------------------------------------
# Comments + supporter updates
# ---------------------------------------------------------------------------


def submit_comment_command(
    *,
    slug: str,
    author_id: str,
    body: str,
    expected_petition_version: int,
    idempotency_key: str,
    request_fingerprint: str,
) -> tuple[str, dict[str, Any] | None]:
    """Atomically add one comment with optimistic version and replay safety."""
    with closing(connect()) as connection:
        connection.execute("BEGIN IMMEDIATE")
        existing = connection.execute(
            "SELECT entity_id,request_fingerprint,result_version "
            "FROM capability_commands "
            "WHERE capability_id='petition-signature-comment' "
            "AND owner_id=? AND idempotency_key=?",
            (author_id, idempotency_key),
        ).fetchone()
        if existing is not None:
            connection.rollback()
            payload = {
                "petition_slug": existing["entity_id"],
                "result_version": int(existing["result_version"]),
            }
            if (
                existing["entity_id"] == slug
                and existing["request_fingerprint"] == request_fingerprint
            ):
                return "replay", payload
            return "idempotency-conflict", payload

        petition = connection.execute(
            "SELECT row_version FROM petitions WHERE slug=?",
            (slug,),
        ).fetchone()
        if petition is None:
            connection.rollback()
            return "missing", None
        current_version = int(petition["row_version"])
        if current_version != expected_petition_version:
            connection.rollback()
            return "stale", {"current_version": current_version}

        version_update = connection.execute(
            "UPDATE petitions SET row_version=row_version+1 "
            "WHERE slug=? AND row_version=?",
            (slug, expected_petition_version),
        )
        if version_update.rowcount != 1:
            connection.rollback()
            refreshed = get_petition(slug)
            return "stale", {
                "current_version": (
                    int(refreshed["row_version"]) if refreshed else -1
                )
            }

        cursor = connection.execute(
            "INSERT INTO comments (petition_slug, author_id, body, "
            "posted_at) VALUES (?, ?, ?, ?)",
            (slug, author_id, body, FROZEN_CLOCK),
        )
        result_version = expected_petition_version + 1
        connection.execute(
            "INSERT INTO capability_commands "
            "(capability_id,owner_id,entity_id,idempotency_key,"
            "request_fingerprint,result_code,result_version,created_at) "
            "VALUES ('petition-signature-comment',?,?,?,?, 'created',?,?)",
            (
                author_id,
                slug,
                idempotency_key,
                request_fingerprint,
                result_version,
                FROZEN_CLOCK,
            ),
        )
        connection.execute(
            "INSERT INTO capability_version_journal "
            "(capability_id,entity_id,entity_version,actor_id,command_key,"
            "created_at) "
            "VALUES ('petition-signature-comment',?,?,?,?,?)",
            (
                slug,
                result_version,
                author_id,
                idempotency_key,
                FROZEN_CLOCK,
            ),
        )
        connection.commit()
        return "created", {
            "id": int(cursor.lastrowid),
            "petition_slug": slug,
            "result_version": result_version,
        }


def comment_count(slug: str) -> int:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT COUNT(*) AS n FROM comments WHERE petition_slug = ?",
            (slug,),
        ).fetchone()
    return int(row["n"])


def consume_transient_failure(
    *,
    operation: str,
    owner_id: str,
    partition_id: str,
    idempotency_key: str,
) -> bool:
    """Fail exactly once for an explicitly requested deterministic probe."""
    with closing(connect()) as connection:
        connection.execute("BEGIN IMMEDIATE")
        existing = connection.execute(
            "SELECT 1 FROM transient_failures "
            "WHERE operation = ? AND owner_id = ? "
            "AND partition_id = ? AND idempotency_key = ?",
            (operation, owner_id, partition_id, idempotency_key),
        ).fetchone()
        if existing is not None:
            return False
        connection.execute(
            "INSERT INTO transient_failures "
            "(operation, owner_id, partition_id, idempotency_key, failed_at) "
            "VALUES (?, ?, ?, ?, ?)",
            (
                operation,
                owner_id,
                partition_id,
                idempotency_key,
                FROZEN_CLOCK,
            ),
        )
        connection.commit()
        return True


def submit_update_command(
    *,
    petition_slug: str,
    body: str,
    author_id: str,
    expected_petition_version: int,
    idempotency_key: str,
    request_fingerprint: str,
) -> tuple[str, dict[str, Any] | None]:
    """Apply a supporter update with optimistic version and idempotency.

    Duplicate identical commands return ``replay`` without a second update or
    row-version bump. Reusing a key for different bytes returns
    ``idempotency-conflict``. A version mismatch returns ``stale``.
    """
    with closing(connect()) as connection:
        existing = connection.execute(
            "SELECT id, petition_slug, body, request_fingerprint, "
            "petition_version FROM supporter_updates "
            "WHERE author_id = ? AND idempotency_key = ?",
            (author_id, idempotency_key),
        ).fetchone()
        if existing is not None:
            payload = {
                "id": int(existing["id"]),
                "petition_slug": existing["petition_slug"],
                "body": existing["body"],
                "petition_version": int(existing["petition_version"]),
            }
            if (
                existing["petition_slug"] == petition_slug
                and existing["request_fingerprint"] == request_fingerprint
                and existing["body"] == body
            ):
                return "replay", payload
            return "idempotency-conflict", payload

        petition = connection.execute(
            "SELECT owner_id, row_version FROM petitions WHERE slug = ?",
            (petition_slug,),
        ).fetchone()
        if petition is None:
            return "missing", None
        if petition["owner_id"] != author_id:
            return "foreign-owner", None
        current_version = int(petition["row_version"])
        if current_version != expected_petition_version:
            return "stale", {"current_version": current_version}

        version_update = connection.execute(
            "UPDATE petitions SET row_version = row_version + 1 "
            "WHERE slug = ? AND row_version = ?",
            (petition_slug, expected_petition_version),
        )
        if version_update.rowcount != 1:
            connection.rollback()
            refreshed = get_petition(petition_slug)
            return "stale", {
                "current_version": (
                    int(refreshed["row_version"]) if refreshed else -1
                )
            }
        cursor = connection.execute(
            "INSERT INTO supporter_updates "
            "(petition_slug, body, author_id, posted_at, idempotency_key, "
            " request_fingerprint, petition_version) "
            "VALUES (?, ?, ?, ?, ?, ?, ?)",
            (
                petition_slug,
                body,
                author_id,
                FROZEN_CLOCK,
                idempotency_key,
                request_fingerprint,
                expected_petition_version,
            ),
        )
        connection.execute(
            "INSERT INTO capability_commands "
            "(capability_id,owner_id,entity_id,idempotency_key,"
            "request_fingerprint,result_code,result_version,created_at) "
            "VALUES ('supporter-update',?,?,?,?, 'created',?,?)",
            (
                author_id,
                petition_slug,
                idempotency_key,
                request_fingerprint,
                expected_petition_version + 1,
                FROZEN_CLOCK,
            ),
        )
        connection.execute(
            "INSERT INTO capability_version_journal "
            "(capability_id,entity_id,entity_version,actor_id,command_key,"
            "created_at) VALUES ('supporter-update',?,?,?,?,?)",
            (
                petition_slug,
                expected_petition_version + 1,
                author_id,
                idempotency_key,
                FROZEN_CLOCK,
            ),
        )
        connection.commit()
        return "created", {
            "id": int(cursor.lastrowid),
            "petition_slug": petition_slug,
            "body": body,
            "petition_version": expected_petition_version,
        }


def update_count(slug: str) -> int:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT COUNT(*) AS n FROM supporter_updates "
            "WHERE petition_slug = ?",
            (slug,),
        ).fetchone()
    return int(row["n"])