BREP_plm 0.11.0

The BREP PLM server: parts, revisions, lifecycle, checkout, BOMs and configurable workflows over an embedded SQLite store, with a browser UI and the document API the BREP CAD app stores through.
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
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
//! The store: the metadata in SQLite (`plm.sqlite`, see [`crate::sql`]), one
//! file per CAD document, and the monotonic change sequence the CAD app's
//! mirror will key its cache on.
//!
//! # Memory, then disk, in one critical section
//!
//! The whole metadata is held in memory under one lock and every read is
//! answered from there. Every change goes through [`Db::mutate`]: under the
//! write lock, the change's closure checks its rules against the in-memory
//! state and edits it, and then — still under the lock — exactly what it
//! touched is written to SQLite in ONE transaction, together with the
//! change's audit events. If the closure refuses, or the transaction fails,
//! the in-memory edits are undone and nothing is on disk. So every rule that
//! "runs inside the lock" runs in the same critical section as the write that
//! depends on it, and the schema's own constraints (one number per part, one
//! label per revision within a part) refuse anything a rule missed.
//!
//! A change costs what it touched, not what the store holds: the part list
//! journals the parts a change touches ([`crate::table::Parts`]), and the
//! other state fields — users, sessions, the catalog, settings — are small.
//!
//! # Documents
//!
//! Write to `<path>.tmp`, then rename. A rename over an existing file is
//! atomic on every platform this runs on, so a process killed mid-write leaves
//! either the old file or the new one and never a truncated one.
//!
//! # The sequence
//!
//! `seq` increments on every mutation, whoever made it, and every mutating
//! response carries it. That is the `mutation_generation()` the CAD app's
//! `ModelStore` requires — a REQUIRED trait method precisely so a backend
//! cannot compile while silently never invalidating anything. `changes(since)`
//! then answers "which keys moved", which is what drives a client's per-key
//! refresh instead of a re-hydrate.
//!
//! The change log is bounded ([`CHANGE_LOG_LIMIT`]). A client that asks from
//! further back than the log reaches is told `stale`, and its correct response
//! is to re-read the index rather than to trust a short answer.
//!
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::audit::{self, AuditFilter, AuditSink};
use crate::auth;
use crate::bom;
use crate::catalog;
use crate::lifecycle;
use crate::model::{
    groups, ApiToken, AttributeDef, AuditEvent, EntityRef, Category, Company, DocumentClass, Lifecycle, Lock, NumberMode, Part, PartType, Revision, Session, Settings,
    Timestamp, Use, User,
};
use crate::scripting::{self, HookResult, Scripts};
use crate::security::{Security, ServerConfig};
use crate::sourcing;
use crate::sql::{self, Durability, Sql};
use crate::table::Parts;
use crate::Error;

/// How many recent key changes the log keeps. Past this a client is told to
/// re-index rather than given a partial answer.
pub const CHANGE_LOG_LIMIT: usize = 4096;

/// One key that changed, and the sequence it changed at.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Change {
    pub seq: u64,
    pub key: String,
}

/// Everything the server holds in memory, and exactly what the metadata file
/// contains.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct State {
    /// The tools library ([`crate::tools`]), and the last tool number handed out.
    #[serde(default)]
    pub tools: Vec<crate::tools::Tool>,
    #[serde(default)]
    pub next_tool: u64,
    /// The jobs floor queue ([`crate::jobs`]), journaled like sessions: a
    /// floor signs a step a minute, and a list kept in the state's other
    /// fields cost every write on the server O(every job) — 0.56 s at 1,000
    /// jobs of 30 steps. One `meta` row per job (`job:<id>`).
    // Stored separately from the metadata snapshot and restored after decoding it.
    #[serde(default)]
    pub jobs: crate::journal::Journaled<crate::jobs::Job>,
    /// The last job number handed out.
    #[serde(default)]
    pub next_job: u64,
    pub workflows: Vec<crate::workflow::Definition>,
    pub workflow_runs: Vec<crate::workflow::Run>,
    pub bom_configuration: crate::bom_config::Configuration,
    pub seq: u64,
    pub users: Vec<User>,
    /// Browser sessions, journaled ([`crate::journal`]): one is added per
    /// sign-in, so this grows with use, and a list outside a journal costs
    /// every write O(its length).
    // Stored separately from the metadata snapshot and restored after decoding it.
    #[serde(default)]
    pub sessions: crate::journal::Journaled<Session>,
    /// Bearer tokens for callers that are not a browser ([`ApiToken`]).
    pub api_tokens: Vec<ApiToken>,
    pub part_types: Vec<PartType>,
    // Stored separately from the metadata snapshot and restored after decoding it.
    #[serde(default)]
    pub parts: Parts,
    /// The catalog tree, flat: each category names its parent.
    pub categories: Vec<Category>,
    /// Who makes parts ([`Company`]); a manufacturer part names one.
    pub manufacturers: Vec<Company>,
    /// Who sells parts ([`Company`]); a supplier offer names one.
    pub suppliers: Vec<Company>,
    /// The administrator's policy choices ([`Settings`]).
    pub settings: Settings,
    /// The workspace model the store is at ([`crate::workspace::MODEL`]);
    /// an older one is brought up to date when the store opens.
    #[serde(default)]
    pub workspace_model: u32,
    pub changes: Vec<Change>,
    /// The lowest sequence the change log can still answer for completely.
    /// It moves only when [`CHANGE_LOG_LIMIT`] forces entries out, so a
    /// client is told `stale` when the log has actually DROPPED something it
    /// needed — not merely because nothing happened at the sequence it asked
    /// from, which is the ordinary case for a client that has been idle.
    pub changes_from: u64,
    /// Every user's workspace entries ([`crate::model::WorkspaceEntry`]),
    /// in creation order.
    // Stored separately from the metadata snapshot and restored after decoding it.
    #[serde(default)]
    pub workspace: crate::workspace::Workspace,
}

impl State {
    /// Record that every revision of `part_id` moved: a lock, a lifecycle or
    /// a supersede changes the store index's rows for them (`locked_by`,
    /// `lifecycle`, `editable`) without writing a document, and the change
    /// feed has to name them so a client can re-read exactly those rows
    /// (`GET /api/store/index?keys=`) instead of the whole index.
    pub(crate) fn touch_part(&mut self, part_id: &str) {
        let keys: Vec<String> = self
            .part(part_id)
            .map(|part| part.revisions.iter().map(|r| r.document_key(&part.id)).collect())
            .unwrap_or_default();
        for key in keys {
            self.touch(key);
        }
    }

    /// Record that `key`'s document moved at the current sequence. Called
    /// inside a mutation, AFTER [`Db::mutate`] has bumped `seq`.
    pub(crate) fn touch(&mut self, key: String) {
        let seq = self.seq;
        self.changes.retain(|change| change.key != key);
        self.changes.push(Change { seq, key });
        if self.changes.len() > CHANGE_LOG_LIMIT {
            let excess = self.changes.len() - CHANGE_LOG_LIMIT;
            let dropped: Vec<Change> = self.changes.drain(..excess).collect();
            if let Some(last) = dropped.last() {
                self.changes_from = self.changes_from.max(last.seq);
            }
        }
    }

    pub fn user(&self, id: &str) -> Option<&User> {
        self.users.iter().find(|u| u.id == id)
    }

    pub fn user_by_name(&self, username: &str) -> Option<&User> {
        let username = username.trim().to_ascii_lowercase();
        self.users
            .iter()
            .find(|u| u.username.to_ascii_lowercase() == username)
    }

    pub fn part(&self, id: &str) -> Option<&Part> {
        self.parts.get(id)
    }

    pub fn part_type(&self, id: &str) -> Option<&PartType> {
        self.part_types.iter().find(|t| t.id == id)
    }

    /// A part by its id, or else by its number.
    pub fn part_by_id_or_number(&self, key: &str) -> Option<&Part> {
        let key = key.trim();
        self.part(key).or_else(|| self.part_with_number(key))
    }

    /// The part that already carries `number`, compared without regard to
    /// ASCII case. A part number is unique across ALL parts, whatever type
    /// made it: it is what an ERP, a BOM and a person reading a drawing
    /// use to mean exactly one part.
    pub fn part_with_number(&self, number: &str) -> Option<&Part> {
        let number = number.trim();
        self.parts.iter().find(|p| p.number.eq_ignore_ascii_case(number))
    }

    /// The oldest sequence the change log can still answer for completely.
    /// A client asking from before this is told `stale` and must re-index.
    pub fn changes_floor(&self) -> u64 {
        self.changes_from
    }
}

/// The server's whole persistent state: the metadata under one lock (and in
/// SQLite), the document tree beside it, and the administrator's scripts.
///
/// A `Db` is a HANDLE: cloning it is cheap and every clone is the same store.
/// That is what lets a script's `plm.*` bindings hold the store for the length
/// of one hook call.
#[derive(Clone)]
pub struct Db {
    root: PathBuf,
    state: Arc<RwLock<State>>,
    scripts: Arc<Scripts>,
    security: Arc<Security>,
    /// The metadata on disk, and the audit log and search index with it.
    sql: Arc<Sql>,
    /// This process's hold on the data directory ([`crate::dirlock`]), for as
    /// long as any handle to the store is alive.
    _lock: Arc<crate::dirlock::DirLock>,
    /// The last backup this process took, and whether one is running.
    backups: Arc<crate::backup::Status>,
    pub(crate) bake_worker: Arc<crate::bake_worker::Controller>,
}

/// Whole seconds since the epoch.
pub fn now() -> Timestamp {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

impl Db {
    /// Open (or create) the store at `root`.
    ///
    /// Returns the generated administrator password when — and only when —
    /// this call seeded the first account. It is printed once at boot and
    /// never recoverable, which is the point: no build of this server ships a
    /// known password.
    pub fn open(root: impl Into<PathBuf>) -> io::Result<(Self, Option<String>)> {
        Self::open_with_scripts(root, None)
    }

    /// [`Db::open`], with the scripts directory somewhere other than
    /// `<root>/scripts` — typically a git checkout the administrator manages.
    /// This is the path `serve` opens with, always at [`Durability::Full`].
    pub fn open_with_scripts(
        root: impl Into<PathBuf>,
        scripts: Option<PathBuf>,
    ) -> io::Result<(Self, Option<String>)> {
        Self::open_with(root, scripts, Durability::Full)
    }

    /// [`Db::open_with_scripts`] at a chosen [`Durability`]. The test suites
    /// open with [`Durability::Normal`]; the server never does.
    pub fn open_with(
        root: impl Into<PathBuf>,
        scripts: Option<PathBuf>,
        durability: Durability,
    ) -> io::Result<(Self, Option<String>)> {
        let root = root.into();
        // First, before anything in the directory is read or moved: two
        // servers on one directory would each hold their own copy of the
        // metadata and overwrite each other's changes.
        let lock = crate::dirlock::DirLock::acquire(&root)?;
        fs::create_dir_all(root.join("models"))?;
        let scripts = Scripts::new(scripts.unwrap_or_else(|| root.join("scripts")))?;
        let sql = Sql::open_with(root.join(SQLITE_FILE), durability).map_err(io::Error::other)?;
        let loaded = sql.load().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        let fresh = loaded.is_none();
        let mut state = loaded.unwrap_or_default();
        if state.parts.iter().any(|p| p.id != p.number || p.revisions.iter().any(|r| r.id != r.label)) {
            return Err(io::Error::new(io::ErrorKind::InvalidData,
                "part and revision identities must match their current number and label"));
        }
        let before = sql::small_value(&mut state);
        // A store with no workspace entries has nothing to convert: it is at
        // the current model from the start, with no audited change.
        if state.workspace.iter().next().is_none() {
            state.workspace_model = crate::workspace::MODEL;
        }

        let mut seeded = None;
        if state.part_types.is_empty() {
            // The DEFAULT, not the rule: prefix and width are data from here
            // on, and an operator adds more types through the API.
            state.part_types.push(PartType {
                id: "component".into(),
                name: "Component".into(),
                prefix: "CPART".into(),
                digits: 9,
                next: 1,
                created_at: now(),
                mode: Default::default(),
            });
        }
        if state.users.is_empty() {
            let password = auth::random_token(12);
            state.users.push(User {
                id: auth::new_id(),
                username: "admin".into(),
                display_name: "Administrator".into(),
                email: String::new(),
                password: auth::hash_password(&password),
                groups: vec![groups::ADMIN.into()],
                active: true,
                created_at: now(),
            });
            seeded = Some(password);
        }
        let after = sql::small_value(&mut state);
        if fresh || before != after {
            let change = sql::Change {
                before: &if fresh { Value::Object(Default::default()) } else { before },
                after: &after,
                parts: Vec::new(),
                categories: &state.categories,
                reindex: Vec::new(),
                all_parts: &state.parts,
                workspace: Vec::new(),
                sessions: Vec::new(),
                jobs: Vec::new(),
            };
            sql.write(&change, Vec::new()).map_err(io::Error::other)?;
        }

        let db = Db {
            root,
            state: Arc::new(RwLock::new(state)),
            scripts: Arc::new(scripts),
            security: Arc::new(Security::default()),
            sql: Arc::new(sql),
            _lock: Arc::new(lock),
            backups: Arc::new(crate::backup::Status::default()),
            bake_worker: Arc::new(crate::bake_worker::Controller::default()),
        };
        // What a crash between an upload's move and its commit can leave:
        // nothing else is running yet, and the directory is ours alone.
        match db.sweep_blobs() {
            Ok(0) => {}
            Ok(n) => eprintln!("brep-plm: removed {n} unreferenced attachment file(s)"),
            Err(error) => eprintln!("brep-plm: could not sweep attachment files: {error}"),
        }
        db.recover_workflows().map_err(io::Error::other)?;
        if db.read(|state| state.workspace_model < crate::workspace::MODEL) {
            db.mutate(crate::workspace::migrate).map_err(io::Error::other)?;
        }
        Ok((db, seeded))
    }



    /// The administrator's scripts directory.
    /// The data directory.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Stop only the child owned by this server, including on shutdown.
    pub fn stop_bake_worker(&self) -> Result<crate::bake_worker::Status, Error> {
        self.bake_worker.stop(self.security.config.bake_worker.as_ref())
    }

    pub fn scripts(&self) -> &Scripts {
        &self.scripts
    }

    /// This store with the network-facing configuration `config`. Called once,
    /// at start-up, before the store is shared; the throttle starts empty.
    pub fn with_config(mut self, config: ServerConfig) -> Self {
        self.security = Arc::new(Security { config, ..Security::default() });
        self
    }

    /// The last backup this process took.
    pub fn backups(&self) -> &crate::backup::Status {
        &self.backups
    }

    /// The hardening layer: configuration and the sign-in throttle.
    pub fn security(&self) -> &Security {
        &self.security
    }

    /// Whether administrators may edit and test-run scripts in the browser:
    /// the setting, unless `--lock-script-editor` forces it off.
    pub fn script_editor_allowed(&self) -> bool {
        !self.security.config.lock_script_editor && self.read(|state| state.settings.script_editor_enabled)
    }

    /// Read the metadata under the shared lock.
    pub fn read<R>(&self, f: impl FnOnce(&State) -> R) -> R {
        let state = self.state.read().unwrap_or_else(|e| e.into_inner());
        f(&state)
    }

    /// Mutate the metadata under the exclusive lock, bump the sequence, and
    /// PERSIST before returning.
    ///
    /// Persisting inside the guard is what makes number allocation safe: two
    /// concurrent part creations serialize on this lock, and neither response
    /// is sent until the number it handed out is committed. A closure that
    /// returns `Err` leaves the state untouched: the parts it touched are put
    /// back from the journal ([`Parts`]) and every other field from the copy
    /// taken before it ran. The same happens when the write to disk fails —
    /// a UNIQUE constraint the closure's own check missed, a full disk.
    ///
    /// The change's audit events ([`crate::audit`]) are computed from exactly
    /// what it touched and committed in the SAME transaction as the change, so
    /// a change is never on disk without its events, nor an event without its
    /// change. Every write path goes through here, so every change is logged
    /// without any of them asking.
    pub fn mutate<R>(&self, f: impl FnOnce(&mut State) -> Result<R, Error>) -> Result<R, Error> {
        let mut state = self.state.write().unwrap_or_else(|e| e.into_inner());
        let before = sql::small_value(&mut state);
        state.parts.begin();
        state.workspace.begin();
        state.sessions.begin();
        state.jobs.begin();
        state.seq += 1;
        match f(&mut state) {
            Ok(value) => {
                let touched = state.parts.commit();
                let entries = state.workspace.commit();
                let sessions = state.sessions.commit();
                let jobs = state.jobs.commit();
                match self.persist(&mut state, &before, &touched, &entries, &sessions, &jobs) {
                    Ok(()) => Ok(value),
                    Err(error) => {
                        state.parts.undo(touched);
                        state.workspace.undo(entries);
                        state.sessions.undo(sessions);
                        state.jobs.undo(jobs);
                        restore_small(&mut state, &before)?;
                        Err(error)
                    }
                }
            }
            Err(error) => {
                state.parts.rollback();
                state.workspace.rollback();
                state.sessions.rollback();
                state.jobs.rollback();
                restore_small(&mut state, &before)?;
                Err(error)
            }
        }
    }

    /// Write one committed change and its audit events in one transaction.
    fn persist(
        &self,
        state: &mut State,
        before: &Value,
        touched: &[crate::table::Touched],
        entries: &[crate::journal::Touched<crate::model::WorkspaceEntry>],
        sessions: &[crate::journal::Touched<Session>],
        jobs: &[crate::journal::Touched<crate::jobs::Job>],
    ) -> Result<(), Error> {
        let after = sql::small_value(state);
        // A part a change borrowed mutably but did not actually change is
        // neither written nor audited.
        let mut old_parts = Vec::new();
        let mut new_parts = Vec::new();
        let mut changed = Vec::new();
        for t in touched {
            let now_part = &state.parts[t.position];
            let now_value = serde_json::to_value(now_part).map_err(Error::internal)?;
            let was_value = match &t.before {
                Some(part) => Some(serde_json::to_value(part).map_err(Error::internal)?),
                None => None,
            };
            if was_value.as_ref() == Some(&now_value) {
                continue;
            }
            old_parts.extend(was_value);
            new_parts.push(now_value);
            changed.push((t.position, now_part));
        }
        // The journaled lists the same way: only what was touched, and only
        // what actually changed, is written and audited.
        let (old_entries, new_entries, workspace) = journal_rows(&state.workspace, entries)?;
        let (old_sessions, new_sessions, session_rows) = journal_rows(&state.sessions, sessions)?;
        let (old_jobs, new_jobs, job_rows) = journal_rows(&state.jobs, jobs)?;
        let mut old = before.clone();
        let mut new = after.clone();
        if let (Some(o), Some(n)) = (old.as_object_mut(), new.as_object_mut()) {
            o.insert("parts".into(), Value::Array(old_parts));
            n.insert("parts".into(), Value::Array(new_parts));
            o.insert("workspace".into(), Value::Array(old_entries));
            n.insert("workspace".into(), Value::Array(new_entries));
            o.insert("sessions".into(), Value::Array(old_sessions));
            n.insert("sessions".into(), Value::Array(new_sessions));
            o.insert("jobs".into(), Value::Array(old_jobs));
            n.insert("jobs".into(), Value::Array(new_jobs));
        }
        let events = audit::refine(audit::diff(&old, &new, &audit::current_actor(), now(), state.seq));
        // A part's search row holds its category's PATH ("Fasteners /
        // Screws"): re-index the parts whose category's path the change moved
        // — a rename, a move, a category created for text a part already had.
        let mut reindex = Vec::new();
        if before.get("categories") != after.get("categories") {
            let old_categories: Vec<Category> =
                serde_json::from_value(before.get("categories").cloned().unwrap_or_default()).unwrap_or_default();
            let moved: BTreeSet<String> = old_categories
                .iter()
                .chain(state.categories.iter())
                .map(|c| c.id.to_ascii_lowercase())
                .filter(|id| catalog::path_name(&old_categories, id) != catalog::path_name(&state.categories, id))
                .collect();
            reindex = state
                .parts
                .iter()
                .enumerate()
                .filter(|(_, p)| moved.contains(&p.category.to_ascii_lowercase()))
                .map(|(i, _)| i)
                .collect();
        }
        let change = sql::Change {
            before,
            after: &after,
            parts: changed,
            categories: &state.categories,
            reindex,
            all_parts: &state.parts,
            workspace,
            sessions: session_rows,
            jobs: job_rows,
        };
        self.sql.write(&change, events).map(|_| ()).map_err(|error| {
            if sql::is_constraint(&error) {
                Error::conflict(format!("the store refused the change: {error}"))
            } else {
                Error::internal(error)
            }
        })
    }

    /// Record an event that is not a change to the store: a failed sign-in, a
    /// script file edited or run in the browser.
    pub fn record(&self, action: &str, entity: EntityRef, detail: impl Into<String>) {
        let event = AuditEvent {
            id: 0,
            at: now(),
            actor: audit::current_actor(),
            action: action.to_string(),
            entity,
            changes: BTreeMap::new(),
            detail: detail.into(),
            seq: 0,
        };
        if let Err(error) = self.sql.append(vec![event]) {
            eprintln!("brep-plm: audit: could not append to the log: {error}");
        }
    }

    /// Audit events matching `filter`, newest first.
    pub fn audit_query(&self, filter: &AuditFilter) -> Result<Vec<AuditEvent>, Error> {
        self.sql.query(filter).map_err(Error::internal)
    }

    /// The SQLite store, for the search index and diagnostics.
    pub fn sql(&self) -> &Sql {
        &self.sql
    }

    // -- documents ---------------------------------------------------------

    pub(crate) fn document_path(&self, key: &str) -> Result<PathBuf, Error> {
        let (part, revision) = crate::identity::split_key(key)
            .ok_or_else(|| Error::bad_request(format!("'{key}' is not a usable document key")))?;
        Ok(self.root.join(crate::identity::model_path(&part, &revision)))
    }

    /// One document's text, or `None` when it has never been written.
    pub fn read_document(&self, key: &str) -> Result<Option<String>, Error> {
        let path = self.document_path(key)?;
        match fs::read_to_string(path) {
            Ok(text) => Ok(Some(text)),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(Error::internal(error)),
        }
    }

    /// Write a document and record its hash on the revision.
    ///
    /// The editable check is HERE, not only in the API layer: this is the one
    /// function that can change a revision's bytes, so it is the one that has
    /// to refuse a released revision. A guard that lives only in the handler
    /// is a guard that the next caller forgets.
    ///
    /// Everything happens inside one [`Db::mutate`], which is what makes the
    /// check race-free — a release landing between a separate check and the
    /// write would otherwise rewrite released bytes. Within the guard the file
    /// still lands BEFORE the metadata that describes it, so a crash between
    /// the two leaves a document whose hash is not yet recorded, rather than a
    /// recorded hash for bytes that do not exist.
    pub fn write_document(&self, part_id: &str, revision_id: &str, body: &str) -> Result<u64, Error> {
        self.write_document_inner(part_id, revision_id, body, None, None).map(|(seq, _)| seq)
    }

    /// [`Self::write_document`] (or [`Self::write_document_if`] with
    /// `if_match`), answering also why the document's uses list was NOT
    /// derived from it, when it was not (S5 derived, `derived-uses`): an
    /// occurrence that places no PLM revision, or a list the uses rules
    /// refuse. The document is written either way, as it was when the CAD app
    /// published the list in a request of its own.
    pub fn write_document_deriving(&self, part_id: &str, revision_id: &str, body: &str, if_match: Option<&str>) -> Result<(u64, Option<String>), Error> {
        self.write_document_inner(part_id, revision_id, body, None, if_match)
    }

    /// [`Self::write_document`] only if the revision still holds the document
    /// whose content hash is `expected` (an `If-Match` write): checked under
    /// the write lock, so a save made meanwhile (another client of the same
    /// user, another session) is never overwritten by a write based on the
    /// older document. A mismatch is `409`, naming when it changed and who
    /// holds it now.
    pub fn write_document_if(&self, part_id: &str, revision_id: &str, body: &str, expected: &str) -> Result<u64, Error> {
        self.write_document_inner(part_id, revision_id, body, None, Some(expected)).map(|(seq, _)| seq)
    }

    /// Import a reviewed document and its structure together. The expected
    /// hash and checkout are checked under the write lock, so another save or
    /// a broken checkout cannot silently replace the document reviewed by the user.
    pub fn write_import_document(&self, user: &User, part_id: &str, revision_id: &str, expected_hash: &str, body: &str, uses: &Value) -> Result<u64, Error> {
        self.write_document_inner(part_id, revision_id, body, Some((user, expected_hash, uses)), None).map(|(seq, _)| seq)
    }

    fn write_document_inner(&self, part_id: &str, revision_id: &str, body: &str, import: Option<(&User, &str, &Value)>, if_match: Option<&str>) -> Result<(u64, Option<String>), Error> {
        let key = crate::identity::document_key(part_id, revision_id);
        let path = self.document_path(&key)?;
        let hash = auth::content_hash(body);
        let embedded = crate::thumbnail::embedded(self.root(), body)?;
        let has_geometry = crate::geometry::contains_geometry(body);
        self.mutate(move |state| {
            let imported_uses = if let Some((user, expected, uses)) = import {
                check_writable(state, user, part_id, revision_id)?;
                let revision = state.part(part_id).and_then(|p| p.revision(revision_id))
                    .ok_or_else(|| Error::not_found("revision"))?;
                if revision.content_hash != expected {
                    return Err(Error::conflict("the document changed since the import was reviewed; review it again"));
                }
                Some(bom::check_uses(state, part_id, uses)?)
            } else { None };
            if let Some(expected) = if_match {
                let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
                let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
                if revision.content_hash != expected {
                    let holder = revision
                        .lock
                        .as_ref()
                        .and_then(|lock| state.user(&lock.user_id))
                        .map_or_else(String::new, |user| format!(", checked out by {}", user.username));
                    return Err(Error::conflict(format!(
                        "{} rev {} was saved again on the PLM (at {:02}:{:02} UTC{holder}) after the document this save was based on: not overwritten",
                        part.number,
                        revision.label,
                        revision.modified_at % 86_400 / 3_600,
                        revision.modified_at % 3_600 / 60,
                    )));
                }
            }
            // S5 derived: the uses list follows the document, in this same
            // write (an import brings its reviewed list instead). A list the
            // rules refuse leaves the old one and says why; the document is
            // written all the same.
            let mut uses_refused = None;
            // Instructions place their assembly as one wrapper component: that
            // is what they instruct, not something they are built from, so
            // they publish no uses list (and no occurrences) from it.
            let instructions = state.part(part_id).is_some_and(|p| p.document_class == DocumentClass::Instructions);
            let instructs = if instructions { serde_json::from_str::<Value>(body).ok().and_then(|d| instructs_of(state, &d)) } else { None };
            let derived_uses = if imported_uses.is_some() || instructions {
                None
            } else {
                match serde_json::from_str::<Value>(body).ok().as_ref().and_then(crate::bom_config::document_uses) {
                    None => None,
                    Some(Err(why)) => {
                        uses_refused = Some(why);
                        None
                    }
                    Some(Ok(list)) => match bom::check_uses(state, part_id, &list) {
                        Ok(uses) => Some(uses),
                        Err(error) => {
                            uses_refused = Some(format!("the uses list was not published: {}", error.message));
                            None
                        }
                    },
                }
            };
            let current = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
            let defs = state.bom_configuration.part_fields.get(&current.part_type).cloned().unwrap_or_default();
            let mut canonical = current.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?.clone();
            if let Some(document) = serde_json::from_str::<Value>(body).ok().filter(|_| !instructions) {
                if let Some(occurrences) = crate::bom_config::document_occurrences(&document) {
                    if let Some(occurrences) = crate::bom_config::capture_occurrences(state, part_id, revision_id, &json!({"occurrences":occurrences}))? {
                        canonical.occurrences = occurrences;
                    }
                }
            }
            let normalized = if !defs.is_empty() || !canonical.occurrences.is_empty() {
                let mut document: Value = serde_json::from_str(body).map_err(|_| Error::bad_request("A CAD document must be JSON"))?;
                let original = document.clone();
                if !canonical.attributes_initialized && !defs.is_empty() {
                    for def in &defs {
                        if let Some(value) = document["partAttributes"].as_object().and_then(|attrs|attrs.iter().find(|(key,_)|key.to_ascii_lowercase()==def.key).map(|(_,value)|value)) {
                            if let Some(value) = catalog::check_value(def, value).map_err(Error::bad_request)? {
                                canonical.attributes.insert(def.key.clone(), value);
                            }
                        }
                    }
                    canonical.attributes_initialized = true;
                }
                crate::bom_config::overlay(&canonical, &defs, &mut document);
                if document != original {Some(serde_json::to_string(&document).map_err(Error::internal)?)} else {None}
            } else { None };
            let body = normalized.as_deref().unwrap_or(body);
            let hash = if normalized.is_some() { auth::content_hash(body) } else { hash };
            let size = body.len() as u64;
            let part = state.parts.get_mut(&part_id)
                .ok_or_else(|| Error::not_found("part"))?;
            let number = part.number.clone();
            let revision = part
                .revision_mut(revision_id)
                .ok_or_else(|| Error::not_found("revision"))?;
            if !revision.lifecycle.is_editable() {
                return Err(Error::conflict(format!(
                    "{number} revision {} is {} and cannot be written — start a new revision",
                    revision.label,
                    revision.lifecycle.as_str()
                )));
            }
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).map_err(Error::internal)?;
            }
            let old_thumbnail = revision.thumbnail.as_ref().map(|t| t.sha256.clone());
            let thumbnail = embedded.as_ref().map(|image| {
                let user = import.map(|(user, _, _)| user.id.as_str())
                    .or_else(|| revision.lock.as_ref().map(|lock| lock.user_id.as_str()))
                    .unwrap_or(&revision.created_by);
                image.place(self.root(), &hash, user)
            }).transpose()?;
            revision.attributes = canonical.attributes;
            revision.attributes_initialized = canonical.attributes_initialized;
            revision.occurrences = canonical.occurrences;
            write_atomic(&path, body).map_err(Error::internal)?;
            if let Some(thumbnail) = thumbnail { revision.thumbnail = Some(thumbnail); }
            if let Some(uses) = imported_uses.or(derived_uses) {
                revision.uses = uses;
                crate::bom_config::synchronize_uses(revision);
            }
            if instructions {
                revision.instructs = instructs;
            }
            revision.has_geometry = has_geometry;
            revision.geometry_content_hash = hash.clone();
            revision.content_hash = hash;
            revision.size = size;
            revision.modified_at = now();
            // A document someone SAVED supersedes a bake still waiting: the
            // CAD app evaluated what it saved. A worker that had the job is
            // refused when it reports back (see `Db::finish_bake`).
            if revision.needs_bake() {
                if let Some(bake) = revision.bake.as_mut() {
                    bake.status = crate::model::BakeStatus::Done;
                    bake.error = "superseded by a saved document".into();
                    bake.finished_by = None;
                    bake.finished_at = Some(now());
                }
            }
            // Approvals given on the document before this save go stale (D8).
            crate::review::document_changed(state, part_id, revision_id);
            state.touch(key);
            if embedded.is_some() {
                if let Some(old) = old_thumbnail { crate::attach::remove_if_unreferenced(state, self.root(), &old)?; }
            }
            Ok((state.seq, uses_refused))
        })
    }

    /// Remove a document's bytes. The revision record stays — a revision with
    /// no document is a legitimate state (a part imported with no 3D model).
    pub fn remove_document(&self, key: &str) -> Result<(), Error> {
        let path = self.document_path(key)?;
        match fs::remove_file(path) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(Error::internal(error)),
        }
    }
}

/// The metadata file in a data directory.
pub const SQLITE_FILE: &str = "plm.sqlite";

/// Put every field but the parts back as `before` had it.
/// Whether `session` has ended by the settings' limits at `now`: idle for
/// longer than `session_idle_minutes`, or signed in longer ago than
/// `session_max_hours` (0: no such limit).
pub fn session_expired(settings: &Settings, session: &Session, now: Timestamp) -> bool {
    let idle = now.saturating_sub(session.last_seen) > settings.session_idle_minutes.saturating_mul(60);
    let old = settings.session_max_hours > 0
        && now.saturating_sub(session.created_at) > settings.session_max_hours.saturating_mul(3600);
    idle || old
}

impl Db {
    /// Remove every expired session ([`session_expired`]), as the system;
    /// how many went.
    ///
    /// A session used to be removed only by signing out, or when its cookie
    /// came back after it expired. A browser that simply stops sending the
    /// cookie — it expired there, the user cleared it, a private window
    /// closed — left its session in the store for good, and every sign-in
    /// adds one: the list grew with use and nothing bounded it. This runs at
    /// every sign-in — the only way the list grows — so it holds the sessions
    /// that could still be used, plus whatever expired since the last
    /// sign-in. Not at start-up: opening a store changes nothing in it (an
    /// import or a restore opens exactly what it was given). Nothing is
    /// written when nothing has expired.
    pub fn prune_sessions(&self) -> Result<usize, Error> {
        let at = now();
        let expired = self.read(|state| state.sessions.iter().filter(|s| session_expired(&state.settings, s, at)).count());
        if expired == 0 {
            return Ok(0);
        }
        audit::as_actor(crate::model::Actor::system(), || {
            self.mutate(move |state| {
                let settings = state.settings.clone();
                let before = state.sessions.len();
                state.sessions.retain(|s| !session_expired(&settings, s, at));
                Ok(before - state.sessions.len())
            })
        })
    }
}

/// A journaled list's change as the audit and the store want it: the touched
/// records before and after (only those that changed), and each changed key
/// with what it is now (`None`: removed).
#[allow(clippy::type_complexity)]
fn journal_rows<'a, T>(
    list: &'a crate::journal::Journaled<T>,
    touched: &'a [crate::journal::Touched<T>],
) -> Result<(Vec<Value>, Vec<Value>, Vec<(String, Option<&'a T>)>), Error>
where
    T: crate::journal::Keyed + Clone + PartialEq + Serialize,
{
    let mut old = Vec::new();
    let mut new = Vec::new();
    let mut rows = Vec::new();
    for (t, now) in list.changed(touched) {
        old.extend(t.before.as_ref().map(serde_json::to_value).transpose().map_err(Error::internal)?);
        new.extend(now.map(serde_json::to_value).transpose().map_err(Error::internal)?);
        rows.push((t.key.clone(), now));
    }
    Ok((old, new, rows))
}

fn restore_small(state: &mut State, before: &Value) -> Result<(), Error> {
    let parts = std::mem::take(&mut state.parts);
    let workspace = std::mem::take(&mut state.workspace);
    let sessions = std::mem::take(&mut state.sessions);
    let jobs = std::mem::take(&mut state.jobs);
    *state = serde_json::from_value(before.clone()).map_err(Error::internal)?;
    state.parts = parts;
    state.workspace = workspace;
    state.sessions = sessions;
    state.jobs = jobs;
    Ok(())
}

/// Write `body` to `path` through a temporary file and a rename, so a reader
/// never sees a partial file and a crash never leaves a short one: the
/// temporary sits beside `path` (same file system, so the rename is atomic),
/// is named for this process and write (`<name>.<pid>-<n>.tmp`, so two
/// writers never share one and it never replaces `path`'s extension), is
/// flushed to disk before the rename, and is removed when any step fails.
pub(crate) fn write_atomic(path: &Path, body: impl AsRef<[u8]>) -> io::Result<()> {
    use std::io::Write;
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(0);
    let name = path.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name"))?;
    let mut temp_name = name.to_os_string();
    temp_name.push(format!(".{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
    let temp = path.with_file_name(temp_name);
    let written = (|| {
        let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&temp)?;
        file.write_all(body.as_ref())?;
        file.sync_all()?;
        drop(file);
        fs::rename(&temp, path)
    })();
    if written.is_err() {
        let _ = fs::remove_file(&temp);
    }
    written
}

// ===========================================================================
// Operations — the rules that are about MORE than one record
// ===========================================================================

impl Db {
    /// Create a part of the default shape: the type decides the number, the
    /// document is normal, the first revision takes the suggested label.
    pub fn create_part(
        &self,
        author: &User,
        part_type_id: &str,
        name: &str,
        description: &str,
        category: &str,
    ) -> Result<Part, Error> {
        self.create_part_with(
            author,
            &PartSpec {
                part_type: part_type_id.to_string(),
                name: name.to_string(),
                description: description.to_string(),
                category: category.to_string(),
                ..PartSpec::default()
            },
        )
    }

    /// Create a part with its first draft revision.
    ///
    /// The number comes from the type's [`NumberMode`]. A Script-mode type and
    /// the revision-label hook are asked OUTSIDE the store lock, on a snapshot;
    /// then one [`Db::mutate`] re-checks everything their answers depend on —
    /// that the type's mode did not change meanwhile, and that the number and
    /// label are still free. Two concurrent creates that a script gave the
    /// same number therefore end as one part and one refusal, never two parts.
    /// The part type instructions are numbered in when a request names none:
    /// `instructions` (`MI` and 9 digits), made the first time it is needed.
    /// An admin may rename it or change its numbering like any other type.
    pub fn instructions_part_type(&self) -> Result<String, Error> {
        const ID: &str = "instructions";
        if self.read(|state| state.part_type(ID).is_some()) {
            return Ok(ID.into());
        }
        self.mutate(|state| {
            if state.part_type(ID).is_none() {
                if let Some(clash) = state.part_types.iter().find(|t| t.mode == NumberMode::Counter && t.prefix.eq_ignore_ascii_case("MI")) {
                    return Err(Error::conflict(format!(
                        "part type '{}' already numbers with MI: create a part type for instructions and name it",
                        clash.id
                    )));
                }
                state.part_types.push(PartType {
                    id: ID.into(),
                    name: "Instructions".into(),
                    prefix: "MI".into(),
                    digits: 9,
                    next: 1,
                    created_at: now(),
                    mode: NumberMode::Counter,
                });
            }
            Ok(ID.into())
        })
    }

    pub fn create_part_with(&self, author: &User, spec: &PartSpec) -> Result<Part, Error> {
        check_origin(spec.origin)?;
        let external_ref = spec.external_ref.trim().to_string();
        let origin = spec.origin;
        let name = spec.name.trim().to_string();
        if name.is_empty() {
            return Err(Error::bad_request("a part needs a name"));
        }
        let kind = self
            .read(|state| state.part_type(&spec.part_type).cloned())
            .ok_or_else(|| Error::bad_request(format!("no part type '{}'", spec.part_type)))?;
        let typed = spec.number.trim().to_string();
        let tags = catalog::tidy_tags(spec.tags.iter().cloned());
        let part_view = json!({
            "name": name,
            "description": spec.description.trim(),
            "category": spec.category.trim(),
            "tags": tags,
            "attributes": spec.attributes,
            "document_class": spec.document_class,
        });

        let given: Option<String> = match &kind.mode {
            NumberMode::Counter => {
                if !typed.is_empty() {
                    return Err(Error::bad_request(format!(
                        "part type '{}' numbers by its counter — leave the number empty",
                        kind.id
                    )));
                }
                None
            }
            NumberMode::Free => {
                if typed.is_empty() {
                    return Err(Error::bad_request(format!(
                        "part type '{}' takes the number you type — enter one",
                        kind.id
                    )));
                }
                Some(typed)
            }
            NumberMode::Pattern { regex } => {
                let pattern = full_match(regex)?;
                if typed.is_empty() {
                    return Err(Error::bad_request(format!(
                        "part type '{}' takes a typed number matching {regex} — enter one",
                        kind.id
                    )));
                }
                if !pattern.is_match(&typed) {
                    return Err(Error::bad_request(format!(
                        "'{typed}' does not match part type '{}' ({regex})",
                        kind.id
                    )));
                }
                Some(typed)
            }
            NumberMode::Script { script } => {
                let input = json!({
                    "requested": typed,
                    "partType": kind,
                    "part": part_view,
                    "user": scripting::user_json(author),
                });
                let answer = match scripting::run(self, author, script, "partNumber", &input)? {
                    HookResult::Absent => {
                        return Err(Error::conflict(format!(
                            "part type '{}' numbers by the script '{script}', which is not in the scripts directory",
                            kind.id
                        )))
                    }
                    HookResult::Refused(failure) => {
                        return Err(Error::conflict(format!("{script}: {}", failure.message)))
                    }
                    HookResult::Returned(success) => success.value,
                };
                let number = scripting::string_answer(&answer, "number").ok_or_else(|| {
                    Error::conflict(format!(
                        "{script}: partNumber() must return the number, or {{ number }} — it returned {answer}"
                    ))
                })?;
                if spec.exact && !number.eq_ignore_ascii_case(&typed) {
                    return Err(Error::conflict(format!(
                        "{script} would number it {number}, not {typed} — a family row names its own number"
                    )));
                }
                Some(number)
            }
        };
        if let Some(number) = &given {
            check_number(number)?;
        }

        let requested_label = spec.label.trim().to_string();
        let label = self.decide_label(author, None, &part_view, &requested_label, "A")?;
        if spec.exact {
            exact_label(&requested_label, &label)?;
        }

        let author_id = author.id.clone();
        let document_class = spec.document_class;
        let description = spec.description.trim().to_string();
        let requested_category = spec.category.trim().to_string();
        if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
            return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
        }
        if spec.attributes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
            return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
        }
        let requested_values = spec.attributes.clone();
        let workspace = spec.workspace.clone();
        self.mutate(move |state| {
            // The category and the values are checked HERE, against the tree
            // as it is at the write — an admin may be editing it meanwhile.
            let category = known_category(&state.categories, &requested_category)?;
            let mut attributes = BTreeMap::new();
            catalog::apply_values(&state.categories, &category, &mut attributes, &requested_values)?;
            let current = state
                .part_types
                .iter_mut()
                .find(|t| t.id == kind.id)
                .ok_or_else(|| Error::bad_request(format!("no part type '{}'", kind.id)))?;
            if current.mode != kind.mode {
                return Err(Error::conflict(format!(
                    "part type '{}' changed its numbering while this part was being created — try again",
                    kind.id
                )));
            }
            let (number, sequence) = match given {
                Some(number) => (number, 0),
                None => {
                    // The counter skips numbers another type already gave out:
                    // a free-text or scripted number may land in its range.
                    let mut sequence = current.next;
                    let mut number = current.format_number(sequence);
                    while sequence <= current.capacity()
                        && state_has_number(&state.parts, &number)
                    {
                        sequence += 1;
                        number = current.format_number(sequence);
                    }
                    if sequence > current.capacity() {
                        return Err(Error::conflict(format!(
                            "part type '{}' is exhausted: {} digits cannot spell {}",
                            current.id, current.digits, sequence
                        )));
                    }
                    current.next = sequence + 1;
                    (number, sequence)
                }
            };
            if let Some(owner) = state.part_with_number(&number) {
                return Err(Error::conflict(format!(
                    "part number {number} already exists ({})",
                    owner.name
                )));
            }

            external_ref_clash(state, &kind.id, &external_ref, "")?;
            let stamp = now();
            let mut revision = Revision::draft(label.clone(), label, author_id.clone(), stamp);
            revision.origin = origin;
            let part = Part {
                id: number.clone(),
                number,
                part_type: kind.id.clone(),
                sequence,
                document_class,
                name,
                description,
                category,
                tags,
                external_ref,
                attributes,
                sourcing: Vec::new(),
                member_part_type: String::new(),
                attachments: Vec::new(),
                created_by: author_id,
                created_at: stamp,
                revisions: vec![revision],
            };
            state.parts.push(part.clone());
            state.touch(part.revisions[0].document_key(&part.id));
            if let Some(folder) = &workspace {
                crate::workspace::link_new_part(state, &part.created_by, folder, &part)?;
            }
            Ok(part)
        })
    }

    /// The label a new revision gets: the revision-label hook's answer when
    /// that script exists, else what the user typed, else `suggested`.
    fn decide_label(
        &self,
        user: &User,
        part: Option<&Part>,
        part_view: &Value,
        requested: &str,
        suggested: &str,
    ) -> Result<String, Error> {
        let existing: Vec<&str> = part
            .map(|p| p.revisions.iter().map(|r| r.label.as_str()).collect())
            .unwrap_or_default();
        let input = json!({
            "requested": requested,
            "suggested": suggested,
            "existing": existing,
            "part": part.map(|p| serde_json::to_value(p).unwrap_or(Value::Null)).unwrap_or_else(|| part_view.clone()),
            "user": scripting::user_json(user),
        });
        let label = match scripting::run(self, user, scripting::REVISION_LABEL, "revisionLabel", &input)? {
            HookResult::Absent => {
                if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
            }
            HookResult::Refused(failure) => {
                return Err(Error::conflict(format!("{}: {}", scripting::REVISION_LABEL, failure.message)))
            }
            HookResult::Returned(success) => match &success.value {
                // Returning nothing means "no opinion".
                Value::Null => {
                    if requested.is_empty() { suggested.to_string() } else { requested.to_string() }
                }
                other => scripting::string_answer(other, "label").ok_or_else(|| {
                    Error::conflict(format!(
                        "{}: revisionLabel() must return the label, or {{ label }} — it returned {other}",
                        scripting::REVISION_LABEL
                    ))
                })?,
            },
        };
        check_label(&label)?;
        Ok(label)
    }

    /// Start a new revision of a part, labelled with the suggestion.
    pub fn create_revision(&self, author: &User, part_id: &str) -> Result<Revision, Error> {
        self.create_revision_labelled(author, part_id, "")
    }

    /// Start a new revision of a part.
    ///
    /// While another revision is in work this is refused only when the
    /// administrator has turned [`Settings::allow_multiple_open_drafts`] off;
    /// by default several revisions may be in work at once. The new draft
    /// inherits the document of the revision currently RELEASED — or, when
    /// none is, the newest revision — so revising a part starts from what the
    /// part currently is, never from somebody else's unfinished draft. That
    /// includes an imported part, which is revised rather than forked.
    ///
    /// `label` is free text; empty takes the suggestion. It must not repeat a
    /// label the part already has.
    pub fn create_revision_labelled(
        &self,
        author: &User,
        part_id: &str,
        label: &str,
    ) -> Result<Revision, Error> {
        self.create_revision_as(author, part_id, label, false, crate::model::Origin::Authored)
    }

    /// [`Db::create_revision_labelled`] with the new revision's origin: a
    /// library re-import makes an `imported` one, so the next re-import
    /// still knows the latest revision is its own.
    pub fn create_revision_from(
        &self,
        author: &User,
        part_id: &str,
        label: &str,
        origin: crate::model::Origin,
    ) -> Result<Revision, Error> {
        check_origin(origin)?;
        self.create_revision_as(author, part_id, label, false, origin)
    }

    /// [`Db::create_revision_labelled`]. With `exact`, the revision-label hook
    /// may refuse `label` but not rename it — what a family row needs, since
    /// the row names the revision it writes.
    pub(crate) fn create_revision_as(
        &self,
        author: &User,
        part_id: &str,
        label: &str,
        exact: bool,
        origin: crate::model::Origin,
    ) -> Result<Revision, Error> {
        let part = self
            .read(|state| state.part(part_id).cloned())
            .ok_or_else(|| Error::not_found("part"))?;
        let single = !self.read(|state| state.settings.allow_multiple_open_drafts);
        if let Some(open) = part.open_draft().filter(|_| single) {
            return Err(one_draft_refusal(open, &part));
        }
        let suggested = suggest_label(&part);
        let requested = label.trim();
        let label = self.decide_label(author, Some(&part), &Value::Null, requested, &suggested)?;
        if exact {
            exact_label(requested, &label)?;
        }

        let carried_revision = part.current_release().or(part.latest()).map(|r| r.id.clone());
        let carried = part.current_release().or(part.latest()).map(|r| r.document_key(part_id));
        let carried_body = match carried {
            Some(key) => self.read_document(&key)?,
            None => None,
        };
        let carried_hash = carried_body.as_deref().map(auth::content_hash);

        let author_id = author.id.clone();
        let revision = self.mutate(move |state| {
            // Again inside the lock: the setting, or the part, may have
            // changed since the look above.
            if !state.settings.allow_multiple_open_drafts {
                let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
                if let Some(open) = part.open_draft() {
                    return Err(one_draft_refusal(open, part));
                }
            }
            let part = state.parts.get_mut(&part_id)
                .ok_or_else(|| Error::not_found("part"))?;
            if let Some(clash) = part.revision_by_label(&label) {
                return Err(Error::conflict(format!(
                    "{} already has a revision labelled {}",
                    part.number, clash.label
                )));
            }
            let stamp = now();
            let mut revision = Revision::draft(label.clone(), label, author_id, stamp);
            revision.origin = origin;
            if let Some(previous) = carried_revision.as_deref().and_then(|id| part.revision(id)) {
                revision.has_geometry = previous.has_geometry;
                revision.attributes = previous.attributes.clone();
                revision.attributes_initialized = previous.attributes_initialized;
                revision.occurrences = previous.occurrences.clone();
            }
            // The uses list travels with the document it describes.
            revision.uses = carried_revision
                .as_deref()
                .and_then(|id| part.revision(id))
                .map(|r| r.uses.clone())
                .unwrap_or_default();
            // As does what instructions instruct.
            revision.instructs = carried_revision.as_deref().and_then(|id| part.revision(id)).and_then(|r| r.instructs.clone());
            // So do its files: new references to the same blobs, so removing
            // one from the new revision never touches the old one.
            revision.attachments = carried_revision
                .as_deref()
                .and_then(|id| part.revision(id))
                .map(|r| {
                    r.attachments
                        .iter()
                        .map(|a| crate::model::Attachment { id: auth::new_id(), ..a.clone() })
                        .collect()
                })
                .unwrap_or_default();
            // And its picture, while it still pictures the carried document
            // (the same bytes are written below, so the hash still matches).
            revision.thumbnail = carried_revision
                .as_deref()
                .and_then(|id| part.revision(id))
                .and_then(|r| r.thumbnail.clone())
                .filter(|t| carried_hash.as_deref() == Some(t.content_hash.as_str()));
            part.revisions.push(revision.clone());
            state.touch(revision.document_key(part_id));
            Ok(revision)
        })?;

        if let Some(body) = carried_body {
            self.write_document(part_id, &revision.id, &body)?;
        }
        Ok(revision)
    }

    /// Change a part's descriptive fields — `name`, `description`,
    /// `category`, `tags`, `external_ref` and `attributes`. The number, the
    /// type and the document class are identity and never change here.
    ///
    /// `attributes` MERGES: each key given is set (type-checked against the
    /// part's category, the new one if `category` changes in the same call),
    /// and a `null` clears it. Keys not mentioned are untouched — so moving a
    /// part to another category keeps the values the new schema lacks.
    ///
    /// This is the write behind `PATCH /api/parts/:id` and a script's
    /// `plm.updatePart`.
    pub fn update_part(&self, key: &str, fields: &Value) -> Result<Part, Error> {
        let Some(fields) = fields.as_object() else {
            return Err(Error::bad_request("the fields to change must be an object"));
        };
        for name in fields.keys() {
            if !matches!(
                name.as_str(),
                "name" | "description" | "category" | "tags" | "external_ref" | "attributes" | "member_part_type"
            ) {
                return Err(Error::bad_request(format!(
                    "'{name}' cannot be changed — only name, description, category, tags, attributes, external_ref and member_part_type"
                )));
            }
        }
        let fields = fields.clone();
        let key = key.to_string();
        self.mutate(move |state| {
            let id = state
                .part_by_id_or_number(&key)
                .map(|p| p.id.clone())
                .ok_or_else(|| Error::not_found("part"))?;
            if let Some(value) = fields.get("external_ref") {
                let reference = value.as_str().map(str::trim).unwrap_or_default();
                let kind = state.part(&id).map(|p| p.part_type.clone()).unwrap_or_default();
                external_ref_clash(state, &kind, reference, &id)?;
            }
            // Borrow the parts and the tree separately: the part is written,
            // the tree is only read.
            let State { parts, categories, settings, part_types, .. } = &mut *state;
            let part = parts.get_mut(&id).expect("found above");
            if let Some(value) = fields.get("member_part_type") {
                let requested = value.as_str().map(str::trim).unwrap_or_default();
                if part.document_class == DocumentClass::Normal && !requested.is_empty() {
                    return Err(Error::bad_request(
                        "only a family or a template has a member part type",
                    ));
                }
                if !requested.is_empty() && !part_types.iter().any(|t| t.id == requested) {
                    return Err(Error::bad_request(format!("no part type '{requested}'")));
                }
                part.member_part_type = requested.to_string();
            }
            let before = (part.category.clone(), part.attributes.clone());
            let updated = apply_part_fields(categories, part, &fields)?;

            // Judged on what CHANGED, not on which fields were sent: the edit
            // dialog re-sends every field, and renaming a released part must
            // not trip a lock on values it left alone.
            if settings.lock_released_attributes
                && part.catalog_frozen()
                && before != (updated.category.clone(), updated.attributes.clone())
            {
                return Err(Error::conflict(format!(
                    "{} is released and its category and attributes are locked — start a new revision to change them",
                    part.number
                )));
            }
            Ok(updated)
        })
    }
}

/// A family row and a template spin-out name their number and revision
/// themselves: the revision-label hook may refuse the label, but a hook that
/// RENAMES it would leave the table naming a revision that does not exist.
fn exact_label(requested: &str, decided: &str) -> Result<(), Error> {
    if !requested.is_empty() && !decided.eq_ignore_ascii_case(requested) {
        return Err(Error::conflict(format!(
            "{} would label it {decided}, not {requested} — a family row names its own revision",
            scripting::REVISION_LABEL
        )));
    }
    Ok(())
}

/// A document still waiting for its bake cannot release: once released its
/// bytes are frozen, and the bake could never be written.
fn bake_gate(revision: &Revision) -> Result<(), Error> {
    match &revision.bake {
        Some(bake) if revision.needs_bake() => Err(Error::conflict(format!(
            "revision {} is waiting for a bake ({}{}) — it releases once a CAD worker has baked it, or once someone saves it from the CAD app",
            revision.label,
            bake.status.as_str(),
            if bake.error.is_empty() { String::new() } else { format!(": {}", bake.error) }
        ))),
        _ => Ok(()),
    }
}

/// The refusal [`Settings::allow_multiple_open_drafts`] = off gives.
fn one_draft_refusal(open: &Revision, part: &Part) -> Error {
    Error::conflict(format!(
        "revision {} of {} is still open — release or delete it first (this server allows one revision in work at a time)",
        open.label, part.number
    ))
}

impl Db {
    /// The administrator's settings as they stand.
    pub fn settings(&self) -> Settings {
        self.read(|state| state.settings.clone())
    }

    /// Change settings. `fields` MERGES: each key given is set, the rest are
    /// untouched. An unknown key or a value of the wrong type is refused
    /// rather than ignored, so a typo in an admin's request cannot silently
    /// leave a policy where it was.
    pub fn update_settings(&self, fields: &Value) -> Result<Settings, Error> {
        let Some(fields) = fields.as_object() else {
            return Err(Error::bad_request("the settings to change must be an object"));
        };
        let mut merged = serde_json::to_value(self.settings()).map_err(Error::internal)?;
        for (key, value) in fields {
            let slot = merged
                .get_mut(key)
                .ok_or_else(|| Error::bad_request(format!("there is no setting '{key}'")))?;
            if slot.is_boolean() && !value.is_boolean() {
                return Err(Error::bad_request(format!("'{key}' must be true or false")));
            }
            if slot.is_u64() {
                let minimum = if key == "session_idle_minutes" { 5 } else { 0 };
                match value.as_u64() {
                    Some(n) if n >= minimum => {}
                    _ => {
                        return Err(Error::bad_request(format!(
                            "'{key}' must be a whole number of at least {minimum}"
                        )))
                    }
                }
            }
            *slot = value.clone();
        }
        self.read(|state| crate::review::normalize_settings_json(state, &mut merged))?;
        let settings: Settings = serde_json::from_value(merged)
            .map_err(|e| Error::bad_request(format!("those settings do not read: {e}")))?;
        self.mutate(move |state| {
            // The review rules name users, groups, part types and categories:
            // checked against the store as it is at the write.
            let mut settings = settings;
            crate::review::check_settings(state, &mut settings)?;
            crate::lifecycle::check_options(&settings.status_options)?;
            state.settings = settings.clone();
            Ok(settings)
        })
    }
}

/// The body of [`Db::update_part`], inside its lock. `categories` is the tree
/// as it is at the write.
fn apply_part_fields(
    categories: &[Category],
    part: &mut Part,
    fields: &serde_json::Map<String, Value>,
) -> Result<Part, Error> {
    let text = |value: &Value| value.as_str().map(|s| s.trim().to_string());
    if let Some(value) = fields.get("name") {
        let name = text(value)
            .filter(|n| !n.is_empty())
            .ok_or_else(|| Error::bad_request("a part needs a name"))?;
        part.name = name;
    }
    if let Some(value) = fields.get("description") {
        part.description = text(value).unwrap_or_default();
    }
    if let Some(value) = fields.get("category") {
        let requested = text(value).unwrap_or_default();
        part.category = known_category(categories, &requested)?;
    }
    if let Some(value) = fields.get("external_ref") {
        part.external_ref = text(value).unwrap_or_default();
    }
    if let Some(value) = fields.get("tags") {
        part.tags = catalog::tidy_tags(
            value
                .as_array()
                .ok_or_else(|| Error::bad_request("tags must be a list of strings"))?
                .iter()
                .filter_map(|t| t.as_str().map(str::to_string)),
        );
    }
    // After the category, so a move and the new category's values can land in
    // one call.
    if let Some(value) = fields.get("attributes") {
        let changes = value
            .as_object()
            .ok_or_else(|| Error::bad_request("attributes must be an object of key: value"))?;
        if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_geometry")) {
            return Err(Error::bad_request("has_geometry is derived from the saved model and cannot be edited"));
        }
        if changes.keys().any(|key| key.trim().eq_ignore_ascii_case("has_thumbnail")) {
            return Err(Error::bad_request("has_thumbnail is derived from current thumbnails and cannot be edited"));
        }
        catalog::apply_values(categories, &part.category, &mut part.attributes, changes)?;
    }
    Ok(part.clone())
}

/// The category id to store for `requested`: empty for none, else the id of
/// an existing category (the text may differ in case). A category that does
/// not exist is refused rather than stored as free text, so a typo cannot
/// quietly file a part nowhere.
fn known_category(categories: &[Category], requested: &str) -> Result<String, Error> {
    let requested = requested.trim();
    if requested.is_empty() {
        return Ok(String::new());
    }
    catalog::find(categories, requested)
        .map(|c| c.id.clone())
        .ok_or_else(|| Error::bad_request(format!("there is no category '{requested}'")))
}

/// What a parts listing is narrowed to. Every field is optional; empty means
/// "no constraint".
#[derive(Debug, Clone, Default)]
pub struct PartFilter {
    /// Text matched against the number, name, description, category name,
    /// tags, attribute values, and every MPN and SPN.
    pub q: String,
    /// A category id: the parts in it AND in every category beneath it.
    /// [`UNCATEGORIZED`] selects the parts without a category.
    pub category: String,
    /// A tag, matched whole and without regard to case.
    pub tag: String,
    /// A manufacturer, by id or name: the parts with a manufacturer part
    /// from it.
    pub manufacturer: String,
    /// A supplier, by id or name: the parts with an offer from it.
    pub supplier: String,
    /// Catalog attribute conditions, all of which a part must meet
    /// ([`AttributeFilter`]).
    pub attributes: Vec<AttributeFilter>,
    /// An external reference, matched exactly (a library import's lookup).
    pub external_ref: String,
    /// A part type id, matched exactly.
    pub part_type: String,
}

/// One attribute condition of a parts listing (`attr.<key>=…`,
/// `attr.<key>.min=…`, `attr.<key>.max=…`), as the caller typed it. It is
/// read against the attribute's type in the catalog ([`attribute_matchers`]).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct AttributeFilter {
    pub key: String,
    /// The part's value must equal one of these (any of); empty: any value.
    pub values: Vec<String>,
    /// Inclusive bounds, for a number attribute.
    pub min: Option<String>,
    pub max: Option<String>,
}

impl AttributeFilter {
    /// The conditions in a query string's `attr.*` pairs, merged per key in
    /// the order they first appear. Anything after `attr.<key>` other than
    /// `.min` or `.max` is refused. Other pairs are ignored.
    pub fn from_query(pairs: &[(String, String)]) -> Result<Vec<AttributeFilter>, Error> {
        let mut out: Vec<AttributeFilter> = Vec::new();
        for (name, value) in pairs {
            let Some(rest) = name.strip_prefix("attr.") else { continue };
            let (key, bound) = match rest.rsplit_once('.') {
                Some((key, "min")) => (key, Some(true)),
                Some((key, "max")) => (key, Some(false)),
                Some((_, other)) if !rest.is_empty() => {
                    // An attribute key has no dots (catalog::usable_key), so
                    // anything after one is a suffix, and only two exist.
                    return Err(Error::bad_request(format!(
                        "'{name}': an attribute filter is attr.<key>, attr.<key>.min or attr.<key>.max, not .{other}"
                    )));
                }
                _ => (rest, None),
            };
            let key = key.trim();
            if key.is_empty() {
                return Err(Error::bad_request(format!("'{name}' names no attribute")));
            }
            let at = match out.iter().position(|f| f.key == key) {
                Some(i) => i,
                None => {
                    out.push(AttributeFilter { key: key.to_string(), ..AttributeFilter::default() });
                    out.len() - 1
                }
            };
            let filter = &mut out[at];
            match bound {
                None => filter.values.push(value.clone()),
                Some(true) => filter.min = Some(value.clone()),
                Some(false) => filter.max = Some(value.clone()),
            }
        }
        Ok(out)
    }
}

/// An [`AttributeFilter`] read against the catalog: its type, its values in
/// the canonical form they are stored in, its bounds as numbers.
#[derive(Debug, Clone)]
pub struct AttributeMatcher {
    key: String,
    any_of: Vec<Value>,
    min: Option<f64>,
    max: Option<f64>,
}

impl AttributeMatcher {
    fn matches(&self, part: &Part) -> bool {
        let geometry = Value::Bool(part.latest().is_some_and(|r| r.has_geometry));
        let thumbnail = Value::Bool(crate::thumbnail::of_part(part).is_some());
        let have = if self.key == "has_geometry" { &geometry } else if self.key == "has_thumbnail" { &thumbnail } else {
            let Some(value) = part.attributes.get(&self.key).filter(|v| !v.is_null()) else { return false };
            value
        };
        let number = have.as_f64();
        let equal = |want: &Value| match (want, have) {
            (Value::Number(w), Value::Number(h)) => w.as_f64() == h.as_f64(),
            (Value::String(w), Value::String(h)) => w.eq_ignore_ascii_case(h.trim()),
            (w, h) => w == h,
        };
        (self.any_of.is_empty() || self.any_of.iter().any(equal))
            && self.min.is_none_or(|min| number.is_some_and(|n| n >= min))
            && self.max.is_none_or(|max| number.is_some_and(|n| n <= max))
    }
}

/// Read `filter`'s attribute conditions against the catalog, or say why they
/// cannot be read (a `400`).
///
/// With a `category` the key must be in that category's effective schema.
/// Without one it must be defined by some category, and every category that
/// defines it must agree on its type — else the caller is told to narrow by
/// category. A value is read as the catalog reads form text
/// ([`catalog::check_value`]), so `12.5`, `yes` and an enum value in any case
/// all work; `min` and `max` are for numbers only.
pub fn attribute_matchers(state: &State, filter: &PartFilter) -> Result<Vec<AttributeMatcher>, Error> {
    use crate::model::{AttributeDef, AttributeKind};
    let category = catalog::find(&state.categories, filter.category.trim()).map(|c| c.id.clone());
    let mut out = Vec::new();
    for condition in &filter.attributes {
        let key = condition.key.as_str();
        if matches!(key, "has_geometry" | "has_thumbnail") {
            if condition.min.is_some() || condition.max.is_some() {
                return Err(Error::bad_request(format!("{key} is a boolean and has no range")));
            }
            let any_of = condition.values.iter().map(|v| match v.as_str() {
                "true" => Ok(Value::Bool(true)), "false" => Ok(Value::Bool(false)),
                _ => Err(Error::bad_request(format!("attr.{key} must be true or false"))),
            }).collect::<Result<Vec<_>, _>>()?;
            out.push(AttributeMatcher { key: key.into(), any_of, min: None, max: None });
            continue;
        }
        let defs: Vec<(String, AttributeDef)> = match &category {
            Some(id) => catalog::schema(&state.categories, id)?
                .into_iter()
                .filter(|e| e.def.key == key)
                .map(|e| (id.clone(), e.def))
                .collect(),
            None => state
                .categories
                .iter()
                .flat_map(|c| c.attributes.iter().filter(|d| d.key == key).map(move |d| (c.id.clone(), d.clone())))
                .collect(),
        };
        let Some((first_category, def)) = defs.first().cloned() else {
            return Err(Error::bad_request(match &category {
                Some(id) => format!("the category '{id}' has no attribute '{key}'"),
                None => format!("no category has an attribute '{key}'"),
            }));
        };
        if let Some((other, clash)) = defs.iter().find(|(_, d)| d.kind.as_str() != def.kind.as_str()) {
            return Err(Error::bad_request(format!(
                "'{key}' is a {} in '{first_category}' but a {} in '{other}' — give a category to filter by it",
                def.kind.as_str(),
                clash.kind.as_str()
            )));
        }
        let mut any_of = Vec::new();
        for raw in &condition.values {
            // An enum's values may differ between the categories that define
            // the key: a value any of them lists is accepted.
            let read = defs.iter().map(|(_, d)| catalog::check_value(d, &Value::String(raw.clone())));
            let mut first_error = None;
            let mut value = None;
            for result in read {
                match result {
                    Ok(v) => {
                        value = v;
                        first_error = None;
                        break;
                    }
                    Err(e) => {
                        first_error.get_or_insert(e);
                    }
                }
            }
            if let Some(error) = first_error {
                return Err(Error::bad_request(format!("attr.{key}: {error}")));
            }
            let Some(value) = value else {
                return Err(Error::bad_request(format!("attr.{key} is empty — leave it out to filter on nothing")));
            };
            any_of.push(value);
        }
        let bound = |raw: &Option<String>, which: &str| -> Result<Option<f64>, Error> {
            let Some(raw) = raw else { return Ok(None) };
            if !matches!(def.kind, AttributeKind::Number { .. }) {
                return Err(Error::bad_request(format!(
                    "attr.{key}.{which}: '{key}' is a {}, and only a number has a range",
                    def.kind.as_str()
                )));
            }
            raw.trim()
                .parse::<f64>()
                .ok()
                .filter(|n| n.is_finite())
                .map(Some)
                .ok_or_else(|| Error::bad_request(format!("attr.{key}.{which} must be a number, not '{raw}'")))
        };
        out.push(AttributeMatcher {
            key: key.to_string(),
            any_of,
            min: bound(&condition.min, "min")?,
            max: bound(&condition.max, "max")?,
        });
    }
    Ok(out)
}

/// One page of a parts listing ([`Db::find_parts_page`]).
#[derive(Debug, Default)]
pub struct PartPage {
    pub parts: Vec<Part>,
    /// The cursor for the next page, or `None` when this is the last.
    pub next: Option<String>,
    cursors: Vec<i64>,
}

impl PartPage {
    /// Trim a page collected one past `limit`, and set its cursor.
    fn finish(&mut self, limit: Option<usize>) {
        if let Some(limit) = limit {
            if self.parts.len() > limit {
                self.parts.truncate(limit);
                self.next = self.cursors.get(limit - 1).map(|c| c.to_string());
            }
        }
        self.cursors.clear();
    }
}

/// A [`PartFilter`] resolved against the store: the exact rules a part must
/// pass, whichever way the candidates were found.
struct Matcher {
    needle: String,
    tag: String,
    /// The category ids (lower-case) a part must be in; `Some(empty)` with
    /// `uncategorized` for "without a category".
    within: Option<BTreeSet<String>>,
    uncategorized: bool,
    /// `Some(None)`: the filter names a company that does not exist, which
    /// matches nothing rather than silently widening to everything.
    manufacturer: Option<Option<String>>,
    supplier: Option<Option<String>>,
    external_ref: String,
    part_type: String,
    /// The attribute conditions, read; `None` when they could not be read,
    /// which matches nothing (the route refuses such a filter with a 400
    /// before it gets here).
    attributes: Option<Vec<AttributeMatcher>>,
}

impl Matcher {
    fn new(state: &State, filter: &PartFilter) -> Self {
        let within = match filter.category.trim() {
            "" => None,
            UNCATEGORIZED => Some(BTreeSet::new()),
            id => Some(catalog::descendants(&state.categories, id)),
        };
        let company = |which: sourcing::Companies, key: &str| -> Option<Option<String>> {
            let key = key.trim();
            if key.is_empty() {
                return None;
            }
            Some(sourcing::find_company(which.list(state), key).map(|c| c.id.clone()))
        };
        Matcher {
            needle: filter.q.trim().to_ascii_lowercase(),
            tag: filter.tag.trim().to_string(),
            within,
            uncategorized: filter.category.trim() == UNCATEGORIZED,
            manufacturer: company(sourcing::Companies::Manufacturers, &filter.manufacturer),
            supplier: company(sourcing::Companies::Suppliers, &filter.supplier),
            attributes: attribute_matchers(state, filter).ok(),
            external_ref: filter.external_ref.trim().to_string(),
            part_type: filter.part_type.trim().to_string(),
        }
    }

    /// A filter no part can pass: it names a company that does not exist,
    /// or attribute conditions that do not read.
    fn impossible(&self) -> bool {
        matches!(self.manufacturer, Some(None)) || matches!(self.supplier, Some(None)) || self.attributes.is_none()
    }

    fn matches(&self, categories: &[Category], part: &Part) -> bool {
        (match &self.within {
            None => true,
            Some(_) if self.uncategorized => part.category.is_empty(),
            Some(ids) => ids.contains(&part.category.to_ascii_lowercase()),
        }) && (self.tag.is_empty() || part.tags.iter().any(|t| t.eq_ignore_ascii_case(&self.tag)))
            && (match &self.manufacturer {
                None => true,
                Some(None) => false,
                Some(Some(id)) => part.sourcing.iter().any(|mp| &mp.manufacturer == id),
            })
            && (match &self.supplier {
                None => true,
                Some(None) => false,
                Some(Some(id)) => part.sourcing.iter().flat_map(|mp| &mp.offers).any(|o| &o.supplier == id),
            })
            && (self.external_ref.is_empty() || part.external_ref == self.external_ref)
            && (self.part_type.is_empty() || part.part_type == self.part_type)
            && self.attributes.as_ref().is_some_and(|all| all.iter().all(|a| a.matches(part)))
            && (self.needle.is_empty() || part_matches(categories, part, &self.needle))
    }
}

/// The `category` filter value that selects parts without a category —
/// an empty category.
pub const UNCATEGORIZED: &str = "_none";

impl Db {
    /// Search parts by number, name, category or tag — what a script's
    /// `plm.findParts` asks.
    pub fn search_parts(&self, query: &str) -> Vec<Part> {
        self.find_parts(&PartFilter { q: query.to_string(), ..PartFilter::default() })
    }

    /// The parts that pass `filter`, in creation order.
    pub fn find_parts(&self, filter: &PartFilter) -> Vec<Part> {
        self.find_parts_page(filter, None, None).parts
    }

    /// One page of the parts that pass `filter`, in creation order: at most
    /// `limit`, continuing after the cursor `after` (a [`PartPage::next`]).
    ///
    /// The SQLite side narrows ([`crate::sql::Sql::candidates`]): the trigram
    /// index finds the parts whose searchable text contains the search text,
    /// and indexed columns apply the category, tag and company filters. Every
    /// candidate is then checked against the in-memory part with the exact
    /// rules below, so the answer is the one the rules give — the index only
    /// decides how few parts are looked at. Search text shorter than three
    /// characters (the trigram minimum) narrows nothing and is checked on
    /// every part the other filters leave. Should the index fail, the answer
    /// comes from a scan of memory rather than an error.
    pub fn find_parts_page(&self, filter: &PartFilter, after: Option<&str>, limit: Option<usize>) -> PartPage {
        let matcher = self.read(|state| Matcher::new(state, filter));
        let after: Option<i64> = after.and_then(|a| a.trim().parse().ok());
        let limit = limit.map(|l| l.max(1));
        if matcher.impossible() {
            return PartPage::default();
        }
        // An exact external reference picks one part, or a handful: a walk of
        // memory finds it without paging through the index 256 rows at a time.
        if !matcher.external_ref.is_empty() {
            return self.scanned_page(&matcher, after, limit);
        }
        match self.indexed_page(&matcher, after, limit) {
            Ok(page) => page,
            Err(error) => {
                eprintln!("brep-plm: search index: {error}; answering from a scan");
                self.scanned_page(&matcher, after, limit)
            }
        }
    }

    fn indexed_page(&self, matcher: &Matcher, mut after: Option<i64>, limit: Option<usize>) -> rusqlite::Result<PartPage> {
        let categories: Option<Vec<String>> = match (&matcher.within, matcher.uncategorized) {
            (Some(ids), false) => Some(ids.iter().cloned().collect()),
            _ => None,
        };
        let needle = (matcher.needle.chars().count() >= 3).then_some(matcher.needle.as_str());
        let mut page = PartPage::default();
        // One more than the page, to know whether there IS a next page.
        let wanted = limit.map(|l| l + 1);
        let batch = wanted.map(|w| w.max(256));
        loop {
            let rows = self.sql.candidates(&sql::Candidates {
                needle,
                categories: categories.as_deref(),
                uncategorized: matcher.uncategorized,
                tag: (!matcher.tag.is_empty()).then_some(matcher.tag.as_str()),
                manufacturer: matcher.manufacturer.as_ref().and_then(|m| m.as_deref()),
                supplier: matcher.supplier.as_ref().and_then(|s| s.as_deref()),
                after,
                limit: batch,
            })?;
            let exhausted = batch.is_none_or(|b| rows.len() < b);
            let full = self.read(|state| {
                for (ord, id) in &rows {
                    after = Some(*ord);
                    let Some(part) = state.parts.get(id) else { continue };
                    if matcher.matches(&state.categories, part) {
                        page.parts.push(part.clone());
                        page.cursors.push(*ord);
                        if wanted.is_some_and(|w| page.parts.len() >= w) {
                            return true;
                        }
                    }
                }
                false
            });
            if full || exhausted {
                break;
            }
        }
        page.finish(limit);
        Ok(page)
    }

    fn scanned_page(&self, matcher: &Matcher, after: Option<i64>, limit: Option<usize>) -> PartPage {
        let mut page = PartPage::default();
        self.read(|state| {
            for (ord, part) in state.parts.iter().enumerate() {
                let ord = ord as i64;
                if after.is_some_and(|a| ord <= a) || !matcher.matches(&state.categories, part) {
                    continue;
                }
                page.parts.push(part.clone());
                page.cursors.push(ord);
                if limit.is_some_and(|l| page.parts.len() > l) {
                    break;
                }
            }
        });
        page.finish(limit);
        page
    }

    /// [`Db::find_parts`] by a scan of memory alone, with no index — what the
    /// index's answers are checked against.
    pub fn find_parts_scanning(&self, filter: &PartFilter) -> Vec<Part> {
        let matcher = self.read(|state| Matcher::new(state, filter));
        if matcher.impossible() {
            return Vec::new();
        }
        self.scanned_page(&matcher, None, None).parts
    }

    /// Take the lock on a draft revision.
    pub fn checkout(
        &self,
        user: &User,
        part_id: &str,
        revision_id: &str,
        client_id: &str,
    ) -> Result<(), Error> {
        let user_id = user.id.clone();
        let client_id = client_id.to_string();
        self.mutate(move |state| {
            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
            if !revision.lifecycle.is_editable() {
                return Err(Error::conflict(format!(
                    "revision {} is {} — only a draft can be checked out",
                    revision.label,
                    revision.lifecycle.as_str()
                )));
            }
            if let Some(lock) = &revision.lock {
                if lock.user_id != user_id {
                    return Err(Error::conflict(
                        "already checked out by another user".to_string(),
                    ));
                }
                // The same user re-taking their own lock from another client
                // is a no-op that re-stamps which client holds it.
            }
            revision.lock = Some(Lock {
                user_id,
                client_id,
                acquired_at: now(),
            });
            state.touch_part(part_id);
            Ok(())
        })
    }

    /// Release the lock. `force` is the BREAK path and requires the check-in
    /// group; without it only the holder may check in.
    pub fn checkin(
        &self,
        user: &User,
        part_id: &str,
        revision_id: &str,
        force: bool,
    ) -> Result<(), Error> {
        let user_id = user.id.clone();
        let may_break = user.can_checkin();
        self.mutate(move |state| {
            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
            let Some(lock) = revision.lock.clone() else {
                return Err(Error::conflict("nothing is checked out".to_string()));
            };
            if lock.user_id != user_id {
                if !force {
                    return Err(Error::forbidden(
                        "another user holds this lock — breaking it needs the check-in group",
                    ));
                }
                if !may_break {
                    return Err(Error::forbidden(
                        "breaking another user's lock needs the check-in group",
                    ));
                }
            }
            revision.lock = None;
            state.touch_part(part_id);
            Ok(())
        })
    }

    /// Move a revision's lifecycle state, applying the rules in
    /// [`crate::lifecycle`] and the automatic supersede.
    ///
    /// A release runs two hooks when their files exist. `beforeRelease` runs
    /// first, outside the store lock, and a throw refuses the release; the
    /// locked write then re-checks that the revision's bytes are the ones the
    /// hook saw. `afterRelease` runs once the release is committed: it cannot
    /// undo it, so its failure comes back as a WARNING, the release standing.
    pub fn transition(
        &self,
        user: &User,
        part_id: &str,
        revision_id: &str,
        to: Lifecycle,
    ) -> Result<Vec<String>, Error> {
        self.transition_checked(user, part_id, revision_id, to, None, None)
    }

    pub fn transition_reviewed(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: &str) -> Result<Vec<String>, Error> {
        self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), None)
    }

    pub(crate) fn transition_workflow(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: &str, run_id: &str) -> Result<Vec<String>, Error> {
        self.transition_checked(user, part_id, revision_id, to, Some(expected_hash), Some(run_id))
    }

    fn transition_checked(&self, user: &User, part_id: &str, revision_id: &str, to: Lifecycle, expected_hash: Option<&str>, workflow_run: Option<&str>) -> Result<Vec<String>, Error> {
        if let Some(expected) = expected_hash {
            let (_, revision) = self.snapshot(part_id, revision_id)?;
            if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
        }
        lifecycle::check_enabled(&self.settings(), to)?;
        if to == Lifecycle::Released { self.read(|s|crate::workflow::release_gate(s,part_id,revision_id,workflow_run))?; }
        if to == Lifecycle::Superseded {
            return Err(Error::bad_request(
                "superseded is applied automatically when a newer revision releases",
            ));
        }
        if to == Lifecycle::Released && !user.can_checkin() {
            return Err(Error::forbidden("releasing needs the check-in group"));
        }
        // Retiring a released revision from every new use is the release
        // authority's decision too.
        if to == Lifecycle::Obsolete && !user.can_checkin() {
            return Err(Error::forbidden("making a revision obsolete needs the check-in group"));
        }
        // Submitting for review and pulling back from it are an author's work.
        if matches!(to, Lifecycle::InReview | Lifecycle::Draft) && !user.can_author() {
            return Err(Error::forbidden("submitting for review, or withdrawing, needs the author group"));
        }
        // Submitting opens a review round ([`crate::review`]).
        if to == Lifecycle::InReview {
            return self.submit_for_review(user, part_id, revision_id, &crate::review::Submission::default());
        }

        // The before-release gate, on a snapshot. Refusals the locked write
        // would make anyway are made first, so a script is never asked about
        // a release that cannot happen.
        let mut seen_hash = None;
        if to == Lifecycle::Released {
            let (part, revision) = self.snapshot(part_id, revision_id)?;
            lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
            self.read(|state| catalog_gate(&state.categories, &part))?;
            self.read(|state| children_gate(state, &part, &revision))?;
            self.read(|state| review_gate(state, &part, &revision))?;
            if revision.lock.is_some() {
                return Err(Error::conflict(format!(
                    "revision {} is checked out — check it in before releasing",
                    revision.label
                )));
            }
            bake_gate(&revision)?;
            let input = self.read(|state| release_input(state, &part, &revision, user));
            match scripting::run(self, user, scripting::BEFORE_RELEASE, "beforeRelease", &input)? {
                HookResult::Absent | HookResult::Returned(_) => {}
                HookResult::Refused(failure) => {
                    return Err(Error::conflict(format!(
                        "{} refused the release: {}",
                        scripting::BEFORE_RELEASE,
                        failure.message
                    )))
                }
            }
            seen_hash = Some(revision.content_hash.clone());
        }

        // Who uses the revision as it stands, for the warning an obsolete
        // revision answers with (it is still used; nothing refuses).
        let users = if to == Lifecycle::Obsolete {
            self.read(|state| used_by_now(state, part_id, revision_id))
        } else {
            Vec::new()
        };
        let user_id = user.id.clone();
        let root = self.root().to_path_buf();
        self.mutate(move |state| {
            lifecycle::check_enabled(&state.settings, to)?;
            if to == Lifecycle::Released { crate::workflow::release_gate(state,part_id,revision_id,workflow_run)?; }
            if let Some(expected) = expected_hash {
                let revision = state.part(part_id).and_then(|p|p.revision(revision_id)).ok_or_else(||Error::not_found("revision"))?;
                if revision.content_hash != expected { return Err(Error::conflict("workflow model changed after review")); }
            }
            if to == Lifecycle::Released {
                // Again INSIDE the lock: the part's values or its category's
                // schema may have changed while the hook ran.
                let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
                catalog_gate(&state.categories, part)?;
                let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
                let field_problems = crate::bom_config::release_problems(state, part, revision);
                if !field_problems.is_empty() { return Err(Error::conflict(field_problems.join("; "))); }
                children_gate(state, part, revision)?;
                instructions_gate(state, &root, part, revision)?;
                review_gate(state, part, revision)?;
            }
            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
            lifecycle::check_transition(revision.lifecycle, to).map_err(Error::conflict)?;
            // Pulling a revision out of review ends its round.
            if revision.lifecycle == Lifecycle::InReview && to == Lifecycle::Draft {
                if let Some(review) = revision.live_review_mut() {
                    crate::review::withdraw(review, &user_id, now());
                }
            }
            if let Some(hash) = &seen_hash {
                if *hash != revision.content_hash {
                    return Err(Error::conflict(format!(
                        "revision {} changed while {} was checking it — release it again",
                        revision.label,
                        scripting::BEFORE_RELEASE
                    )));
                }
            }
            if to == Lifecycle::Released {
                bake_gate(revision)?;
                if let Some(lock) = &revision.lock {
                    return Err(Error::conflict(format!(
                        "revision {} is checked out (held since {}) — check it in before releasing",
                        revision.label, lock.acquired_at
                    )));
                }
                crate::review::close_on_release(revision, &user_id, now());
                revision.released_by = Some(user_id);
                revision.released_at = Some(now());
                revision.lock = None;
            }
            revision.lifecycle = to;
            let released_id = revision.id.clone();

            // The automatic supersede: every OTHER released revision of this
            // part steps down. Applied here so no caller can release without
            // it.
            if to == Lifecycle::Released {
                let part = state.parts.get_mut(&part_id)
                    .ok_or_else(|| Error::not_found("part"))?;
                for other in part.revisions.iter_mut() {
                    if other.id != released_id && other.lifecycle == Lifecycle::Released {
                        other.lifecycle = Lifecycle::Superseded;
                    }
                }
            }
            state.touch_part(&part_id);
            Ok(())
        })?;

        let mut warnings = Vec::new();
        if to == Lifecycle::Draft {
            warnings.extend(self.review_withdrawn(user, part_id, revision_id));
        }
        if !users.is_empty() {
            warnings.push(format!(
                "obsolete, but still used by {}: their BOMs flag it until they are revised to use another revision",
                named_list(&users)
            ));
        }
        if to == Lifecycle::Released {
            let (part, revision) = self.snapshot(part_id, revision_id)?;
            // With the gate off the release stands, and says what it did not
            // wait for.
            let unreleased = self.read(|state| bom::unreleased_children(state, &revision));
            if !unreleased.is_empty() {
                warnings.push(format!("released, but it uses unreleased parts: {}", unreleased.join("; ")));
            }
            let input = self.read(|state| release_input(state, &part, &revision, user));
            match scripting::run(self, user, scripting::AFTER_RELEASE, "afterRelease", &input) {
                Ok(HookResult::Absent) | Ok(HookResult::Returned(_)) => {}
                Ok(HookResult::Refused(failure)) => warnings.push(format!(
                    "released, but {} failed: {}",
                    scripting::AFTER_RELEASE,
                    failure.message
                )),
                Err(error) => warnings.push(format!(
                    "released, but {} could not run: {}",
                    scripting::AFTER_RELEASE,
                    error.message
                )),
            }
        }
        Ok(warnings)
    }

    /// A copy of one part and one of its revisions, for a hook to read.
    pub(crate) fn snapshot(&self, part_id: &str, revision_id: &str) -> Result<(Part, Revision), Error> {
        self.read(|state| {
            let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
            let revision = part
                .revision(revision_id)
                .ok_or_else(|| Error::not_found("revision"))?;
            Ok((part.clone(), revision.clone()))
        })
    }

    /// Delete a draft revision outright — the only removal this server allows.
    /// A released revision is never deleted; it is obsoleted.
    pub fn delete_draft(&self, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
        let user_id = user.id.clone();
        let may_break = user.can_checkin();
        let key = crate::identity::document_key(part_id, revision_id);
        let root = self.root().to_path_buf();
        self.mutate(|state| {
            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
            if !revision.lifecycle.is_editable() {
                return Err(Error::conflict(
                    "only a draft can be deleted — release history is permanent".to_string(),
                ));
            }
            if let Some(lock) = &revision.lock {
                if lock.user_id != user_id && !may_break {
                    return Err(Error::forbidden(
                        "another user has this draft checked out",
                    ));
                }
            }
            let part = state.parts.get_mut(&part_id)
                .ok_or_else(|| Error::not_found("part"))?;
            if part.revisions.len() == 1 {
                return Err(Error::conflict(
                    "a part keeps at least one revision".to_string(),
                ));
            }
            // A revision another list pins cannot go: that list would name
            // nothing.
            let pinners = pinned_by(state, part_id, revision_id);
            if !pinners.is_empty() {
                let lists = if pinners.len() == 1 { "that list" } else { "those lists" };
                return Err(Error::conflict(format!(
                    "this revision is used by {} — remove it from {lists} first",
                    named_list(&pinners)
                )));
            }
            let part = state.parts.get_mut(&part_id)
                .ok_or_else(|| Error::not_found("part"))?;
            let thumbnail = part.revision(revision_id).and_then(|r| r.thumbnail.as_ref()).map(|t| t.sha256.clone());
            part.revisions.retain(|r| r.id != revision_id);
            if let Some(sha) = thumbnail {
                crate::attach::remove_if_unreferenced(state, &root, &sha)?;
            }
            state.touch(key.clone());
            Ok(())
        })?;
        self.remove_document(&key)
    }

    /// The keys that changed since `since`, and whether the log still reaches
    /// that far back.
    pub fn changes_since(&self, since: u64) -> (u64, bool, Vec<String>) {
        self.read(|state| {
            let stale = since < state.changes_floor();
            let keys: Vec<String> = state
                .changes
                .iter()
                .filter(|c| c.seq > since)
                .map(|c| c.key.clone())
                .collect::<BTreeSet<_>>()
                .into_iter()
                .collect();
            (state.seq, stale, keys)
        })
    }
}

// ===========================================================================
// The catalog tree
// ===========================================================================

/// What a category is made from, or changed to. On a change, `None` leaves a
/// field as it is.
#[derive(Debug, Clone, Default)]
pub struct CategoryChange {
    pub name: Option<String>,
    /// `Some("")` moves the category to the top level.
    pub parent: Option<String>,
    /// Replaces the category's OWN attribute list.
    pub attributes: Option<Vec<AttributeDef>>,
}

impl Db {
    /// Add a category. The whole tree is re-checked inside the write
    /// ([`catalog::check_tree`]), so a parent that vanished meanwhile or a
    /// key an ancestor gained meanwhile is caught there.
    pub fn create_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
        let id = catalog::normalize_id(id)?;
        let name = change.name.unwrap_or_default().trim().to_string();
        if name.is_empty() {
            return Err(Error::bad_request("a category needs a name"));
        }
        let attributes = catalog::check_definitions(change.attributes.unwrap_or_default())?;
        let parent = change.parent.unwrap_or_default().trim().to_string();
        self.mutate(move |state| {
            if catalog::find(&state.categories, &id).is_some() {
                return Err(Error::conflict(format!("category '{id}' exists")));
            }
            let parent = if parent.is_empty() {
                String::new()
            } else {
                catalog::find(&state.categories, &parent)
                    .map(|c| c.id.clone())
                    .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
            };
            let category = Category { id, name, parent, attributes, created_at: now() };
            state.categories.push(category.clone());
            catalog::check_tree(&state.categories)?;
            Ok(category)
        })
    }

    /// Rename a category, move it, or replace its own attributes.
    ///
    /// Changing an attribute's type, or dropping one, leaves the values parts
    /// already hold where they are: a value that no longer fits is reported
    /// at the next release of that part, and a value whose key is gone is
    /// inert. Nothing is rewritten behind anyone's back.
    pub fn update_category(&self, id: &str, change: CategoryChange) -> Result<Category, Error> {
        let attributes = change.attributes.map(catalog::check_definitions).transpose()?;
        let id = id.trim().to_string();
        self.mutate(move |state| {
            let index = state
                .categories
                .iter()
                .position(|c| c.id.eq_ignore_ascii_case(&id))
                .ok_or_else(|| Error::not_found(format!("category '{id}'")))?;
            if let Some(name) = change.name {
                let name = name.trim().to_string();
                if name.is_empty() {
                    return Err(Error::bad_request("a category needs a name"));
                }
                state.categories[index].name = name;
            }
            if let Some(parent) = change.parent {
                let parent = parent.trim();
                state.categories[index].parent = if parent.is_empty() {
                    String::new()
                } else {
                    catalog::find(&state.categories, parent)
                        .map(|c| c.id.clone())
                        .ok_or_else(|| Error::bad_request(format!("there is no category '{parent}'")))?
                };
            }
            if let Some(attributes) = attributes {
                state.categories[index].attributes = attributes;
            }
            // A cycle, a too-deep chain, or a key now defined twice along a
            // chain — in EITHER direction — is refused here, and the mutation
            // rolls back.
            catalog::check_tree(&state.categories)?;
            Ok(state.categories[index].clone())
        })
    }

    /// Remove a category that nothing uses. A category with children, or with
    /// any part filed in it, is refused: deleting it would silently re-file
    /// those parts as uncategorized.
    pub fn delete_category(&self, id: &str) -> Result<(), Error> {
        let id = id.trim().to_string();
        self.mutate(move |state| {
            let category = catalog::find(&state.categories, &id)
                .ok_or_else(|| Error::not_found(format!("category '{id}'")))?
                .id
                .clone();
            if let Some(child) = state.categories.iter().find(|c| c.parent.eq_ignore_ascii_case(&category)) {
                return Err(Error::conflict(format!(
                    "category '{category}' has a sub-category '{}' — move or delete it first",
                    child.id
                )));
            }
            let used = state
                .parts
                .iter()
                .filter(|p| p.category.eq_ignore_ascii_case(&category))
                .count();
            if used > 0 {
                return Err(Error::conflict(format!(
                    "category '{category}' holds {used} part{} — move them to another category first",
                    if used == 1 { "" } else { "s" }
                )));
            }
            state.categories.retain(|c| c.id != category);
            Ok(())
        })
    }
}

/// Whether `needle` (lower-case) appears in anything a person would search a
/// part by.
fn part_matches(categories: &[Category], part: &Part, needle: &str) -> bool {
    let hit = |text: &str| text.to_ascii_lowercase().contains(needle);
    hit(&part.number)
        || hit(&part.name)
        || hit(&part.description)
        || hit(&part.category)
        || hit(&catalog::path_name(categories, &part.category))
        || part.tags.iter().any(|t| hit(t))
        || part.attributes.values().any(|value| match value {
            Value::String(text) => hit(text),
            Value::Number(n) => hit(&n.to_string()),
            _ => false,
        })
        || part.sourcing.iter().any(|mp| hit(&mp.mpn) || mp.offers.iter().any(|o| hit(&o.spn)))
}

/// Refuse a release whose part is missing a required attribute, or holds a
/// value its category's schema no longer accepts. Every problem is named at
/// once, so a user fixes them in one pass.
fn catalog_gate(categories: &[Category], part: &Part) -> Result<(), Error> {
    let problems = catalog::release_problems(categories, part);
    if problems.is_empty() {
        return Ok(());
    }
    Err(Error::conflict(format!(
        "{} cannot release until its catalog values are complete: {}",
        part.number,
        problems.join("; ")
    )))
}

/// A revision whose review rule is not met cannot release ([`crate::review`]).
fn review_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
    let (rule, _) = crate::review::rule_for(&state.settings, &state.categories, part);
    crate::review::release_gate(revision, &rule, &part.number)
}

/// The assembly revision an instructions document instructs: its
/// `instructions.target.sourceKey`, when that names a PLM revision that exists
/// and is not itself instructions. A local file's key is no reference.
pub fn instructs_of(state: &State, document: &Value) -> Option<crate::model::Instructs> {
    let key = document.pointer("/instructions/target/sourceKey")?.as_str()?;
    let (number, label) = crate::identity::split_key(key)?;
    let part = state.part(&number).filter(|p| p.document_class != DocumentClass::Instructions)?;
    let revision = part.revision(&label)?;
    Some(crate::model::Instructs { part: part.id.clone(), revision: revision.id.clone() })
}

/// Instructions release for a released assembly revision, only once the
/// author approved a re-target (the document's `instructions.retarget` is
/// clear), and only with current player data: made by the CAD app from the
/// document the revision holds ([`crate::player`]), so the released player
/// shows what was released.
fn instructions_gate(state: &State, root: &Path, part: &Part, revision: &Revision) -> Result<(), Error> {
    if part.document_class != DocumentClass::Instructions {
        return Ok(());
    }
    let refuse = |why: String| Err(Error::conflict(format!("{} rev {} cannot release: {why}", part.number, revision.label)));
    let Some(target) = &revision.instructs else {
        return refuse("its document instructs no PLM assembly revision".into());
    };
    let Some((assembly, assembly_revision)) = state.part(&target.part).and_then(|p| Some((p, p.revision(&target.revision)?))) else {
        return refuse("the assembly revision it instructs is gone".into());
    };
    if assembly_revision.lifecycle != Lifecycle::Released {
        return refuse(format!("{} rev {} is {}, not released", assembly.number, assembly_revision.label, assembly_revision.lifecycle.as_str()));
    }
    let document = fs::read_to_string(root.join(crate::identity::model_path(&part.id, &revision.id)))
        .ok()
        .and_then(|text| serde_json::from_str::<Value>(&text).ok());
    if document.as_ref().and_then(|d| d.pointer("/instructions/retarget")).is_some_and(|r| !r.is_null()) {
        return refuse(format!("its re-target to {} rev {} is not approved yet", assembly.number, assembly_revision.label));
    }
    if revision.player.as_ref().is_none_or(|player| player.content_hash != revision.content_hash) {
        return refuse("it has no current player data: open it in the CAD app and save it there".into());
    }
    Ok(())
}

fn children_gate(state: &State, part: &Part, revision: &Revision) -> Result<(), Error> {
    if !state.settings.require_released_children {
        return Ok(());
    }
    let problems = bom::unreleased_children(state, revision);
    if problems.is_empty() {
        return Ok(());
    }
    Err(Error::conflict(format!(
        "{} rev {} cannot release until everything it uses is released: {}",
        part.number,
        revision.label,
        problems.join("; ")
    )))
}

/// The first revision whose uses list pins `revision_id` of `part_id`, as
/// "number" and "label".
fn pinned_by(state: &State, part_id: &str, revision_id: &str) -> Vec<String> {
    state
        .parts
        .iter()
        .flat_map(|parent| {
            parent.revisions.iter().filter_map(move |rev| {
                rev.uses
                    .iter()
                    .any(|u| u.part == part_id && u.revision == revision_id)
                    .then(|| format!("{} rev {}", parent.number, rev.label))
            })
        })
        .collect()
}

/// The direct users of `revision_id` of `part_id` (pinned, or floating to it
/// now), each as `<number> rev <label> (<state>)`, in store order, each once.
fn used_by_now(state: &State, part_id: &str, revision_id: &str) -> Vec<String> {
    let Some(part) = state.part(part_id) else { return Vec::new() };
    let Some(revision) = part.revision(revision_id) else { return Vec::new() };
    let mut out: Vec<String> = Vec::new();
    for line in bom::where_used(state, part, Some(revision), 1).lines {
        let name = format!("{} rev {} ({})", line.number, line.revision_label, line.state);
        if !out.contains(&name) {
            out.push(name);
        }
    }
    out
}

/// `names` for a sentence: at most [`NAMED_AT_MOST`], then how many more.
pub(crate) fn named_list(names: &[String]) -> String {
    let shown = names.iter().take(NAMED_AT_MOST).cloned().collect::<Vec<_>>().join(", ");
    match names.len().saturating_sub(NAMED_AT_MOST) {
        0 => shown,
        more => format!("{shown} and {more} more"),
    }
}

/// How many users a refusal or warning names before "and N more".
const NAMED_AT_MOST: usize = 10;

/// The two conditions a revision's document and uses list are written under,
/// checked together so the refusal says which one failed: the revision is in
/// work, and `user` holds its lock.
pub fn check_writable(state: &State, user: &User, part_id: &str, revision_id: &str) -> Result<(), Error> {
    let part = state.part(part_id).ok_or_else(|| Error::not_found("part"))?;
    let revision = part
        .revision(revision_id)
        .ok_or_else(|| Error::not_found("revision"))?;
    if !revision.lifecycle.is_editable() {
        return Err(Error::conflict(format!(
            "{} revision {} is {} and cannot be written — start a new revision",
            part.number,
            revision.label,
            revision.lifecycle.as_str()
        )));
    }
    match &revision.lock {
        None => Err(Error::conflict(format!(
            "{} revision {} is not checked out — check it out before saving",
            part.number, revision.label
        ))),
        Some(lock) if lock.user_id != user.id => {
            let holder = state
                .user(&lock.user_id)
                .map(|u| u.username.clone())
                .unwrap_or_else(|| "another user".to_string());
            Err(Error::conflict(format!(
                "{} revision {} is checked out by {holder}",
                part.number, revision.label
            )))
        }
        Some(_) => Ok(()),
    }
}

impl Db {
    /// Replace a revision's uses list — the call the CAD app makes on save,
    /// and the web page's stand-in until it does. Written under the same two
    /// conditions as the document ([`check_writable`]), so a released
    /// revision's list never changes; checked by [`bom::check_uses`] inside
    /// the same lock, so no two concurrent writes can close a cycle between
    /// them.
    pub fn set_uses(&self, user: &User, part_id: &str, revision_id: &str, body: &Value) -> Result<Vec<Use>, Error> {
        let user = user.clone();
        let body = body.clone();
        self.mutate(move |state| {
            check_writable(state, &user, part_id, revision_id)?;
            let uses = bom::check_uses(state, part_id, &body)?;
            let occurrences = crate::bom_config::capture_occurrences(state, part_id, revision_id, &body)?;
            let (_, revision) = find_revision_mut(state, part_id, revision_id)?;
            revision.uses = uses.clone();
            if let Some(occurrences) = occurrences { revision.occurrences = occurrences; }
            crate::bom_config::synchronize_uses(revision);
            revision.modified_at = now();
            state.touch(crate::identity::document_key(part_id, revision_id));
            Ok(uses)
        })
    }
}

/// What the release hooks receive.
pub(crate) fn release_input(state: &State, part: &Part, revision: &Revision, user: &User) -> Value {
    json!({
        "part": part,
        "sourcing": sourcing::resolved(state, part),
        "revision": revision,
        "uses": bom::resolved_uses(state, revision),
        "unreleased_children": bom::unreleased_children(state, revision),
        "document_key": revision.document_key(&part.id),
        "user": scripting::user_json(user),
    })
}

/// Whether any part already carries `number` (ASCII case ignored).
fn state_has_number(parts: &[Part], number: &str) -> bool {
    parts.iter().any(|p| p.number.eq_ignore_ascii_case(number))
}

/// An admin's pattern, anchored so it must match the WHOLE number: a pattern
/// of `\d{5}` should not accept `ABC12345XYZ`.
pub fn full_match(pattern: &str) -> Result<regex::Regex, Error> {
    regex::Regex::new(&format!("^(?:{pattern})$"))
        .map_err(|e| Error::bad_request(format!("'{pattern}' is not a usable pattern: {e}")))
}

/// The longest part number or revision label the store accepts.
pub const MAX_IDENTIFIER: usize = 64;

/// A number is text a person can read aloud and type back: not empty, not
/// padded, no control characters, and short enough to print on a label.
pub fn check_number(number: &str) -> Result<(), Error> {
    check_identifier(number, "a part number")
}

/// A label follows the same rule as a number.
pub fn check_label(label: &str) -> Result<(), Error> {
    check_identifier(label, "a revision label")
}

fn check_identifier(text: &str, what: &str) -> Result<(), Error> {
    if text.trim().is_empty() {
        return Err(Error::bad_request(format!("{what} cannot be empty")));
    }
    if text.trim() != text {
        return Err(Error::bad_request(format!("{what} cannot start or end with a space")));
    }
    if text.chars().any(char::is_control) {
        return Err(Error::bad_request(format!("{what} cannot hold control characters")));
    }
    if text.chars().count() > MAX_IDENTIFIER {
        return Err(Error::bad_request(format!("{what} is at most {MAX_IDENTIFIER} characters")));
    }
    Ok(())
}

/// The label offered for a part's next revision: the one after the newest
/// revision's, skipping any the part already has. Free-text labels can be
/// anything, so the walk may restart at `A`; skipping taken labels is what
/// keeps the suggestion usable.
pub fn suggest_label(part: &Part) -> String {
    let mut candidate = lifecycle::next_revision_label(part.latest().map(|r| r.label.as_str()));
    while part.revision_by_label(&candidate).is_some() {
        candidate = lifecycle::next_revision_label(Some(&candidate));
    }
    candidate
}

/// What a new part is made from. Empty `number` lets the type decide (a
/// counter) or leaves it to the script; empty `label` takes the suggestion.
#[derive(Debug, Clone, Default)]
pub struct PartSpec {
    pub part_type: String,
    pub number: String,
    pub name: String,
    pub description: String,
    pub category: String,
    pub document_class: DocumentClass,
    pub label: String,
    pub tags: Vec<String>,
    /// Attribute values, checked against the category's schema. A draft may
    /// leave required ones out; the release gate asks for them.
    pub attributes: serde_json::Map<String, Value>,
    /// Use `number` and `label` as typed: a script may refuse them but not
    /// change them. A family row names its member's number and revision.
    pub exact: bool,
    /// Where the part comes from in another system (a KiCad `library_id`).
    /// Unique among parts of the same type ([`external_ref_clash`]).
    pub external_ref: String,
    /// The first revision's origin: authored, or imported by a library
    /// import. Generated is Generate's alone.
    pub origin: crate::model::Origin,
    /// Link the new part into its creator's workspace, in this folder (empty:
    /// the top), in the same transaction as the part. `None` links nothing.
    /// Only [`crate::workspace::link_on_create`] decides it.
    pub workspace: Option<String>,
}

/// The refusal for giving a part of type `part_type` the external reference
/// `external_ref` when another part of that type already has it — checked
/// inside the store's write lock, so two imports of one library entry at
/// once cannot both make a part. `except` is the part being edited. An empty
/// reference never clashes.
pub fn external_ref_clash(state: &State, part_type: &str, external_ref: &str, except: &str) -> Result<(), Error> {
    if external_ref.is_empty() {
        return Ok(());
    }
    match state.parts.iter().find(|p| p.id != except && p.part_type == part_type && p.external_ref == external_ref) {
        Some(owner) => Err(Error::conflict(format!(
            "external_ref '{external_ref}' is already {} ({}) — look it up with ?external_ref= and use that part",
            owner.number, part_type
        ))),
        None => Ok(()),
    }
}

/// Refuse `origin: generated` from a caller: only Generate makes those.
pub fn check_origin(origin: crate::model::Origin) -> Result<(), Error> {
    if origin == crate::model::Origin::Generated {
        return Err(Error::bad_request("origin 'generated' is set by Generate alone — use authored or imported"));
    }
    Ok(())
}

/// Find a revision for mutation, reporting which half was missing.
pub(crate) fn find_revision_mut<'a>(
    state: &'a mut State,
    part_id: &str,
    revision_id: &str,
) -> Result<(String, &'a mut Revision), Error> {
    let part = state.parts.get_mut(&part_id)
        .ok_or_else(|| Error::not_found("part"))?;
    let number = part.number.clone();
    let revision = part
        .revision_mut(revision_id)
        .ok_or_else(|| Error::not_found("revision"))?;
    Ok((number, revision))
}