zebflow 0.11.14

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
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
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
//! Platform domain models and configuration.

use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use crate::infra::cluster::config::ClusterSettings;
use crate::infra::cluster::registry::WorkerHeartbeat;
use crate::infra::execution::placement::ProjectRuntimeProfile;
use crate::infra::execution::runner::RunnerCapabilities;
use crate::zebfs::{FileBackend, FileStore, ZebFs, ZebFsError};

/// Data adapter selection.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum DataAdapterKind {
    /// SQLite-backed platform catalog (WAL mode, bundled SQLite 3.47).
    #[default]
    Sqlite,
    /// Placeholder adapter.
    DynamoDb,
    /// Placeholder adapter.
    Firebase,
}

/// File adapter selection.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum FileAdapterKind {
    /// Local filesystem tree. Git-sync friendly.
    #[default]
    Filesystem,
}

/// Platform bootstrap/runtime config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlatformConfig {
    /// Root data directory where platform metadata + project files are stored.
    ///
    /// Defaults to `ZEBFLOW_PLATFORM_DATA_DIR` when it is set and to the OS
    /// user-data path otherwise (`platform::boot`); never to a path relative to
    /// the working directory, which `interface.md` §5 says identifies nothing.
    pub data_root: PathBuf,
    /// Selected metadata adapter.
    pub data_adapter: DataAdapterKind,
    /// Selected file adapter.
    pub file_adapter: FileAdapterKind,
    /// Default superadmin username created on first bootstrap.
    pub default_owner: String,
    /// Optional initial superadmin password created on first bootstrap.
    ///
    /// When empty, Zebflow generates a random password and stores it in a
    /// private file under the platform data root.
    pub default_password: String,
    /// Default project slug created on first bootstrap.
    pub default_project: String,
    /// Unix timestamp seconds; platform-issued secrets created before this time
    /// are invalidated on startup/lookup.
    #[serde(default)]
    pub secret_rotation_epoch: i64,
    /// Cluster/controller-office role and connectivity settings.
    pub cluster: ClusterSettings,
}

impl Default for PlatformConfig {
    fn default() -> Self {
        Self {
            // Not a literal: `boot::default_data_root` is the one place the
            // two cases live, so every construction of this struct that does
            // not name a root gets the same one a server mode would open.
            data_root: crate::platform::boot::default_data_root(),
            data_adapter: DataAdapterKind::Sqlite,
            file_adapter: FileAdapterKind::Filesystem,
            default_owner: "superadmin".to_string(),
            default_password: String::new(),
            default_project: "default".to_string(),
            secret_rotation_epoch: 0,
            cluster: ClusterSettings::default(),
        }
    }
}

/// User profile stored by platform metadata adapter.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformUser {
    /// Stable internal user id.
    #[serde(default)]
    pub user_id: String,
    /// User identifier.
    pub owner: String,
    /// Role string (`superadmin`, `member`, ...).
    pub role: String,
    /// Display name for git commits (e.g. "Alice Smith").
    #[serde(default)]
    pub git_name: String,
    /// Email for git commits (e.g. "alice@example.com").
    #[serde(default)]
    pub git_email: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// User record with auth secret, used internally by auth service.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StoredUser {
    /// Public profile fields.
    pub profile: PlatformUser,
    /// Local platform auth material.
    pub auth: PlatformUserLocalAuth,
}

/// Credential state: the current password was generated by the platform and
/// never chosen by a person. A browser login on such an account is forced to
/// the change-password screen until the state becomes [`CREDENTIAL_STATE_CHOSEN`].
pub const CREDENTIAL_STATE_GENERATED: &str = "generated";

/// Credential state: the current password was chosen by an operator or user.
pub const CREDENTIAL_STATE_CHOSEN: &str = "chosen";

fn default_credential_state() -> String {
    CREDENTIAL_STATE_CHOSEN.to_string()
}

/// Local auth record for one user.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformUserLocalAuth {
    /// Stable internal user id.
    pub user_id: String,
    /// Stored password hash.
    pub password_hash: String,
    /// Password hash algorithm identifier.
    pub password_alg: String,
    /// Unix timestamp seconds.
    pub password_updated_at: i64,
    /// `generated` while the password is a platform-generated one nobody has
    /// replaced; `chosen` once a person set it. See [`CREDENTIAL_STATE_GENERATED`].
    #[serde(default = "default_credential_state")]
    pub credential_state: String,
}

/// Project profile stored by metadata adapter.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformProject {
    /// Stable internal project id.
    #[serde(default)]
    pub project_id: String,
    /// Stable internal owner user id.
    #[serde(default)]
    pub owner_user_id: String,
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Display title.
    pub title: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
    /// Left off this office's home project list ("Hide from home"). The
    /// project stays reachable by URL and search, and is listed under the
    /// home page's hidden section. Instance presentation, not project content:
    /// it is not in `zebflow.yaml` and does not travel with the repository.
    #[serde(default)]
    pub hidden: bool,
}

// ---------------------------------------------------------------------------
// Credential type definitions
// ---------------------------------------------------------------------------

/// Defines a credential type (e.g. `postgres`, `telegram_bot`).
/// Same format for official (built-in) and custom (from composite/WASM packages).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CredentialTypeDef {
    /// Unique kind identifier, e.g. `"postgres"`, `"telegram_bot"`.
    pub kind: String,
    /// Human-readable title shown in UI.
    pub title: String,
    /// Short description of this credential type.
    #[serde(default)]
    pub description: String,
    /// Form fields for creating/editing a credential of this type.
    pub fields: Vec<CredentialFieldDef>,
    /// Placeholder mappings for composite nodes.
    /// Maps placeholder name → secret field key.
    /// Only used by composite/WASM packages. Empty for built-in types.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub placeholders: HashMap<String, String>,
    /// Config key in the composite node that holds the credential ID.
    /// E.g. `"credential_id"` — the composite's `config.credential_id` value is
    /// used to look up the credential at runtime.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub config_key: String,
}

/// One field in a credential type definition form.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CredentialFieldDef {
    /// Secret JSON key this field writes to.
    pub key: String,
    /// Display label.
    pub label: String,
    /// Field type: `"text"`, `"password"`, `"select"`, `"textarea"`, `"number"`, `"tags"`.
    #[serde(default = "default_field_type", rename = "type")]
    pub field_type: String,
    /// Whether this field is required.
    #[serde(default)]
    pub required: bool,
    /// Input placeholder text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placeholder: Option<String>,
    /// Help text shown below the field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub help: Option<String>,
    /// Default value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    /// Auto-generation hint, e.g. `"random_hex_32"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generate: Option<String>,
    /// Options for `select` field type.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub options: Vec<CredentialFieldOption>,
    /// Whether this field should span full width in UI.
    #[serde(default, rename = "fullWidth")]
    pub full_width: bool,
    /// Number of rows for `textarea` field type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rows: Option<u32>,
}

/// Option for a `select` credential field.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CredentialFieldOption {
    pub value: String,
    pub label: String,
}

fn default_field_type() -> String {
    "text".to_string()
}

/// Stored project credential record used by runtime nodes and management APIs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProjectCredential {
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Stable credential id.
    pub credential_id: String,
    /// Display title.
    pub title: String,
    /// Driver/kind (`postgres`, `openai`, ...).
    pub kind: String,
    /// Secret payload owned by the project.
    pub secret: serde_json::Value,
    /// Optional freeform notes.
    pub notes: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One project credential summary row safe to return in list responses.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectCredentialListItem {
    /// Stable credential id.
    pub credential_id: String,
    /// Display title.
    pub title: String,
    /// Driver/kind (`postgres`, `openai`, ...).
    pub kind: String,
    /// Whether the credential currently stores a secret payload.
    pub has_secret: bool,
    /// Optional freeform notes.
    pub notes: String,
    /// Roles registered in this credential (JWT only). Non-sensitive — safe to expose in list responses.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub auth_roles: Vec<String>,
    /// Safe variable definitions exposed by `secure_request` credentials.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secure_request_vars: Vec<SecureRequestVariableDefinition>,
    /// OAuth2 token status. Derived at list-time, not stored.
    /// Values: "" (non-oauth2), "not_configured", "authorized", "expired".
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub oauth2_status: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// Safe variable definition exposed from a `secure_request` credential.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SecureRequestVariableDefinition {
    /// Stable variable name used in the request template.
    pub name: String,
    /// Human-readable label displayed in UI surfaces.
    pub label: String,
    /// Value kind hint such as `string`, `secret`, or `header`.
    #[serde(default)]
    pub value_type: String,
    /// Whether this variable is required at request time.
    #[serde(default)]
    pub required: bool,
    /// Optional default expression evaluated client-side or by later request tooling.
    #[serde(default)]
    pub default_expr: String,
    /// Optional human-readable explanation.
    #[serde(default)]
    pub description: String,
}

/// Stored project DB connection record used by DB suite and runtime nodes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProjectDbConnection {
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Stable connection id.
    pub connection_id: String,
    /// Stable route slug.
    pub connection_slug: String,
    /// Display label.
    pub connection_label: String,
    /// Database kind (`sqlite`, `postgresql`, ...).
    pub database_kind: String,
    /// Optional linked credential id.
    pub credential_id: Option<String>,
    /// Optional kind-specific config payload.
    pub config: serde_json::Value,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One project DB connection summary row safe to return in list responses.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectDbConnectionListItem {
    /// Stable connection id.
    pub connection_id: String,
    /// Stable route slug.
    pub connection_slug: String,
    /// Display label.
    pub connection_label: String,
    /// Database kind (`sqlite`, `postgresql`, ...).
    pub database_kind: String,
    /// Optional linked credential id.
    pub credential_id: Option<String>,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One project-scoped hub repository source.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectHubRepository {
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Stable repository id.
    pub repository_id: String,
    /// Display title.
    pub title: String,
    /// Base URL of the remote hub, e.g. `http://127.0.0.1:10612`.
    pub base_url: String,
    /// Remote owner slug on the target hub.
    pub remote_owner: String,
    /// Remote project slug on the target hub.
    pub remote_project: String,
    /// Optional bearer token for read access.
    pub read_token: String,
    /// Whether this repository should be queried in Packs.
    pub enabled: bool,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One platform-scoped hub repository source used from Home.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformHubRepository {
    /// Stable internal source id.
    #[serde(default)]
    pub source_id: String,
    /// Stable internal owner user id.
    #[serde(default)]
    pub owner_user_id: String,
    /// Owner identifier for the local platform user who manages this source.
    pub owner: String,
    /// Stable repository id.
    pub repository_id: String,
    /// Display title.
    pub title: String,
    /// Base URL of the remote hub, e.g. `http://127.0.0.1:10612/api/projects/superadmin/default/hub`.
    pub base_url: String,
    /// Remote owner slug on the target hub when using a proxy base.
    pub remote_owner: String,
    /// Remote project slug on the target hub when using a proxy base.
    pub remote_project: String,
    /// Optional bearer token for read access.
    pub read_token: String,
    /// Which channel serves this source: `api` or `static`.
    ///
    /// Absent means `api`, which is what every row written before static
    /// repositories existed is. A kind this build does not implement refuses
    /// rather than being fetched from as though it were an API hub.
    #[serde(default)]
    pub kind: String,
    /// Where this source sits in resolution order. Lower is consulted first.
    ///
    /// This is where the order in `distribution.md` is configured: the official
    /// sources are seeded at 10 and 20, and anything added later defaults to
    /// 100 so it is consulted after them.
    #[serde(default)]
    pub priority: i64,
    /// Source visibility in Platform Home hub explorer: public or private.
    #[serde(default)]
    pub visibility: String,
    /// Whether this repository should be queried in Home hub.
    pub enabled: bool,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One explicit grant from a platform-owned Hub access source to projects.
///
/// Registering a Hub source only records where the Hub lives. A grant is the
/// separate policy row that lets projects use that access for read/publish/manage
/// workflows. This keeps internal/private Hubs explicit instead of inherited.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubAccessGrant {
    /// Stable grant id.
    pub grant_id: String,
    /// Platform owner that owns the Hub source.
    pub source_owner: String,
    /// Stable platform Hub source id.
    pub source_id: String,
    /// Human-facing repository id for the Hub source.
    pub repository_id: String,
    /// Grant scope: `all_projects` or `selected_project`.
    pub grant_scope: String,
    /// Target owner for selected-project grants. Empty for all-project grants.
    pub target_owner: String,
    /// Target project for selected-project grants. Empty for all-project grants.
    pub target_project: String,
    /// Whether this grant allows browsing/installing from the source.
    pub can_read: bool,
    /// Whether this grant allows publishing through the access.
    pub can_publish: bool,
    /// Whether this grant allows managing the access.
    pub can_manage: bool,
    /// Whether the grant is active.
    pub enabled: bool,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One explicit hub authority row.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubAuthority {
    /// Stable authority id.
    pub authority_id: String,
    /// Host project id.
    pub host_project_id: String,
    /// Hub authority owner slug.
    pub owner: String,
    /// Hub authority project slug.
    pub project: String,
    /// Whether producer mode is currently enabled.
    pub enabled: bool,
    /// Public hub API base URL when exposed.
    pub public_base_url: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One durable office row in the platform control plane.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformOffice {
    /// Stable office id.
    pub office_id: String,
    /// Human-readable / URL-safe office slug.
    pub office_slug: String,
    /// Display label.
    pub label: String,
    /// Office kind (`controller`, `office`, `standalone`).
    pub office_kind: String,
    /// Base URL advertised for control/runtime traffic.
    pub base_url: String,
    /// Current status summary.
    pub status: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// Status word of one issued join token.
pub const JOIN_TOKEN_STATUS_ACTIVE: &str = "active";
/// Status word of one revoked join token.
pub const JOIN_TOKEN_STATUS_REVOKED: &str = "revoked";

/// One join token the controller issued to one office.
///
/// The secret itself is never held here: only `secret_digest`, which is what
/// the controller compares a presented token against (`offices.md` §8).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformOfficeJoinToken {
    /// Office the token was issued to. One row per office.
    pub office_id: String,
    /// `sha256(secret)`, hex. Never the secret, and never serialised.
    ///
    /// `skip_serializing` because this struct is both the stored row and the
    /// shape returned by `GET /api/platform/cluster/join-tokens` and by the mint
    /// response. The digest used to travel in both, which put an office's
    /// stored material into HTTP responses, browser memory, and every proxy log
    /// on the way. It no longer keys anything a forger could use — the
    /// controller signs with a private key it never publishes — but a value
    /// that identifies one office's membership still has no business leaving
    /// the controller's storage, and the API never needed it.
    #[serde(skip_serializing, default)]
    pub secret_digest: String,
    /// `active` or `revoked`. Revoking one row locks out exactly one office.
    pub status: String,
    /// Operator note recorded at mint time.
    #[serde(default)]
    pub note: String,
    /// Unix timestamp seconds when the token was minted.
    pub created_at: i64,
    /// Unix timestamp seconds of the last accepted presentation, or `0`.
    #[serde(default)]
    pub last_used_at: i64,
}

impl PlatformOfficeJoinToken {
    /// Whether this token may still be presented.
    pub fn is_active(&self) -> bool {
        self.status.trim() == JOIN_TOKEN_STATUS_ACTIVE
    }
}

/// One vouch this office has already redeemed.
///
/// `offices.md` §2's vouch verb is a hand-off, and a hand-off happens once. The
/// row exists so a second presentation of the same vouch is refused — without
/// it, a value that leaks from a URL bar, a proxy log, or a `Referer` header is
/// a reusable key for as long as it lives.
///
/// It lives in the *office's* own catalog, because the office is the party that
/// must refuse, and §3's whole point is that it can do so without the
/// controller. `instance-directory.md` puts `platform/catalog.db` in the STORE
/// tier beside sessions, which is the same lifetime and the same durability
/// requirement: a record kept only in memory would let a restart reopen every
/// unspent vouch.
///
/// It is bounded by its own subject. A vouch past `expires_at` is refused by
/// the expiry check whatever this table says, so the row can be deleted the
/// moment it outlives the vouch it records, and it is
/// ([`crate::platform::services::ClusterJoinTokenService::redeem_vouch`] prunes
/// on every redemption). The table's ceiling is therefore the number of
/// vouches redeemed inside one TTL window, not the number ever redeemed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformOfficeVouchRedemption {
    /// The vouch's nonce. One row per vouch, and the reason it is spendable once.
    pub nonce: String,
    /// Office the vouch named.
    pub office_id: String,
    /// Identity the vouch carried.
    pub identity: String,
    /// The vouch's own expiry; the row is prunable once it passes.
    pub expires_at: i64,
    /// Unix timestamp seconds the vouch was spent.
    pub redeemed_at: i64,
}

/// A vouch resolved to a local account that already existed.
pub const IDENTITY_WRITE_ACTION_LINKED: &str = "linked";
/// A vouch created a local account that did not exist.
pub const IDENTITY_WRITE_ACTION_CREATED: &str = "created";

/// One thing the controller put into this office's accounts.
///
/// `offices.md` §8: "Anything the controller pushes into an office's accounts
/// is logged where the office's operator can read it." *Where the office's
/// operator can read it* is the load-bearing half — a record only the
/// controller can read would be the controller auditing itself.
///
/// So it is a row in the office's own `platform/catalog.db`, read over the
/// office's own API by the office's own superadmin, with the controller
/// unreachable and uninvolved. On the tier question `instance-directory.md`
/// leaves one answer: STORE, "machine-written, cannot be regenerated, back it
/// up". Not CACHE, which may be deleted with no loss. Not BOUNDED, which is
/// "disposable after a retention window" — the record of who was inserted into
/// your accounts is the last thing that should quietly expire. And not a
/// project's `data/logs/`, which is BOUNDED, 30-day, and scoped to a project an
/// identity write does not belong to.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformOfficeIdentityWrite {
    /// Stable row id.
    pub write_id: String,
    /// Office whose accounts were written.
    pub office_id: String,
    /// Local owner slug that was created or resolved.
    pub owner: String,
    /// [`IDENTITY_WRITE_ACTION_CREATED`] or [`IDENTITY_WRITE_ACTION_LINKED`].
    pub action: String,
    /// Role the local account holds after the write.
    pub role: String,
    /// What caused the write, e.g. `controller-vouch`.
    pub source: String,
    /// Human-readable detail an operator reads without a decoder.
    pub detail: String,
    /// Unix timestamp seconds.
    pub written_at: i64,
}

/// A host command re-enabled this office's local authority (`offices.md` §6).
pub const LOCAL_AUTHORITY_EVENT_BREAK_GLASS: &str = "break-glass";
/// A host command detached this office from its controller (`offices.md` §7).
pub const LOCAL_AUTHORITY_EVENT_DETACH: &str = "detach";

/// One act on this office's own local authority.
///
/// `offices.md` §6 asks for two things at once: break-glass "re-enables local
/// authority", and "its use is recorded locally and reported to the controller
/// on reconnect". §7 then makes detaching a *separate* act. Both are acts by
/// somebody with host access on the office, both change whether local login
/// works, and both are things the office's operator must be able to read back
/// later — so they are one append-only log rather than two.
///
/// The log is also the **state**. Nothing else records whether local authority
/// has been re-enabled, and that is deliberate: a flag stored beside the log
/// could disagree with it, and after a restore or a copy one of the two would
/// be wrong with no way to tell which. The rule is stated once, in
/// [`crate::platform::services::OfficeLocalAuthorityService`], and derived from
/// these rows every time it is asked.
///
/// It lives in the office's own `platform/catalog.db`, STORE tier, for exactly
/// the reason [`PlatformOfficeIdentityWrite`] does: the record of who opened
/// this instance's front door is the last thing that should quietly expire, and
/// it must be readable by the office's operator with the controller absent or
/// gone for good.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformOfficeLocalAuthorityEvent {
    /// Stable row id.
    pub event_id: String,
    /// Office this act was performed on.
    pub office_id: String,
    /// [`LOCAL_AUTHORITY_EVENT_BREAK_GLASS`] or [`LOCAL_AUTHORITY_EVENT_DETACH`].
    pub event: String,
    /// Fingerprint of the join token held when the act happened.
    ///
    /// `sha256(sha256(secret))` — one hash further than the digest the mutual
    /// proof is keyed by, so a row that identifies *which* membership was
    /// broken out of still carries nothing that could be used as that key.
    ///
    /// This is what stops a break-glass silently outliving the join it was
    /// performed against. A re-issued token has a different fingerprint, so the
    /// old row no longer matches and local login is disabled again on the new
    /// join, with nobody having to remember to clear anything.
    #[serde(default)]
    pub join_fingerprint: String,
    /// Local account whose password was rotated in the same act, or empty.
    #[serde(default)]
    pub owner: String,
    /// Human-readable detail an operator reads without a decoder.
    #[serde(default)]
    pub detail: String,
    /// Unix timestamp seconds the act was performed.
    pub acted_at: i64,
    /// Unix timestamp seconds the controller acknowledged it, or `0`.
    ///
    /// Only a break-glass is ever reported. A detach gives up the credential
    /// that would authenticate the report, so a detach row stays `0` for good
    /// and says so rather than pretending a delivery is pending.
    #[serde(default)]
    pub reported_at: i64,
}

impl PlatformOfficeLocalAuthorityEvent {
    /// Whether this row is a break-glass rather than a detach.
    pub fn is_break_glass(&self) -> bool {
        self.event.trim() == LOCAL_AUTHORITY_EVENT_BREAK_GLASS
    }
}

/// One minted vouch, as the controller hands it over.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ClusterOfficeVouch {
    /// Office the vouch opens, and no other.
    pub office_id: String,
    /// Identity the controller vouched for.
    pub identity: String,
    /// Unix timestamp seconds after which the office refuses it.
    pub expires_at: i64,
    /// Seconds the vouch lives, so a caller need not subtract clocks.
    pub ttl_seconds: i64,
    /// The vouch itself.
    pub vouch: String,
    /// Where to redeem it, when the office record advertises a base URL.
    #[serde(default)]
    pub redeem_url: String,
}

/// One accepted vouch, after the office verified and spent it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcceptedOfficeVouch {
    /// Office that accepted it.
    pub office_id: String,
    /// Identity the controller vouched for.
    pub identity: String,
    /// The vouch's expiry, kept for the redemption record.
    pub expires_at: i64,
}

/// One platform-level service instance hosted by an office.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformServiceInstance {
    /// Stable service instance id, e.g. `hub-default`.
    pub service_instance_id: String,
    /// Service kind, e.g. `hub`.
    pub service_kind: String,
    /// Display label.
    pub display_label: String,
    /// Office that serves this service runtime.
    pub host_office_id: String,
    /// Office that owns this service's operational state.
    pub state_office_id: String,
    /// Public API/base URL for this service, when exposed.
    pub public_base_url: String,
    /// Whether the service is enabled.
    pub enabled: bool,
    /// Current service status summary.
    pub status: String,
    /// Monotonic placement/config generation.
    pub placement_generation: i64,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One registered runtime node under an office.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlatformOfficeNode {
    /// Stable office id.
    pub office_id: String,
    /// Stable node id.
    pub node_id: String,
    /// Display label.
    pub label: String,
    /// Advertised base URL.
    pub base_url: String,
    /// Current status summary.
    pub status: String,
    /// Declared capabilities.
    #[serde(default)]
    pub capabilities: RunnerCapabilities,
    /// Unix timestamp seconds.
    pub registered_at: i64,
    /// Unix timestamp seconds.
    pub last_heartbeat_at: i64,
}

/// One stable publisher identity inside one hub service authority.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubPublisher {
    /// Stable authority id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub authority_id: String,
    /// Stable publisher row id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub publisher_pk: String,
    /// Internal hub scope owner.
    pub owner: String,
    /// Internal hub scope project.
    pub project: String,
    /// Stable immutable public publisher identity.
    pub publisher_id: String,
    /// Human-facing publisher name.
    pub display_name: String,
    /// Stable public publisher URL.
    pub publisher_url: String,
    /// Publisher contact email.
    pub email: String,
    /// Optional human-readable description.
    pub description: String,
    /// Optional icon URL.
    pub icon_url: String,
    /// Optional website URL.
    pub website_url: String,
    /// Whether the publisher is active.
    pub enabled: bool,
    /// Whether this publisher may read private hub artifacts.
    #[serde(default = "default_true")]
    pub can_read: bool,
    /// Whether this publisher may publish package versions.
    #[serde(default = "default_true")]
    pub can_publish: bool,
    /// Whether this publisher may manage publisher-scoped settings/tokens.
    #[serde(default)]
    pub can_manage: bool,
    /// Maximum number of package ids this publisher may own. Zero means default.
    #[serde(default)]
    pub max_packages: i64,
    /// Maximum raw artifact bytes per package version. Zero means default.
    #[serde(default)]
    pub max_package_bytes: i64,
    /// Maximum media files per package version. Zero means default.
    #[serde(default)]
    pub max_media_files: i64,
    /// Maximum bytes per image media file. Zero means default.
    #[serde(default)]
    pub max_image_bytes: i64,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One presentation image kept beside a hub package, as an artifact digest.
///
/// The bytes live in this instance's content-addressed Hub artifact store, not
/// inside any release document: a cover is something a human looks at while
/// choosing, and the release is the thing an installer parses to reach files.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubAssetMedia {
    /// Plain file name this image is served as, unique within the package.
    pub name: String,
    /// Role this image plays, for example `cover`.
    pub role: String,
    /// Media type of the stored bytes.
    pub content_type: String,
    /// Size of the stored bytes.
    pub size_bytes: usize,
    /// Lowercase hex SHA-256 naming the bytes in the Hub artifact store.
    pub artifact_sha256: String,
}

/// Presentation for a package listing, mutable beside its releases.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubAssetGallery {
    /// The one image shown for a package before it is opened.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cover: Option<HubAssetGalleryImage>,
    #[serde(default)]
    pub items: Vec<HubAssetGalleryItem>,
}

/// The cover image a listing shows.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubAssetGalleryImage {
    pub kind: String,
    /// A name in the package's `media`.
    pub media_name: String,
    #[serde(default)]
    pub alt: String,
}

/// One gallery entry: a stored image or an external video.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubAssetGalleryItem {
    pub kind: String,
    /// Image form: a name in the package's `media`.
    #[serde(default)]
    pub media_name: String,
    #[serde(default)]
    pub alt: String,
    /// Video form: the external URL.
    #[serde(default)]
    pub url: String,
    #[serde(default)]
    pub title: String,
}

/// One published hub asset package stored by the hub service.
///
/// This is the **mutable** side of a published package. A release
/// (`HubAssetVersion` plus its `HubPackage` document) is immutable and carries
/// only what installing it requires; everything a human reads while choosing —
/// summary, long-form description, gallery, cover — lives here, so correcting
/// a typo costs an update rather than a version bump.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubAssetPackage {
    /// Stable package row id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub package_pk: String,
    /// Stable authority id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub authority_id: String,
    /// Stable publisher row id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub publisher_pk: String,
    /// Stable package id, unique inside one hub instance.
    pub package_id: String,
    /// Internal hub authority owner. Public APIs must not expose this.
    pub authority_owner: String,
    /// Internal hub authority project. Public APIs must not expose this.
    pub authority_project: String,
    /// Publisher owner id.
    pub publisher_owner: String,
    /// Stable public publisher identity inside this hub authority.
    pub publisher_id: String,
    /// Human-facing publisher name.
    pub publisher_display_name: String,
    /// Stable public publisher URL for attribution and discovery.
    pub publisher_url: String,
    /// Publisher contact email.
    pub publisher_email: String,
    /// Asset kind (`pipeline`, `template_pack`, ...).
    pub asset_kind: String,
    /// Display title.
    pub title: String,
    /// Optional human-readable description.
    pub description: String,
    /// One-line listing summary. Falls back to `description` when empty.
    #[serde(default)]
    pub summary: String,
    /// Long-form markdown shown on the package page.
    #[serde(default)]
    pub description_md: String,
    /// Public package image URL resolved from Hub artifact media.
    #[serde(default)]
    pub image_url: String,
    /// Presentation images, each addressed by its digest in the artifact store.
    #[serde(default)]
    pub media: Vec<HubAssetMedia>,
    /// Cover and gallery entries referencing `media` by name.
    #[serde(default)]
    pub gallery: HubAssetGallery,
    /// Visibility (`public`, `private`, `unlisted`).
    pub visibility: String,
    /// Search tags.
    pub tags: Vec<String>,
    /// When every release of this package was retracted, if it was.
    ///
    /// Retraction destroys the bytes and keeps the coordinates, so this row
    /// outlives the releases it describes and the package id can never be
    /// claimed by different content.
    #[serde(default)]
    pub retracted_at: Option<i64>,
    /// Why it was retracted, shown wherever the coordinate is still listed.
    #[serde(default)]
    pub retracted_reason: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One immutable version of a hub asset package.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct HubAssetVersion {
    /// Stable package row id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub package_pk: String,
    /// Stable package id.
    pub package_id: String,
    /// Version string.
    pub version: String,
    /// Internal hub authority owner. Public APIs must not expose this.
    pub authority_owner: String,
    /// Internal hub authority project. Public APIs must not expose this.
    pub authority_project: String,
    /// Publisher owner id.
    pub publisher_owner: String,
    /// Stable public publisher identity.
    pub publisher_id: String,
    /// Source owner from which the asset was exported.
    ///
    /// Provenance is the publishing instance's own record of where a release
    /// came from. It describes that instance's internal project structure, so
    /// it stays in this row and never travels inside a published document.
    pub source_owner: String,
    /// Source project from which the asset was exported. Local, never published.
    pub source_project: String,
    /// Source kind (`pipeline` for v1). Local, never published.
    pub source_kind: String,
    /// Source ref such as `pipelines/foo.zf.json`. Local, never published.
    pub source_ref: String,
    /// Artifact relative path under platform storage.
    pub artifact_rel_path: String,
    /// SHA-256 of artifact bytes.
    pub artifact_sha256: String,
    /// Serialized manifest/payload metadata.
    pub manifest: serde_json::Value,
    /// When this release was retracted, if it was.
    ///
    /// A retracted release keeps its row so `package@version` stays taken
    /// forever: the artifact bytes are gone, but the coordinate still means
    /// this release and nothing else.
    #[serde(default)]
    pub retracted_at: Option<i64>,
    /// Why it was retracted, served wherever the release is still explorable.
    #[serde(default)]
    pub retracted_reason: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
}

/// One hub access token used for publish/read/manage operations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HubToken {
    /// Stable token id.
    pub token_id: String,
    /// Stable authority id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub authority_id: String,
    /// Stable publisher row id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub publisher_pk: String,
    /// Owner id.
    pub owner: String,
    /// Client project slug that owns this token/profile.
    pub project: String,
    /// Stable public publisher identity this token acts as.
    pub publisher_id: String,
    /// Human-facing publisher name.
    pub publisher_display_name: String,
    /// Stable public publisher URL.
    pub publisher_url: String,
    /// Publisher contact email.
    pub publisher_email: String,
    /// Display title.
    pub title: String,
    /// SHA-256 hash of the secret, never returned to clients.
    pub secret_hash: String,
    /// Granted scopes.
    pub scopes: Vec<String>,
    /// Whether this token grants hub read access.
    #[serde(default, skip_serializing)]
    pub scope_read: bool,
    /// Whether this token grants hub publish access.
    #[serde(default, skip_serializing)]
    pub scope_publish: bool,
    /// Whether this token grants hub manage access.
    #[serde(default, skip_serializing)]
    pub scope_manage: bool,
    /// Optional unix timestamp seconds.
    pub expires_at: Option<i64>,
    /// Optional unix timestamp seconds.
    pub last_used_at: Option<i64>,
    /// Optional unix timestamp seconds.
    pub revoked_at: Option<i64>,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

impl HubToken {
    /// Returns whether the token grants the required hub scope.
    pub fn grants_scope(&self, required_scope: &str) -> bool {
        match required_scope.trim() {
            "hub:read" => self.scope_read,
            "hub:publish" => self.scope_publish,
            "hub:manage" => self.scope_manage,
            _ => false,
        }
    }
}

/// Request to create one hub token.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CreateHubTokenRequest {
    /// Stable public publisher identity.
    pub publisher_id: String,
    /// Display title.
    pub title: String,
    /// Granted scopes.
    #[serde(default)]
    pub scopes: Vec<String>,
    /// Optional unix timestamp seconds.
    pub expires_at: Option<i64>,
}

/// Project-scoped assistant runtime configuration (used by Zebtune/chat assistant).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectAssistantConfig {
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Credential id for high-level reasoning/planning model.
    pub llm_high_credential_id: Option<String>,
    /// Credential id for general/cheap model.
    pub llm_general_credential_id: Option<String>,
    /// Max execution steps per request.
    pub max_steps: u32,
    /// Max replan attempts.
    pub max_replans: u32,
    /// Whether assistant is enabled for this project.
    pub enabled: bool,
    /// Number of user+assistant pairs to persist as server-side chat history (default 10).
    pub chat_history_pairs: u32,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// Atomic project-scoped permission used by REST, MCP, and internal assistants.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ProjectCapability {
    ProjectRead,
    /// Destroying the project itself.
    ///
    /// The one thing an Owner has that a Maintainer does not. Without it the
    /// two roles resolved to exactly the same 29 capabilities, and deletion was
    /// guarded by comparing the session's name to the namespace owner — a
    /// string check outside the policy system, which no binding could grant and
    /// no role could describe.
    ProjectDelete,
    MembersRead,
    MembersWrite,
    CredentialsRead,
    CredentialsWrite,
    TemplatesRead,
    TemplatesWrite,
    TemplatesCreate,
    TemplatesDelete,
    TemplatesMove,
    TemplatesDiagnostics,
    PipelinesRead,
    PipelinesWrite,
    PipelinesCreate,
    PipelinesDelete,
    PipelinesMove,
    PipelinesExecute,
    FilesRead,
    FilesWrite,
    FilesDelete,
    /// Serve a folder as a site (`public_execute`) or change one that is.
    FilesPublish,
    TablesRead,
    TablesWrite,
    LibrariesRead,
    LibrariesInstall,
    LibrariesRemove,
    SettingsRead,
    SettingsWrite,
    McpSessionCreate,
    McpSessionRevoke,
}

impl ProjectCapability {
    /// Stable string id used by policy payloads and UI.
    pub fn key(self) -> &'static str {
        match self {
            Self::ProjectRead => "project.read",
            Self::ProjectDelete => "project.delete",
            Self::MembersRead => "members.read",
            Self::MembersWrite => "members.write",
            Self::CredentialsRead => "credentials.read",
            Self::CredentialsWrite => "credentials.write",
            Self::TemplatesRead => "templates.read",
            Self::TemplatesWrite => "templates.write",
            Self::TemplatesCreate => "templates.create",
            Self::TemplatesDelete => "templates.delete",
            Self::TemplatesMove => "templates.move",
            Self::TemplatesDiagnostics => "templates.diagnostics",
            Self::PipelinesRead => "pipelines.read",
            Self::PipelinesWrite => "pipelines.write",
            Self::PipelinesCreate => "pipelines.create",
            Self::PipelinesDelete => "pipelines.delete",
            Self::PipelinesMove => "pipelines.move",
            Self::PipelinesExecute => "pipelines.execute",
            Self::FilesRead => "files.read",
            Self::FilesWrite => "files.write",
            Self::FilesDelete => "files.delete",
            Self::FilesPublish => "files.publish",
            Self::TablesRead => "tables.read",
            Self::TablesWrite => "tables.write",
            Self::LibrariesRead => "libraries.read",
            Self::LibrariesInstall => "libraries.install",
            Self::LibrariesRemove => "libraries.remove",
            Self::SettingsRead => "settings.read",
            Self::SettingsWrite => "settings.write",
            Self::McpSessionCreate => "mcp.session.create",
            Self::McpSessionRevoke => "mcp.session.revoke",
        }
    }

    /// Parse from stable string key.
    pub fn from_key(key: &str) -> Option<Self> {
        match key {
            "project.read" => Some(Self::ProjectRead),
            "members.read" => Some(Self::MembersRead),
            "members.write" => Some(Self::MembersWrite),
            "credentials.read" => Some(Self::CredentialsRead),
            "credentials.write" => Some(Self::CredentialsWrite),
            "templates.read" => Some(Self::TemplatesRead),
            "templates.write" => Some(Self::TemplatesWrite),
            "templates.create" => Some(Self::TemplatesCreate),
            "templates.delete" => Some(Self::TemplatesDelete),
            "templates.move" => Some(Self::TemplatesMove),
            "templates.diagnostics" => Some(Self::TemplatesDiagnostics),
            "pipelines.read" => Some(Self::PipelinesRead),
            "pipelines.write" => Some(Self::PipelinesWrite),
            "pipelines.create" => Some(Self::PipelinesCreate),
            "pipelines.delete" => Some(Self::PipelinesDelete),
            "pipelines.move" => Some(Self::PipelinesMove),
            "pipelines.execute" => Some(Self::PipelinesExecute),
            "files.read" => Some(Self::FilesRead),
            "files.write" => Some(Self::FilesWrite),
            "files.delete" => Some(Self::FilesDelete),
            "files.publish" => Some(Self::FilesPublish),
            "tables.read" => Some(Self::TablesRead),
            "tables.write" => Some(Self::TablesWrite),
            "libraries.read" => Some(Self::LibrariesRead),
            "libraries.install" => Some(Self::LibrariesInstall),
            "libraries.remove" => Some(Self::LibrariesRemove),
            "settings.read" => Some(Self::SettingsRead),
            "settings.write" => Some(Self::SettingsWrite),
            "mcp.session.create" => Some(Self::McpSessionCreate),
            "mcp.session.revoke" => Some(Self::McpSessionRevoke),
            _ => None,
        }
    }

    /// All capabilities — used when auto-creating an MCP session on first activation.
    pub fn all() -> Vec<Self> {
        vec![
            Self::ProjectRead,
            Self::ProjectDelete,
            Self::MembersRead,
            Self::MembersWrite,
            Self::CredentialsRead,
            Self::CredentialsWrite,
            Self::TemplatesRead,
            Self::TemplatesWrite,
            Self::TemplatesCreate,
            Self::TemplatesDelete,
            Self::TemplatesMove,
            Self::TemplatesDiagnostics,
            Self::PipelinesRead,
            Self::PipelinesWrite,
            Self::PipelinesCreate,
            Self::PipelinesDelete,
            Self::PipelinesMove,
            Self::PipelinesExecute,
            Self::FilesRead,
            Self::FilesWrite,
            Self::FilesDelete,
            Self::FilesPublish,
            Self::TablesRead,
            Self::TablesWrite,
            Self::LibrariesRead,
            Self::LibrariesInstall,
            Self::LibrariesRemove,
            Self::SettingsRead,
            Self::SettingsWrite,
            Self::McpSessionCreate,
            Self::McpSessionRevoke,
        ]
    }
}

/// Product-facing managed role presets for project membership.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProjectAccessRolePreset {
    Guest,
    #[default]
    Reporter,
    Developer,
    Maintainer,
    Owner,
}

impl ProjectAccessRolePreset {
    /// Stable preset id used for storage and API transport.
    pub const fn key(self) -> &'static str {
        match self {
            Self::Guest => "guest",
            Self::Reporter => "reporter",
            Self::Developer => "developer",
            Self::Maintainer => "maintainer",
            Self::Owner => "owner",
        }
    }

    /// Human-readable title for settings and invite UI.
    pub const fn title(self) -> &'static str {
        match self {
            Self::Guest => "Guest",
            Self::Reporter => "Reporter",
            Self::Developer => "Developer",
            Self::Maintainer => "Maintainer",
            Self::Owner => "Owner",
        }
    }

    /// Managed policy id emitted by the role preset layer.
    pub const fn policy_id(self) -> &'static str {
        self.key()
    }
}

/// One explicit project member row.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectMember {
    /// Stable internal project id.
    #[serde(default)]
    pub project_id: String,
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Public user slug receiving membership.
    pub user_id: String,
    /// Stable internal user id receiving membership.
    #[serde(default)]
    pub member_user_id: String,
    /// Managed role preset.
    pub role_preset: ProjectAccessRolePreset,
    /// Extra policy ids layered on top of the role preset.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub custom_policy_ids: Vec<String>,
    /// Optional MCP capability ceiling for future per-user MCP sessions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mcp_capability_ceiling: Vec<ProjectCapability>,
    /// Acting user that created or last updated the row.
    #[serde(default)]
    pub created_by: String,
    /// Stable internal actor user id.
    #[serde(default)]
    pub created_by_user_id: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// Invite lifecycle state.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProjectInviteStatus {
    #[default]
    Pending,
    Accepted,
    Revoked,
    Expired,
}

impl ProjectInviteStatus {
    /// Stable storage key, and what an error message calls this state.
    pub fn key(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Accepted => "accepted",
            Self::Revoked => "revoked",
            Self::Expired => "expired",
        }
    }
}

/// One pending or historical invite row for project collaboration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectInvite {
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Stable invite id.
    pub invite_id: String,
    /// User id being invited.
    pub target_user: String,
    /// Managed role preset to grant on acceptance.
    pub role_preset: ProjectAccessRolePreset,
    /// Extra policy ids to apply on acceptance.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub custom_policy_ids: Vec<String>,
    /// Optional MCP capability ceiling to apply on acceptance.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mcp_capability_ceiling: Vec<ProjectCapability>,
    /// Optional human note attached to the invite.
    #[serde(default)]
    pub note: String,
    /// Inviting actor user id.
    #[serde(default)]
    pub invited_by: String,
    /// Invite lifecycle state.
    #[serde(default)]
    pub status: ProjectInviteStatus,
    /// Optional expiry timestamp.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<i64>,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// Create/update payload for one explicit project member.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UpsertProjectMemberRequest {
    /// User id receiving membership.
    pub user_id: String,
    /// Managed role preset.
    pub role_preset: ProjectAccessRolePreset,
    /// Extra policy ids beyond the managed role preset.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub custom_policy_ids: Vec<String>,
    /// Optional MCP capability ceiling for this member.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mcp_capability_ceiling: Vec<ProjectCapability>,
}

/// Create payload for one project invite.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CreateProjectInviteRequest {
    /// Target user id.
    pub target_user: String,
    /// Managed role preset proposed by the invite.
    pub role_preset: ProjectAccessRolePreset,
    /// Extra policy ids to layer on top of the role preset.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub custom_policy_ids: Vec<String>,
    /// Optional MCP capability ceiling for the invited user.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mcp_capability_ceiling: Vec<ProjectCapability>,
    /// Optional note shown in invite listings.
    #[serde(default)]
    pub note: String,
    /// Optional invite expiry timestamp.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<i64>,
}

/// Project policy bundle stored in metadata and reused by users, MCP sessions, and assistants.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectPolicy {
    /// Stable internal project id.
    #[serde(default)]
    pub project_id: String,
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Stable policy id (`viewer`, `editor`, `owner`, ...).
    pub policy_id: String,
    /// Display label.
    pub title: String,
    /// Capability bundle.
    pub capabilities: Vec<ProjectCapability>,
    /// Whether this policy is platform-managed.
    pub managed: bool,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// Subject kind bound to one project policy.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ProjectSubjectKind {
    User,
    McpSession,
    AssistantProfile,
}

impl ProjectSubjectKind {
    /// Stable string id for storage and transport.
    pub fn key(self) -> &'static str {
        match self {
            Self::User => "user",
            Self::McpSession => "mcp_session",
            Self::AssistantProfile => "assistant_profile",
        }
    }
}

/// One project-level subject -> policy binding.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectPolicyBinding {
    /// Stable internal project id.
    #[serde(default)]
    pub project_id: String,
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Subject kind (`user`, `mcp_session`, `assistant_profile`).
    pub subject_kind: ProjectSubjectKind,
    /// Stable subject id.
    pub subject_id: String,
    /// Bound policy id.
    pub policy_id: String,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// Runtime subject passed into authorization checks so REST, MCP, and assistant paths
/// share the same policy gate.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectAccessSubject {
    /// Subject kind.
    pub kind: ProjectSubjectKind,
    /// Stable subject id.
    pub id: String,
}

impl ProjectAccessSubject {
    /// Creates a user subject.
    pub fn user(owner: &str) -> Self {
        Self {
            kind: ProjectSubjectKind::User,
            id: slug_segment(owner),
        }
    }

    /// Creates an MCP session subject.
    pub fn mcp_session(token: &str) -> Self {
        Self {
            kind: ProjectSubjectKind::McpSession,
            id: token.to_string(),
        }
    }
}

/// Pipeline metadata catalog entry stored in platform-level metadata DB.
///
/// The pipeline source file is stored under one project `app/` workspace
/// (git-sync friendly). This metadata is the fast index used by platform UI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PipelineMeta {
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Pipeline id/name.
    pub name: String,
    /// Optional display title.
    pub title: String,
    /// Logical virtual folder path (for registry hierarchy), canonicalized.
    pub virtual_path: String,
    /// Relative source file path under project `app/` root.
    pub file_rel_path: String,
    /// Optional human-readable description.
    pub description: String,
    /// Trigger kind (`webhook`, `schedule`, `function`, ...).
    pub trigger_kind: String,
    /// Stable content hash for change tracking.
    pub hash: String,
    /// Activated production hash. When this differs from `hash`, the working
    /// tree has draft changes that are not promoted to runtime yet.
    pub active_hash: Option<String>,
    /// Unix timestamp seconds when the current active hash was promoted.
    pub activated_at: Option<i64>,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// One project doc file/folder in app/docs (ERD, README.md, AGENTS.md, use cases, etc.).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectDocItem {
    /// Relative path under app/docs.
    pub path: String,
    /// Display name (file or folder name).
    pub name: String,
    /// "file" or "folder".
    pub kind: String,
}

/// One agent doc entry (AGENTS.md, SOUL.md, MEMORY.md).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AgentDocItem {
    /// File name (e.g. "AGENTS.md").
    pub name: String,
    /// Whether the user can edit this doc via REST (false for MEMORY.md — agent-only).
    pub user_editable: bool,
}

/// One breadcrumb segment in pipeline registry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PipelineBreadcrumb {
    /// Display name.
    pub name: String,
    /// Link to this level.
    pub path: String,
    /// Whether a slash separator should appear before this segment.
    pub show_divider: bool,
}

/// One child folder shown in pipeline registry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PipelineFolderItem {
    /// Folder segment name.
    pub name: String,
    /// Link to drill-down into this folder.
    pub path: String,
    /// True for reserved folders (assets, styles) — pinned at the bottom of the registry list.
    pub is_special: bool,
}

/// One template/script/style file shown in the pipeline registry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RegistryFileItem {
    /// File name including extension (e.g. `home.tsx`).
    pub name: String,
    /// Path relative to `repo/` root (e.g. `pipelines/pages/home.tsx`).
    pub rel_path: String,
    /// File kind: `"template"` (.tsx), `"script"` (.ts), `"style"` (.css).
    pub kind: String,
    /// URL to open this file in the template editor.
    pub edit_href: String,
    /// Git status code if dirty.
    pub git_status: Option<String>,
}

/// One pipeline item shown at one registry level.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PipelineRegistryItem {
    /// Pipeline name/id.
    pub name: String,
    /// Optional title.
    pub title: String,
    /// Description.
    pub description: String,
    /// Trigger kind.
    pub trigger_kind: String,
    /// Source file path under `app/`.
    pub file_rel_path: String,
    /// True when pipeline has an active hash matching current hash.
    pub is_active: bool,
    /// True when pipeline has an active hash but it differs from current hash (draft changes).
    pub has_draft: bool,
    /// Git status code (e.g. "M", "??", "D") if file is dirty, otherwise None.
    pub git_status: Option<String>,
}

/// Pipeline registry listing payload for one project + folder path.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PipelineRegistryListing {
    /// Canonical current virtual path (`/` or `/a/b`).
    pub current_path: String,
    /// Breadcrumbs from root to current path.
    pub breadcrumbs: Vec<PipelineBreadcrumb>,
    /// Immediate child folders (sorted: normal first, special last).
    pub folders: Vec<PipelineFolderItem>,
    /// Pipeline entries located exactly at `current_path`.
    pub pipelines: Vec<PipelineRegistryItem>,
    /// Template/script/style files physically at `current_path`.
    pub files: Vec<RegistryFileItem>,
}

/// API payload used to create/update one pipeline definition.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UpsertPipelineDefinitionRequest {
    /// Stable file-relative path under `repo/` (e.g. `"pipelines/api/my-hook.zf.json"`).
    /// This is the single canonical identifier — name and virtual_path are derived from it.
    pub file_rel_path: String,
    /// Optional display title.
    #[serde(default)]
    pub title: String,
    /// Optional human-readable description.
    #[serde(default)]
    pub description: String,
    /// Trigger kind (`webhook`, `schedule`, `function`, ...).
    #[serde(default)]
    pub trigger_kind: String,
    /// Full pipeline source (`*.zf.json`).
    pub source: String,
}

/// API payload used to delete one pipeline by its stable file_rel_path.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DeletePipelineRequest {
    /// Relative path of the pipeline source file under `repo/`.
    pub file_rel_path: String,
}

/// API payload for committing repo changes via git.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct GitCommitRequest {
    /// File paths relative to `repo/` to stage and commit.
    pub files: Vec<String>,
    /// Commit message.
    pub message: String,
    /// Whether to push after committing.
    #[serde(default)]
    pub push: bool,
    /// Credential ID to use for authenticated push (optional).
    pub credential_id: Option<String>,
    /// Remote repository URL for authenticated push (optional).
    pub repo_url: Option<String>,
    /// Branch to push to (optional, defaults to current branch).
    pub branch: Option<String>,
}

/// Request body for `PUT /api/projects/{owner}/{project}/settings/{section}`.
///
/// Wraps the section-specific data alongside a git commit message.
/// The handler writes the section to `zebflow.yaml` then commits the file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateSettingsSectionRequest {
    /// Git commit message. Shown in the commit dialog before save. Sections
    /// stored in `zebflow.yaml` commit with it; instance-side sections
    /// (`addressing`) have nothing to commit and send none.
    #[serde(default)]
    pub commit_message: String,
    /// Section-specific payload. Deserialized per `{section}`.
    pub data: serde_json::Value,
}

/// API payload used to target one pipeline by its stable file path.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PipelineLocateRequest {
    /// Stable file-relative path under `repo/` (e.g. `"pipelines/api/my-hook.zf.json"`).
    pub file_rel_path: String,
}

/// Trigger type used for explicit pipeline execution calls.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PipelineExecuteTrigger {
    Webhook,
    Schedule,
    Manual,
}

/// API payload used to execute one active pipeline with explicit trigger context.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ExecutePipelineRequest {
    /// Stable file-relative path under `repo/` (e.g. `"pipelines/api/my-hook.zf.json"`).
    pub file_rel_path: String,
    /// Trigger mode to validate against active trigger nodes. Optional: when
    /// absent, `manual` is inferred — unless the graph's first trigger is a
    /// webhook, in which case the run is validated as `webhook` against that
    /// trigger's own path and method, as if the caller had spelled them out.
    #[serde(default)]
    pub trigger: Option<PipelineExecuteTrigger>,
    /// Optional webhook path matcher.
    #[serde(default)]
    pub webhook_path: Option<String>,
    /// Optional webhook method matcher.
    #[serde(default)]
    pub webhook_method: Option<String>,
    /// Optional schedule cron matcher.
    #[serde(default)]
    pub schedule_cron: Option<String>,
    /// Request input payload passed to pipeline execution.
    #[serde(default)]
    pub input: serde_json::Value,
}

/// Payload used to create/update one project doc file under `app/docs`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UpsertProjectDocRequest {
    /// Relative path under `app/docs`.
    pub path: String,
    /// Full file content.
    #[serde(default)]
    pub content: String,
}

/// Payload used to create one project docs folder under `repo/docs`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CreateProjectDocFolderRequest {
    /// Relative folder path under `repo/docs`.
    pub path: String,
}

/// Payload used to move one project docs file or folder.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectDocMoveRequest {
    /// Existing relative path under `repo/docs`.
    pub from_path: String,
    /// Destination parent folder under `repo/docs`.
    pub to_parent_path: String,
}

/// One template tree row for the templates workspace.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateTreeItem {
    /// Display name.
    pub name: String,
    /// Relative path under `app/templates`.
    pub rel_path: String,
    /// `folder` or `file`.
    pub kind: String,
    /// Nesting depth from template root.
    pub depth: usize,
    /// File classification for icon/behavior hints.
    pub file_kind: String,
    /// Whether the entry is protected from destructive actions.
    pub is_protected: bool,
}

/// Template workspace listing for one project.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateWorkspaceListing {
    /// Relative path of the preferred initial file.
    pub default_file: Option<String>,
    /// The folder these rows are the contents of. Empty is the repository root.
    ///
    /// Echoed back so a client holding several folders can file the answer
    /// under the right key without remembering what it asked for.
    #[serde(default)]
    pub path: String,
    /// Flattened tree rows in display order.
    pub items: Vec<TemplateTreeItem>,
}

/// Which part of the repository tree a caller wants.
///
/// A sidebar asks for one folder at a time as the reader opens it; the
/// quick-open palette and the pipeline pages ask for all of it. Making that a
/// parameter rather than two endpoints means a screen can change its mind
/// without the server growing a second road.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct RepoTreeScope {
    /// Subtree root relative to `repo/`. Empty is the repository root.
    pub path: String,
    /// Levels to walk below `path`. `None` walks the whole subtree.
    pub depth: Option<usize>,
}

impl RepoTreeScope {
    /// The whole repository, however deep it goes.
    pub fn all() -> Self {
        Self {
            path: String::new(),
            depth: None,
        }
    }

    /// One folder's immediate children — what an expanding sidebar asks for.
    pub fn children_of(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            depth: Some(1),
        }
    }
}

/// One file status row from the project git repository for templates.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateGitStatusItem {
    /// Relative path under `app/templates`.
    pub rel_path: String,
    /// Short git porcelain status such as `M`, `A`, `D`, `??`, or `R`.
    pub code: String,
}

/// Payload used to save one template file.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateSaveRequest {
    /// Relative path under `app/templates`.
    pub rel_path: String,
    /// Full file content.
    pub content: String,
}

/// Supported controlled template creation kinds.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TemplateCreateKind {
    /// `templates/pages/*.tsx`
    Page,
    /// `templates/components/*.tsx`
    Component,
    /// `templates/scripts/*.ts`
    Script,
    /// arbitrary folder inside `templates/`
    Folder,
}

/// Payload used to create one controlled template entry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateCreateRequest {
    /// Creation kind.
    pub kind: TemplateCreateKind,
    /// Human-entered base name.
    pub name: String,
    /// Optional parent folder under `app/templates`.
    pub parent_rel_path: Option<String>,
}

/// Payload used to move one template entry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateMoveRequest {
    /// Existing relative path under `app/templates`.
    pub from_rel_path: String,
    /// Destination parent folder under `app/templates`.
    pub to_parent_rel_path: String,
}

/// Basic template file response used by the web editor.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateFilePayload {
    /// Relative path under `app/templates`.
    pub rel_path: String,
    /// Display filename.
    pub name: String,
    /// File classification.
    pub file_kind: String,
    /// Full file content.
    pub content: String,
    /// Line count.
    pub line_count: usize,
    /// Whether the entry is protected from destructive actions.
    pub is_protected: bool,
}

/// Request payload used to compile one current template buffer.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateCompileRequest {
    /// Relative path under `app/templates`.
    pub rel_path: String,
    /// Unsaved editor content to compile.
    pub content: String,
}

/// One platform-facing template compile diagnostic.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateDiagnostic {
    /// Stable diagnostic code.
    pub code: String,
    /// Human-readable message.
    pub message: String,
    /// `error` or `warning`.
    pub severity: String,
    /// Optional zero-based source start offset.
    pub from: Option<usize>,
    /// Optional zero-based source end offset.
    pub to: Option<usize>,
}

/// Compile result returned to the web editor.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TemplateCompileResponse {
    /// Whether compile completed without a hard failure.
    pub ok: bool,
    /// Diagnostics emitted by the compile path.
    pub diagnostics: Vec<TemplateDiagnostic>,
}

/// One attribute definition in a Simple Table collection schema.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CollectionAttribute {
    /// Field name (slug).
    pub name: String,
    /// Data kind: `string` | `number` | `boolean` | `text` | `json` | `vector` | `geo`.
    pub kind: String,
    /// Active index types: `hash` | `range` | `fulltext` | `vector` | `spatial`.
    #[serde(default)]
    pub index_types: Vec<String>,
    /// Two rows may not hold the same value here (`UNIQUE`); NULLs never collide.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub unique: bool,
    /// The SQL type as the database declared it (`INT`, `TIMESTAMPTZ`,
    /// `GEOMETRY(Point,4326)`, `VECTOR(384)`), when it reports one. It is
    /// what a table recreated from the schema document is declared with;
    /// `kind` is the coarse family the Studio reasons about.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub declared: String,
    /// The column's `DEFAULT` expression as declared (`'pending'`, `now()`).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub default: String,
    /// `NOT NULL`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub not_null: bool,
    /// This column is the table's named primary key (`id TEXT PRIMARY KEY`),
    /// standing in for `_key`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub primary_key: bool,
}

/// One managed Simple Table definition stored inside the project runtime DB.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct SimpleTableDefinition {
    /// Stable table slug.
    pub table: String,
    /// Backing collection name.
    pub collection: String,
    /// Attribute schema definitions.
    #[serde(default)]
    pub attributes: Vec<CollectionAttribute>,
    /// Hash indexed payload fields (exact equality).
    #[serde(default)]
    pub hash_indexed_fields: Vec<String>,
    /// Range indexed payload fields (ordered scans).
    #[serde(default)]
    pub range_indexed_fields: Vec<String>,
    /// Full-text indexed payload fields.
    #[serde(default)]
    pub fulltext_fields: Vec<String>,
    /// Vector indexed payload fields (semantic similarity).
    #[serde(default)]
    pub vector_fields: Vec<String>,
    /// Spatial indexed payload fields (geo queries).
    #[serde(default)]
    pub spatial_fields: Vec<String>,
    /// Live row count.
    pub row_count: usize,
    /// The `DEFAULT` of `_key` itself (`ulid()`, `uuid4()`), when the table
    /// mints its keys and names no key column of its own.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub key_default: String,
    /// Named schema the table lives in; empty for the default (`public`).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub schema: String,
    /// Present when the table is an edge table: a view over a property
    /// graph's own edges rather than a table of rows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edge: Option<EdgeTableDefinition>,
}

/// What makes a table an edge table: the rows its edges join, the key that
/// decides how many edges one pair may have, and the graph that declares it.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct EdgeTableDefinition {
    /// Each `REFERENCES` column and the table it names.
    #[serde(default)]
    pub references: Vec<EdgeTableReference>,
    /// Primary key columns; empty for a table without one.
    #[serde(default)]
    pub key: Vec<String>,
    /// Source column and its table.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub source: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub source_table: String,
    /// Destination column and its table.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub destination: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub destination_table: String,
    /// The label its edges carry.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub label: String,
    /// The property graph that declares it; empty when none does.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub graph: String,
}

/// One `REFERENCES` column of an edge table.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct EdgeTableReference {
    pub column: String,
    pub table: String,
}

/// One generation of the credential encryption keyring.
///
/// Never carries key material — only which generations exist and which one new
/// writes use. The instance key is not in the catalog and is not in any API.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CredentialKeyGeneration {
    /// The number every `zfc1:<key_id>:…` envelope written under it names.
    pub key_id: u32,
    /// When this generation was minted.
    pub created_at: i64,
    /// Whether new writes use it.
    pub current: bool,
}

/// The state of this instance's credential encryption keyring.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CredentialKeyringReport {
    /// `file` or `environment` — where the instance key came from.
    pub source: String,
    /// Where the instance key file is, whether or not it is the source in use.
    pub key_file: String,
    /// The generation new writes use.
    pub current_key_id: u32,
    /// Every generation, oldest first.
    pub generations: Vec<CredentialKeyGeneration>,
}

/// What a re-encryption sweep did.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CredentialSweepReport {
    /// Generation everything now sits under.
    pub key_id: u32,
    /// Credentials looked at.
    pub examined: usize,
    /// Credentials rewritten under [`Self::key_id`].
    pub rewritten: usize,
    /// Of those, ones that had been stored as plaintext before this release.
    pub migrated_from_plaintext: usize,
    /// Whether the catalog file was rebuilt afterwards.
    ///
    /// Re-encrypting a row overwrites the *row*; SQLite keeps the page the old
    /// bytes were on until it reuses it, and a WAL frame keeps them longer
    /// still. That is invisible to every query and perfectly visible to
    /// `strings catalog.db`, which is the exact reader this feature exists to
    /// defeat — so the sweep checkpoints and `VACUUM`s. Best effort: a rebuild
    /// that could not take the lock leaves the re-encryption done and says so
    /// here rather than failing the operation.
    pub compacted: bool,
}

/// Create payload for one project credential.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UpsertProjectCredentialRequest {
    /// Stable credential id.
    pub credential_id: String,
    /// Display title.
    pub title: String,
    /// Driver/kind (`postgres`, `openai`, ...).
    pub kind: String,
    /// Secret payload.
    #[serde(default)]
    pub secret: serde_json::Value,
    /// Optional freeform notes.
    #[serde(default)]
    pub notes: String,
}

/// Create/update payload for one project DB connection.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UpsertProjectDbConnectionRequest {
    /// Stable route slug.
    pub connection_slug: String,
    /// Display label.
    pub connection_label: String,
    /// Database kind (`sqlite`, `postgresql`, ...).
    pub database_kind: String,
    /// Optional linked credential id.
    pub credential_id: Option<String>,
    /// Optional kind-specific config payload.
    #[serde(default)]
    pub config: serde_json::Value,
}

/// Create/update payload for one project assistant config.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UpsertProjectAssistantConfigRequest {
    /// Credential id for high-level reasoning/planning model.
    pub llm_high_credential_id: Option<String>,
    /// Credential id for general/cheap model.
    pub llm_general_credential_id: Option<String>,
    /// Max execution steps per request.
    pub max_steps: Option<u32>,
    /// Max replan attempts.
    pub max_replans: Option<u32>,
    /// Whether assistant is enabled for this project.
    pub enabled: Option<bool>,
    /// Number of user+assistant pairs to persist as server-side chat history.
    pub chat_history_pairs: Option<u32>,
}

/// Test payload for one project DB connection (existing or draft).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TestProjectDbConnectionRequest {
    /// Existing connection slug to test.
    pub connection_slug: Option<String>,
    /// Optional draft database kind (used when slug is not provided).
    pub database_kind: Option<String>,
    /// Optional draft credential id (used when slug is not provided).
    pub credential_id: Option<String>,
    /// Optional draft config payload.
    #[serde(default)]
    pub config: serde_json::Value,
}

/// Describe payload for one DB connection runtime endpoint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct DescribeProjectDbConnectionRequest {
    /// Describe scope (`tree`, `schemas`, `tables`, `functions`, `columns`).
    pub scope: Option<String>,
    /// Optional schema filter.
    pub schema: Option<String>,
    /// Filter to a specific table for column-level detail.
    /// Format: "schema.table" (e.g. "academic.staff") or just "table" for public schema.
    /// When set, scope is treated as "columns" automatically.
    #[serde(default)]
    pub table: Option<String>,
    /// Whether system schemas should be included when supported.
    pub include_system: Option<bool>,
}

/// One node in DB object tree.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DbObjectNode {
    /// Object kind (`schema`, `table`, `function`).
    pub kind: String,
    /// Object name.
    pub name: String,
    /// Optional schema name.
    pub schema: Option<String>,
    /// Optional children.
    #[serde(default)]
    pub children: Vec<DbObjectNode>,
    /// Optional metadata.
    #[serde(default)]
    pub meta: serde_json::Value,
}

/// One column type an engine actually offers.
///
/// The studio's type picker is built from these, so a PostgreSQL column is
/// declared `int4` or `timestamptz` — the engine's own words — rather than a
/// generic kind that has to be translated twice and loses meaning both ways.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DbTypeDef {
    /// The name written into DDL, lowercase (`varchar`, `int4`, `jsonb`).
    pub name: String,
    /// Grouping for the picker and the column icon.
    pub family: DbTypeFamily,
    /// Whether the type takes arguments, as `varchar(255)` or `numeric(10,2)`.
    pub parameterized: bool,
    /// Shown beside the name where the name alone is cryptic.
    pub note: String,
}

/// What a column type is for. Drives the picker's grouping and the icon the
/// column grid shows, and is the granularity at which a type change is judged
/// safe or refused.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum DbTypeFamily {
    #[default]
    Text,
    Number,
    Boolean,
    Json,
    DateTime,
    Uuid,
    Binary,
    Geometry,
    Vector,
    Other,
}

/// What one database engine supports, declared by its driver.
///
/// The data-management UI renders panels from this and never branches on
/// `database_kind`. Adding an engine is writing a driver, not editing the UI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DbCapabilities {
    /// Rows can be edited in place in the grid.
    pub inline_edit: bool,
    /// Tables can be created from the UI.
    pub create_table: bool,
    /// Tables can be dropped from the UI.
    pub drop_table: bool,
    /// The engine exposes a health/sync/compact surface.
    pub maintenance: bool,
    /// The engine namespaces tables under schemas.
    pub schemas: bool,
    /// Attributes and index kinds can be edited after a table exists.
    pub edit_table_properties: bool,
    /// The column that identifies one row, for editing and deletion.
    ///
    /// Sekejap answers `_key`; SQL engines answer the primary key this
    /// platform creates. The studio reads this rather than assuming a name,
    /// because a row it cannot address is a row it cannot change.
    pub row_identity: String,
    /// The row identity is not among `*`'s columns, so a statement that
    /// wants it names it: sekejap's `_key` is a system column, where a SQL
    /// engine's key column is an ordinary one.
    #[serde(default)]
    pub row_identity_hidden: bool,
    /// The table writer applies NOT NULL, DEFAULT and UNIQUE as a column
    /// declares them. Where it does not, the studio shows them disabled
    /// rather than accept values it would drop.
    #[serde(default)]
    pub column_constraints: bool,
    /// The generators a table's key may be declared with (`ulid()`), so an
    /// INSERT may leave the key out. Empty where the engine has none.
    #[serde(default)]
    pub key_defaults: Vec<String>,
    /// The engine can store and return geometry.
    pub geo: bool,
    /// How this engine relates rows to each other.
    pub relations: DbRelationStyle,
}

impl Default for DbCapabilities {
    /// The conservative set: read and query only.
    ///
    /// A new driver that declares nothing gets a working read-only surface
    /// rather than buttons that fail when pressed.
    fn default() -> Self {
        Self {
            inline_edit: false,
            create_table: false,
            drop_table: false,
            maintenance: false,
            schemas: false,
            edit_table_properties: false,
            row_identity: String::new(),
            row_identity_hidden: false,
            column_constraints: false,
            key_defaults: Vec::new(),
            geo: false,
            relations: DbRelationStyle::None,
        }
    }
}

/// How an engine expresses relationships between rows.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum DbRelationStyle {
    /// No relationship surface.
    #[default]
    None,
    /// Declared foreign keys, as in SQL engines.
    ForeignKey,
    /// Free edges between rows, as in sekejap.
    Graph,
}

/// Describe result for one DB connection.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProjectDbConnectionDescribeResult {
    /// Stable connection id.
    pub connection_id: String,
    /// Stable route slug.
    pub connection_slug: String,
    /// Database kind (`sqlite`, `postgresql`, ...).
    pub database_kind: String,
    /// Effective scope.
    pub scope: String,
    /// What this engine supports. Stamped by the runtime from the driver, so a
    /// driver cannot forget to report it.
    #[serde(default)]
    pub capabilities: DbCapabilities,
    /// Object tree/list payload.
    #[serde(default)]
    pub nodes: Vec<DbObjectNode>,
}

/// Query payload for one DB connection runtime endpoint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct QueryProjectDbConnectionRequest {
    /// SQL text (for SQL engines like PostgreSQL).
    #[serde(default)]
    pub sql: String,
    /// Positional bind parameters.
    #[serde(default)]
    pub params: Vec<serde_json::Value>,
    /// Optional table identifier for engines that do not use SQL directly.
    pub table: Option<String>,
    /// Optional max rows to return.
    pub limit: Option<usize>,
    /// Whether write statements are blocked (defaults true).
    pub read_only: Option<bool>,
}

/// One query result column.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DbQueryColumn {
    /// Column name.
    pub name: String,
    /// Optional engine-native data type.
    pub data_type: Option<String>,
}

/// Query result for one DB connection.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProjectDbConnectionQueryResult {
    /// Stable connection id.
    pub connection_id: String,
    /// Stable route slug.
    pub connection_slug: String,
    /// Database kind (`sqlite`, `postgresql`, ...).
    pub database_kind: String,
    /// Returned columns.
    #[serde(default)]
    pub columns: Vec<DbQueryColumn>,
    /// Returned rows as column-aligned vectors.
    #[serde(default)]
    pub rows: Vec<Vec<serde_json::Value>>,
    /// Number of rows in this payload.
    pub row_count: usize,
    /// Whether payload was truncated due to row limit.
    pub truncated: bool,
    /// Optional affected rows for write statements.
    pub affected_rows: Option<u64>,
    /// Query execution duration in milliseconds.
    pub duration_ms: u64,
}

/// Result payload returned by DB connection test endpoint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProjectDbConnectionTestResult {
    /// Whether test passed.
    pub ok: bool,
    /// Human-friendly message.
    pub message: String,
    /// Optional details.
    pub details: serde_json::Value,
}

/// Create payload for one Simple Table.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CreateSimpleTableRequest {
    /// Stable table slug.
    pub table: String,
    /// Attribute schema definitions.
    #[serde(default)]
    pub attributes: Vec<CollectionAttribute>,
    /// Hash indexed payload fields.
    #[serde(default)]
    pub hash_indexed_fields: Vec<String>,
    /// Range indexed payload fields.
    #[serde(default)]
    pub range_indexed_fields: Vec<String>,
    /// `_key`'s generator (`ulid()` / `uuid4()`), for a table that mints its
    /// own keys; one of the driver's `key_defaults`, or empty.
    #[serde(default)]
    pub key_default: String,
    /// Present when the new table is an edge table: which column holds each
    /// end, which table each end reaches, and its label.
    #[serde(default)]
    pub edge: Option<CreateEdgeTableRequest>,
}

/// The edge-table part of a create request. The two end columns are made by
/// the create itself, ahead of the table's own columns, which become the
/// edges' properties.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CreateEdgeTableRequest {
    /// The column holding the source row's key.
    pub source: String,
    /// The table the source column references (`members`, `geo.places`).
    pub source_table: String,
    /// The column holding the destination row's key.
    pub destination: String,
    /// The table the destination column references.
    pub destination_table: String,
    /// The label the edges carry; the table's own name when empty.
    #[serde(default)]
    pub label: String,
    /// One edge per source and destination pair: the two ends are the key.
    #[serde(default)]
    pub one_per_pair: bool,
}

/// Update payload for an existing sekejap table (attributes + indexes).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct UpdateSimpleTableRequest {
    /// New attribute schema definitions (replaces existing).
    #[serde(default)]
    pub attributes: Vec<CollectionAttribute>,
    /// Hash indexed payload fields.
    #[serde(default)]
    pub hash_indexed_fields: Vec<String>,
    /// Range indexed payload fields.
    #[serde(default)]
    pub range_indexed_fields: Vec<String>,
}

/// Upsert payload for one Simple Table row.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UpsertSimpleTableRowRequest {
    /// Target table slug.
    pub table: String,
    /// Stable row id within the table.
    pub row_id: String,
    /// Row payload.
    #[serde(default)]
    pub data: serde_json::Value,
}

/// Query payload for one Simple Table read.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SimpleTableQueryRequest {
    /// Target table slug.
    pub table: String,
    /// Optional equality field name.
    pub where_field: Option<String>,
    /// Equality field value.
    pub where_value: Option<serde_json::Value>,
    /// Maximum rows to return.
    #[serde(default = "default_simple_table_limit")]
    pub limit: usize,
}

fn default_simple_table_limit() -> usize {
    100
}

/// Query result returned by project Simple Table management and nodes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SimpleTableQueryResult {
    /// Table definition.
    pub table: SimpleTableDefinition,
    /// Returned rows.
    pub rows: Vec<serde_json::Value>,
}

/// File-system tree returned for one project.
///
/// `data/` splits into four tiers (`project-directory.md` §3), and every tier
/// below `data_dir` is an accessor derived from it — the same pattern
/// `repo_source_dir()` and the other `repo_*` methods already use for `repo/`
/// — rather than a separately stored field, so there is exactly one place
/// that can disagree with the tree the contract draws.
#[derive(Debug, Clone)]
pub struct ProjectFileLayout {
    /// `{data_root}/users/{owner}/{project}`
    pub root: PathBuf,
    /// `.../data`
    pub data_dir: PathBuf,
    /// `.../files`
    pub files_dir: PathBuf,
    /// `.../repo` (git-sync workspace root).
    pub repo_dir: PathBuf,
    /// `.../repo/.git`
    pub repo_git_dir: PathBuf,
    /// `.../repo/zebflow.yaml` (non-sensitive project configuration, git-synced).
    pub project_config_file: PathBuf,
    /// The repository layout these paths project onto disk.
    ///
    /// Every directory inside `repo/` is derived from this rather than stored
    /// beside it, so an absolute path and the repository-relative rule that
    /// names it cannot disagree.
    pub repo_layout: ResolvedProjectLayout,
    /// The native store that owns this project's files: `spec.files.backend`
    /// resolved once, with everything opening it needs — the `files/`
    /// directory, or the bucket and the credential the instance selected for
    /// it (`data/store/files-backend.json`). Resolved here so that
    /// `open_files` cannot fail.
    pub file_store: FileStore,
    /// The id of that store: `local`, or the id of the `s3` credential that
    /// reaches the bucket. What a node saves as `--store` and a FileRef
    /// carries as `store`.
    pub file_store_id: String,
}

impl ProjectFileLayout {
    /// Opens the native store that owns this project's files.
    ///
    /// Every caller that needs a project's bytes goes through here rather than
    /// naming an implementation, so a second backend is added in
    /// [`crate::zebfs::backend::open`] and nowhere else.
    pub fn open_files(&self) -> ZebFs {
        crate::zebfs::backend::open(&self.file_store)
    }

    /// The declared word for this project's store — what every FileRef written
    /// here carries in `backend`.
    pub fn file_backend(&self) -> FileBackend {
        self.file_store.backend()
    }

    /// The id of the project's default store.
    pub fn store_id(&self) -> &str {
        &self.file_store_id
    }

    /// `.../repo/{source}` — unified source root: *.zf.json pipelines + *.tsx
    /// templates + *.ts scripts. Also the `@/` root for the RWE compiler.
    pub fn repo_source_dir(&self) -> PathBuf {
        self.repo_dir.join(&self.repo_layout.source)
    }

    /// `.../repo/{assets}` — files served under `/static/{owner}/{project}/...`.
    pub fn repo_static_dir(&self) -> PathBuf {
        self.repo_dir.join(&self.repo_layout.r#static)
    }

    /// `.../repo/{docs}` (project docs: ERD, README.md, use cases, etc.).
    pub fn repo_docs_dir(&self) -> PathBuf {
        self.repo_dir.join(&self.repo_layout.docs)
    }

    /// `.../repo/{node_interfaces}` — interfaces of the third-party nodes this
    /// project uses.
    ///
    /// These are `NodeDefinition` documents, not bundles. They let a graph stay
    /// readable and reimplementable on an instance where the bundle is absent.
    pub fn repo_node_interfaces_dir(&self) -> PathBuf {
        self.repo_dir.join(&self.repo_layout.node_interfaces)
    }

    /// `.../data/store` — durable, generated, irreplaceable. Back this up.
    pub fn data_store_dir(&self) -> PathBuf {
        self.data_dir.join("store")
    }

    /// `.../data/store/sekejap` — the project's database: WAL, indexes, snapshot.
    pub fn data_store_sekejap_dir(&self) -> PathBuf {
        self.data_store_dir().join(crate::platform::sekejap::STORE_DIR)
    }

    /// `.../data/store/local.db` — the project's SQLite runtime database.
    pub fn data_store_local_db_file(&self) -> PathBuf {
        self.data_store_dir().join("local.db")
    }

    /// `.../data/store/kv.db` — the project's durable `kv.*` state.
    ///
    /// `MemStateBus` (`src/infra/io/state/mem.rs`) builds this path itself
    /// from the data root because infra cannot see this type; the two sites
    /// are named in `project-directory.md` §5 so a layout change updates both.
    pub fn data_store_kv_db_file(&self) -> PathBuf {
        self.data_store_dir().join("kv.db")
    }

    /// `.../data/store/chat_history.json` — the project's assistant
    /// conversation history. User state, not cache: deleting it loses a
    /// conversation, so it lives in the `store` tier.
    pub fn data_store_chat_history_file(&self) -> PathBuf {
        self.data_store_dir().join("chat_history.json")
    }

    /// `.../data/store/assistant` — per-user assistant state.
    pub fn data_store_assistant_dir(&self) -> PathBuf {
        self.data_store_dir().join("assistant")
    }

    /// `.../data/store/assistant/{user_id}/memory.md` — one user's assistant
    /// memory. Machine-written by the assistant, irreplaceable, so `store`
    /// tier — deleting it loses everything the assistant learned.
    ///
    /// The format stays markdown: every reader and writer (MCP
    /// `docs_agent_read`/`docs_agent_write`, the assistant chat tools, the
    /// system-prompt embed) speaks markdown under the `MEMORY.md` doc name.
    /// Only the tier and the per-user keying changed with the move out of
    /// `data/cache/agent_docs/`.
    pub fn data_store_assistant_memory_file(&self, user_id: &str) -> PathBuf {
        self.data_store_assistant_dir()
            .join(slug_segment(user_id))
            .join("memory.md")
    }

    /// `.../data/cache` — disposable, rebuilds from `repo/`.
    pub fn data_cache_dir(&self) -> PathBuf {
        self.data_dir.join("cache")
    }

    /// `.../data/cache/pipelines` — materialized pipeline runtime (active
    /// snapshots compiled from `repo/`).
    pub fn data_cache_pipelines_dir(&self) -> PathBuf {
        self.data_cache_dir().join("pipelines")
    }

    /// `.../data/cache/agent_docs` (AGENTS.md, SOUL.md — agent context.
    /// MEMORY moved to the `store` tier: [`Self::data_store_assistant_memory_file`]).
    pub fn data_cache_agent_docs_dir(&self) -> PathBuf {
        self.data_cache_dir().join("agent_docs")
    }

    /// `.../data/cache/mapserver-artifacts` — generated map layer artifacts
    /// (chunked NDJSON + manifest per layer, `{instance}/{layer}/`). The
    /// engine builds them from the uploaded source in `files/mapserver/`, so
    /// they regenerate: CACHE, not OBJECT.
    pub fn data_cache_mapserver_artifacts_dir(&self) -> PathBuf {
        self.data_cache_dir().join("mapserver-artifacts")
    }

    /// First-touch tier move of `files/mapserver/.artifacts` onto its cache
    /// home `data/cache/mapserver-artifacts` (`instance-directory.md`). One
    /// atomic whole-directory rename; both-paths-present refuses rather than
    /// guesses, per `migrate_tier_entry`. Returns the cache root.
    pub fn ensure_mapserver_artifacts_home(&self) -> std::io::Result<PathBuf> {
        let new_root = self.data_cache_mapserver_artifacts_dir();
        crate::infra::io::durable::migrate_tier_entry(
            &self.files_dir.join("mapserver").join(".artifacts"),
            &new_root,
        )?;
        Ok(new_root)
    }

    /// Resolves a layer record's `artifact_manifest_path`
    /// (`mapserver-artifacts/{instance}/{layer}/manifest.json`) under the
    /// cache root. Any other shape, or one climbing out, is `None`: the path
    /// arrives in a registry a bundle may carry, and its parent is what a
    /// delete removes.
    pub fn resolve_mapserver_artifact_path(&self, rel: &str) -> Option<PathBuf> {
        let rest = rel.strip_prefix("mapserver-artifacts/")?;
        if !crate::contracts::kinds::valid_artifact_rest(rest) {
            return None;
        }
        Some(self.data_cache_mapserver_artifacts_dir().join(rest))
    }

    /// `.../data/hub` — the INSTALLED tier: content unpacked from a hub or a
    /// local document (`instance-directory.md`). Removal is `uninstall`,
    /// recorded in `zeb.lock` — never a cleanup.
    pub fn data_hub_dir(&self) -> PathBuf {
        self.data_dir.join("hub")
    }

    /// `.../data/hub/nodes` — installed node bundles.
    ///
    /// These are materialized from `zeb.lock`, not authored, so they live with
    /// the machine's other derived state rather than in the source repository.
    /// A locked bundle's `entry` (`nodes/{slug}/definition.json`) resolves
    /// against [`Self::data_hub_dir`], so the recorded string survives the
    /// move from the pre-contract `data/nodes` home unchanged.
    pub fn data_hub_nodes_dir(&self) -> PathBuf {
        self.data_hub_dir().join("nodes")
    }

    /// `.../data/hub/rwe-libraries` — installed RWE libraries.
    ///
    /// Drawn by `instance-directory.md`; the writer arrives with library
    /// seeding. Scaffolded empty until then so the tree matches the contract.
    pub fn data_hub_rwe_libraries_dir(&self) -> PathBuf {
        self.data_hub_dir().join("rwe-libraries")
    }

    /// `.../data/recovery` — disposable, bounded. Migration safety copies,
    /// named with the date the migration ran (`project-directory.md` §5).
    pub fn data_recovery_dir(&self) -> PathBuf {
        self.data_dir.join("recovery")
    }

    /// `.../data/logs` — disposable, bounded. Invocation records, traces.
    pub fn data_logs_dir(&self) -> PathBuf {
        self.data_dir.join("logs")
    }
}

// ── Node package system ─────────────────────────────────────────────────────

/// Implementation type of one node in a bundle.
///
/// This is always derived from the node's [`RunBinding`]. It is never authored,
/// so a bundle cannot declare an implementation that disagrees with the artifact
/// the node actually points at.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NodePackageSource {
    /// Composite node: the behavior is a function pipeline.
    Composite,
    /// WASM node: the behavior is an export in a compiled module.
    Wasm,
    /// Trigger node with no user code; the event payload passes through.
    Declarative,
}

impl NodePackageSource {
    /// Stable string used by the node API and UI.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Composite => "composite",
            Self::Wasm => "wasm",
            Self::Declarative => "declarative",
        }
    }
}

/// One compiled WASM artifact declared by a bundle.
///
/// The ABI belongs to the module because a bundle may carry artifacts compiled
/// at different times.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct WasmModuleSpec {
    /// Package-relative path of the module (e.g. `"wasm/ml.wasm"`).
    pub path: String,
    /// ABI identifier. Only `zebflow-wasm-json-v1` is accepted under v1.
    pub abi: String,
}

/// Where one node's code lives.
///
/// Exactly one form is valid: `function` names a key in `spec.functions`, or
/// `module` plus `export` names a key in `spec.modules` and a symbol inside it.
/// `export` is never optional, because a default symbol would make two WASM
/// nodes in one bundle resolve to the same entry point.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct RunBinding {
    /// Composite form: a key in `spec.functions`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub function: Option<String>,
    /// WASM form: a key in `spec.modules`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub module: Option<String>,
    /// WASM form: the exported symbol to call.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub export: Option<String>,
}

impl RunBinding {
    /// Implementation type implied by this binding, if it is well formed.
    pub fn source(&self) -> Option<NodePackageSource> {
        match (&self.function, &self.module, &self.export) {
            (Some(_), None, None) => Some(NodePackageSource::Composite),
            (None, Some(_), Some(_)) => Some(NodePackageSource::Wasm),
            _ => None,
        }
    }
}

/// Runtime-normalized manifest for one node from an installed `definition.json` bundle.
///
/// This is not an authoring or disk format. The registry derives it from the
/// canonical [`MultiNodePackageDefinition`] and uses it uniformly for composite
/// and WASM execution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct NodePackageManifest {
    /// Implementation type, derived from `run`.
    pub source: NodePackageSource,
    /// `spec.package` of the bundle providing this node.
    ///
    /// Carried per node because the runtime resolves a manifest by kind and
    /// otherwise could not name the bundle a refusal came from.
    #[serde(default)]
    pub package: String,
    /// Package release version.
    pub version: String,
    /// External hosts the providing bundle declared in `spec.hosts`.
    ///
    /// Copied from the package because egress is enforced where a node runs,
    /// and the only thing in hand there is the manifest for one kind.
    #[serde(default)]
    pub hosts: Vec<String>,
    /// The node definition (same struct as native nodes).
    pub definition: crate::pipeline::NodeDefinition,
    /// Credential type definitions this node declares through `uses_credentials`.
    #[serde(default)]
    pub credentials: Vec<CredentialTypeDef>,
    /// Where this node's code lives. Absent only for a declarative trigger.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run: Option<RunBinding>,
    /// Trigger role configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<PackageTriggerConfig>,
    /// Lifecycle hooks. Valid only on a trigger node.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lifecycle: Option<PackageLifecycleConfig>,
    /// Function name → package-relative pipeline path.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub functions: BTreeMap<String, String>,
    /// Module name → compiled WASM artifact.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub modules: BTreeMap<String, WasmModuleSpec>,
}

impl NodePackageManifest {
    /// Name of the composite function this node runs, if it is a composite node.
    pub fn main_function(&self) -> Option<&str> {
        self.run.as_ref()?.function.as_deref()
    }

    /// Resolves the WASM module and export this node runs, if it is a WASM node.
    pub fn wasm_target(&self) -> Option<(&WasmModuleSpec, &str)> {
        let run = self.run.as_ref()?;
        let module = run.module.as_deref()?;
        let export = run.export.as_deref()?;
        Some((self.modules.get(module)?, export))
    }
}

/// Trigger role configuration for a node that starts a pipeline.
///
/// This declares a role, not an implementation. The inbound handler is the
/// node's `run` binding, which is why a WASM trigger is expressible.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct PackageTriggerConfig {
    /// Trigger type: "webhook", "ws", "ws_client", "cron".
    #[serde(rename = "type")]
    pub trigger_type: String,
    /// Webhook path template with `{{ config_key }}` placeholders.
    /// E.g. `"/tg/{{ credential_id }}"` resolves from node config.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_template: Option<String>,
    /// A webhook trigger whose sender proves itself with a shared secret in a
    /// header: every inbound request must carry `header` equal to the
    /// node's credential value named by `placeholder`, or it is refused
    /// before any run. Activation generates the value when the credential
    /// has none, so the lifecycle hook can hand it to the sender.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secret_header: Option<PackageTriggerSecretHeader>,
}

/// The header a webhook trigger's sender proves itself with, and the
/// credential placeholder holding the expected value.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct PackageTriggerSecretHeader {
    /// Header name, e.g. `X-Telegram-Bot-Api-Secret-Token`.
    pub header: String,
    /// A placeholder one of the node's credentials declares, e.g.
    /// `WEBHOOK_SECRET`.
    pub placeholder: String,
}

/// Lifecycle hooks for a trigger node. Each hook is a run binding, so composite
/// and WASM nodes have the same lifecycle capability.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
pub struct PackageLifecycleConfig {
    /// Runs when a pipeline using this trigger is activated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_activate: Option<RunBinding>,
    /// Runs when a pipeline using this trigger is deactivated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_deactivate: Option<RunBinding>,
}

/// Multi-node package definition (`definition.json` format).
///
/// A single file declaring N nodes, shared credentials, and reusable function pipelines.
/// The loader explodes this into N `NodePackageManifest` entries.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct MultiNodePackageDefinition {
    /// Package identifier. Owns the `x.{package_token}.` kind namespace.
    pub package: String,
    /// Release version, `major.minor.patch`.
    pub version: String,
    /// Human-readable title.
    pub title: String,
    /// Package description.
    #[serde(default)]
    pub description: String,
    /// Package-level icon path.
    #[serde(default)]
    pub icon: String,
    /// Credential kinds this package can use. Nodes opt in per entry.
    #[serde(default)]
    pub credentials: Vec<CredentialTypeDef>,
    /// External hosts this package is allowed to contact.
    ///
    /// Enforced at run time by [`crate::pipeline::security::BundleEgress`] over
    /// everything a bundle-provided node runs, inner nodes of a composite
    /// included. A non-empty list is an allowlist; an empty one restricts no
    /// host, because `#[serde(default)]` makes absent and empty the same bytes
    /// and a deny-all reading would break every bundle published before
    /// enforcement existed.
    ///
    /// Declaring nothing is not a way out. Every other guard the policy carries
    /// — refusing a node whose destination the guard cannot read — applies to a
    /// bundle that declared nothing exactly as it does to one that declared.
    #[serde(default)]
    pub hosts: Vec<String>,
    /// Function name → package-relative pipeline path.
    #[serde(default)]
    pub functions: BTreeMap<String, String>,
    /// Module name → compiled WASM artifact.
    #[serde(default)]
    pub modules: BTreeMap<String, WasmModuleSpec>,
    /// Node entries.
    pub nodes: Vec<MultiNodeEntry>,
}

/// A single node entry within a multi-node package.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct MultiNodeEntry {
    /// Node kind. Must be `x.{package_token}.{noun}.{verb}`.
    pub kind: String,
    /// Node title.
    pub title: String,
    /// Node description.
    #[serde(default)]
    pub description: String,
    /// Per-node icon path (relative to package).
    #[serde(default)]
    pub icon: String,
    /// UI category for Project Studio node picker.
    #[serde(default)]
    pub ui_category: String,
    /// UI category label.
    #[serde(default)]
    pub ui_category_label: String,
    /// Credential kinds this node uses, declared in `spec.credentials`.
    #[serde(default)]
    pub uses_credentials: Vec<String>,
    /// Where this node's code lives. Required unless the node is a trigger.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run: Option<RunBinding>,
    /// Trigger role configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<PackageTriggerConfig>,
    /// Lifecycle hooks. Valid only alongside `trigger`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lifecycle: Option<PackageLifecycleConfig>,
    /// Node definition (pins, schema, fields, layout, dsl_flags).
    pub definition: MultiNodeEntryDefinition,
}

/// Partial node definition within a multi-node entry.
/// The full `NodeDefinition` is constructed by the loader, filling in kind/title/description
/// from the parent `MultiNodeEntry`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct MultiNodeEntryDefinition {
    #[serde(default)]
    pub input_pins: Vec<String>,
    #[serde(default)]
    pub output_pins: Vec<String>,
    #[serde(default)]
    pub config_schema: serde_json::Value,
    #[serde(default)]
    pub input_schema: serde_json::Value,
    #[serde(default)]
    pub output_schema: serde_json::Value,
    #[serde(default)]
    pub examples: Vec<crate::pipeline::NodeExample>,
    #[serde(default)]
    pub failure_semantics: Vec<crate::pipeline::NodeFailureSemantic>,
    #[serde(default)]
    pub fields: Vec<crate::pipeline::NodeFieldDef>,
    #[serde(default)]
    pub layout: Vec<crate::pipeline::model::LayoutItem>,
    #[serde(default)]
    pub dsl_flags: Vec<crate::pipeline::model::DslFlag>,
    /// One profile per `--provider` word (`node-conventions.md` §11).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub profiles: Vec<crate::pipeline::model::ProviderProfile>,
}

/// Runtime-enriched entry for an installed node package.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstalledNodePackage {
    /// The slug (directory name under `data/hub/nodes/`).
    pub slug: String,
    /// Owner this package belongs to.
    pub owner: String,
    /// Project this package belongs to.
    pub project: String,
    /// Parsed manifest.
    pub manifest: NodePackageManifest,
    /// Absolute path to the package directory on disk.
    pub package_dir: String,
    /// Validated package-relative icon path for this node.
    pub icon_rel_path: Option<String>,
}

/// Request payload for user creation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateUserRequest {
    /// Target owner/user id.
    pub owner: String,
    /// Password.
    pub password: String,
    /// Role.
    #[serde(default = "default_member_role")]
    pub role: String,
    /// Display name for git commits.
    #[serde(default)]
    pub git_name: String,
    /// Email for git commits.
    #[serde(default)]
    pub git_email: String,
}

/// Self-service user settings payload.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct UpdateUserSettingsRequest {
    /// Display name for git commits.
    #[serde(default)]
    pub git_name: String,
    /// Email for git commits.
    #[serde(default)]
    pub git_email: String,
}

fn default_member_role() -> String {
    "member".to_string()
}

/// Source used to resolve one git author identity.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum GitIdentitySource {
    UserProfile,
    ProjectSettings,
    Fallback,
}

/// Concrete git identity chosen for one write action.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ResolvedGitIdentity {
    /// Resolved git author/committer name.
    pub name: String,
    /// Resolved git author/committer email.
    pub email: String,
    /// Source from which the identity was resolved.
    pub source: GitIdentitySource,
}

/// Runtime view of project configuration loaded from `repo/zebflow.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJson {
    #[serde(default)]
    pub metadata: ZebflowJsonMetadata,
    #[serde(default)]
    pub configs: ZebflowJsonConfigs,
    #[serde(default)]
    pub distribution: ZebflowJsonDistribution,
}

fn default_max_asset_size_mb() -> u32 {
    10
}

fn default_webhook_body_max_mb() -> u32 {
    100
}

pub const MAX_UPLOAD_SIZE_MB: u32 = 1024;

pub fn default_pipeline_node_timeout_secs() -> u64 {
    30
}

impl Default for ZebflowJson {
    fn default() -> Self {
        Self {
            metadata: ZebflowJsonMetadata::default(),
            configs: ZebflowJsonConfigs::default(),
            distribution: ZebflowJsonDistribution::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonMetadata {
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub description: String,
}

/// Repo-owned activation/bootstrap intent: which pipelines `zebflow.yaml`
/// asks the office to activate once the project's source is in place.
///
/// This is the project's own configuration, not a transfer format. It is read
/// by [`ProjectConfigurationSpec`](crate::contracts::kinds::ProjectConfigurationSpec)
/// and applied by the local repo refresh.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectBootstrapPlan {
    /// Pipeline glob patterns that should auto-activate after clone/import.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub activate: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonConfigs {
    /// Skipped when nothing is declared, so an undeclared layout stays absent
    /// from every serialization of this view rather than appearing as an empty
    /// object that was never authored.
    #[serde(default, skip_serializing_if = "ZebflowJsonLayout::is_undeclared")]
    pub layout: ZebflowJsonLayout,
    #[serde(default)]
    pub rwe: ZebflowJsonRwe,
    #[serde(default)]
    pub pipelines: ZebflowJsonPipelines,
    #[serde(default)]
    pub runtime: ProjectRuntimeProfile,
    #[serde(default)]
    pub bootstrap: ProjectBootstrapPlan,
    #[serde(default)]
    pub git: ZebflowJsonGit,
    #[serde(default)]
    pub assistant: ZebflowJsonAssistant,
    #[serde(default)]
    pub locks: ZebflowJsonLocks,
    #[serde(default)]
    pub data: ZebflowJsonData,
    #[serde(default)]
    pub files: ZebflowJsonFiles,
}

/// Repository-relative source root: pipelines, pages, styles, and components.
/// The source tree defaults to the repository itself.
///
/// A project starts as an empty repository: no `pipelines/`, no `pages/`, no
/// `docs/`. A pipeline, a page and a stylesheet may sit at the root beside the
/// README, and a project that wants them gathered under one directory says so
/// with `spec.layout.source`. The directories named by the other layout entries
/// are where their kind is *looked for*, never directories the platform
/// creates.
pub const DEFAULT_LAYOUT_SOURCE_DIR: &str = "";
/// Directory name, inside the source root, served for
/// `/static/{owner}/{project}/...`.
pub const DEFAULT_LAYOUT_STATIC_SUBDIR: &str = "static";
/// Repository-relative directory holding project documentation.
pub const DEFAULT_LAYOUT_DOCS_DIR: &str = "docs";
/// Repository-relative directory holding the exported database schema document.
pub const DEFAULT_LAYOUT_SCHEMA_DIR: &str = "schemas/sekejap";
/// Repository-relative directory holding the portable SQLite schema export.
pub const DEFAULT_LAYOUT_SQLITE_SCHEMA_DIR: &str = "schemas/sqlite";
/// Repository-relative directory holding third-party node interface documents.
pub const DEFAULT_LAYOUT_NODE_INTERFACES_DIR: &str = "nodes";
/// File extensions a package may write into `repo/`, lowercase, without a dot.
///
/// An extension is here because this build can say what the file is: source the
/// RWE compiler builds, a document a contract defines, or a media type
/// `content_type_for_path` serves from the asset route. Everything else lands
/// as `application/octet-stream` -- a binary nothing here reads -- which is the
/// `.dylib` and `.sh` case this set exists to refuse.
///
/// The test is a suffix, so it is decidable from the path alone with no
/// heuristic and no false positive. That is what makes it fit to be a
/// violation, which nobody can override, rather than a warning.
pub const DEFAULT_ALLOWED_FILE_EXTENSIONS: &[&str] = &[
    // Source and project documents. `.zf.json`, the schema exports, node
    // interfaces and library manifests are all `json`.
    "css", "geojson", "js", "json", "jsx", "md", "mjs", "sql", "ts", "tsx", "txt", "webmanifest", "xml",
    "yaml", "yml", // Assets: what the asset route serves with a content type of its own.
    "csv", "gif", "ico", "jpeg", "jpg", "mp3", "mp4", "pdf", "png", "svg", "ttf", "webp", "woff",
    "woff2", // Potoru: a story and a linked library, played by `zeb/potoru`.
    "poto", "potolib",
];
/// Files a package may write whatever the extension set says, matched on the
/// whole file name.
///
/// These carry their meaning in the name rather than the suffix. Three of them
/// are load-bearing: a bundle with no `zebflow.yaml` is refused outright,
/// `zeb.lock` travels in every install scope and ends in nothing else, and
/// `ensure_project_layout` writes a `.gitkeep` into three directories of every
/// project -- so without these a project's own export could not come back. A
/// project narrows extensions and never this list, because narrowing it is how
/// a project would make its own bundles uninstallable.
pub const ALWAYS_ALLOWED_FILE_NAMES: &[&str] = &[
    ".gitkeep",
    "schema.json",
    "zeb.lock",
    "zebflow.init.json",
    "zebflow.yaml",
];
/// Filename suffix that marks a pipeline definition.
pub const PIPELINE_DEFINITION_EXTENSION: &str = ".zf.json";

/// The repository folder a version migration keeps its originals in
/// (`archive/0.10/<path>`). Nothing under it is a pipeline: it is never
/// registered, listed, loaded or activated.
pub const MIGRATION_ARCHIVE_DIR: &str = "archive";

/// Whether a repository-relative path lies under [`MIGRATION_ARCHIVE_DIR`].
pub fn is_migration_archive_path(repo_rel: &str) -> bool {
    let rel = repo_rel.trim_start_matches("./").trim_start_matches('/');
    rel == MIGRATION_ARCHIVE_DIR || rel.starts_with(&format!("{MIGRATION_ARCHIVE_DIR}/"))
}
/// The source root every persisted pipeline id carried before identity became
/// source-relative. It is the one prefix the migration knows how to remove.
pub const LEGACY_PIPELINE_IDENTITY_ROOT: &str = "pipelines";
/// Recovery copy stem written by the pipeline identity migration, combined
/// with the migration date (`project-directory.md` §5) into
/// `data/recovery/pipeline-identity-{date}.json`.
pub const PIPELINE_IDENTITY_BACKUP_FILE: &str = "pipeline-identity";
/// Filename of the exported schema document inside the schema directory.
pub const SCHEMA_DOCUMENT_FILE: &str = "schema.json";
/// Filename of the SQLite schema export inside the SQLite schema directory.
pub const SQLITE_SCHEMA_DOCUMENT_FILE: &str = "schema.sql";

/// Declared repository layout loaded from `zebflow.yaml`.
///
/// Every entry is optional and an absent entry means the platform default, so a
/// project written before this section existed keeps the directories the
/// platform hardcodes rather than acquiring a declaration it never made.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonLayout {
    /// Source root. This is also the RWE template root and the `@/` import root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#static: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub docs: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sqlite_schema: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_interfaces: Option<String>,
    /// Prefixes an install replays as initial data, each bound to one engine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub initial_data: Option<Vec<ZebflowJsonInitialDataDir>>,
    /// File extensions this project accepts, narrowing the platform set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allowed_extensions: Option<Vec<String>>,
}

/// One initial-data prefix and the database engine that would replay it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonInitialDataDir {
    /// Repository-relative directory prefix.
    pub path: String,
    /// Engine name, matching the engine tokens the installer dispatches on.
    pub engine: String,
}

/// The default initial-data prefixes, derived from the installer's own table so
/// a declaration-free project can never resolve to a different set than the one
/// the installer actually replays.
pub fn default_initial_data_dirs() -> Vec<ZebflowJsonInitialDataDir> {
    crate::platform::policy::package::INITIAL_DATA_DIRS
        .iter()
        .map(|(path, engine)| ZebflowJsonInitialDataDir {
            path: (*path).to_string(),
            engine: (*engine).to_string(),
        })
        .collect()
}

/// The layout a project actually has: every entry resolved to a concrete,
/// repository-relative directory.
///
/// Consumers read this instead of the declaration so that "not declared" is
/// answered once, here, rather than at each of the places that need a path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedProjectLayout {
    pub source: String,
    pub r#static: String,
    pub docs: String,
    pub schema: String,
    pub sqlite_schema: String,
    pub node_interfaces: String,
    pub initial_data: Vec<ZebflowJsonInitialDataDir>,
    /// Lowercase, dotless, and never wider than
    /// [`DEFAULT_ALLOWED_FILE_EXTENSIONS`].
    pub allowed_extensions: Vec<String>,
}

impl ZebflowJsonLayout {
    /// Returns true when the project declared no layout at all.
    pub fn is_undeclared(&self) -> bool {
        *self == Self::default()
    }

    /// Resolves the declaration against the platform defaults.
    pub fn resolve(&self) -> ResolvedProjectLayout {
        let resolved = |declared: &Option<String>, fallback: &str| {
            declared.clone().unwrap_or_else(|| fallback.to_string())
        };
        let source = resolved(&self.source, DEFAULT_LAYOUT_SOURCE_DIR);
        // The static root sits *inside* the source root rather than at a fixed
        // path, so a project that moves its source does not leave a static
        // directory behind in the tree it moved out of. With the source at the
        // repository root the subdirectory stands alone: joining `"/static"`
        // onto a path is absolute in Rust and would leave the project entirely.
        //
        // It keeps a directory of its own whatever the source is, because
        // `/static/{owner}/{project}/…` serves everything beneath it publicly
        // -- rooting it at the repository would publish `zebflow.yaml` and
        // every pipeline definition. It is the one layout entry that may not
        // be empty.
        let r#static = self.r#static.clone().unwrap_or_else(|| {
            if source.is_empty() {
                DEFAULT_LAYOUT_STATIC_SUBDIR.to_string()
            } else {
                format!("{source}/{DEFAULT_LAYOUT_STATIC_SUBDIR}")
            }
        });
        ResolvedProjectLayout {
            source,
            r#static,
            docs: resolved(&self.docs, DEFAULT_LAYOUT_DOCS_DIR),
            schema: resolved(&self.schema, DEFAULT_LAYOUT_SCHEMA_DIR),
            sqlite_schema: resolved(&self.sqlite_schema, DEFAULT_LAYOUT_SQLITE_SCHEMA_DIR),
            node_interfaces: resolved(&self.node_interfaces, DEFAULT_LAYOUT_NODE_INTERFACES_DIR),
            initial_data: self
                .initial_data
                .clone()
                .unwrap_or_else(default_initial_data_dirs),
            allowed_extensions: resolve_allowed_extensions(self.allowed_extensions.as_deref()),
        }
    }
}

/// The extensions a declaration ends up with: the platform set, or the declared
/// subset of it.
///
/// The intersection is the guarantee rather than the message. A declared
/// extension outside the platform set is refused by name when the document is
/// read, so no user ever reaches this clamp; it is here so that no code path
/// can construct a layout accepting more than the platform does either. A
/// project may narrow the set because narrowing only ever refuses more. It may
/// not widen it, because a violation nobody can override stops being one the
/// moment a line in a project's own configuration can turn it off.
fn resolve_allowed_extensions(declared: Option<&[String]>) -> Vec<String> {
    let Some(declared) = declared else {
        return DEFAULT_ALLOWED_FILE_EXTENSIONS
            .iter()
            .map(|value| (*value).to_string())
            .collect();
    };
    let mut resolved = declared
        .iter()
        .map(|value| value.trim().trim_start_matches('.').to_ascii_lowercase())
        .filter(|value| DEFAULT_ALLOWED_FILE_EXTENSIONS.contains(&value.as_str()))
        .collect::<Vec<_>>();
    resolved.sort();
    resolved.dedup();
    resolved
}

impl ResolvedProjectLayout {
    /// The layout of a project that declares nothing.
    pub fn platform_default() -> Self {
        ZebflowJsonLayout::default().resolve()
    }

    /// Repository-relative path of `rest` inside the source root.
    ///
    /// With the source at the repository root there is no prefix to add, and
    /// adding one anyway would make the path absolute.
    pub fn source_rel(&self, rest: &str) -> String {
        if rest.is_empty() {
            self.source.clone()
        } else if self.source.is_empty() {
            rest.to_string()
        } else {
            format!("{}/{rest}", self.source)
        }
    }

    /// `rel` with the source root removed, or `None` when it lives elsewhere.
    pub fn strip_source<'a>(&self, rel: &'a str) -> Option<&'a str> {
        strip_dir_prefix(&self.source, rel)
    }

    /// Whether `rel` is a repository-relative path inside the source root.
    pub fn is_in_source(&self, rel: &str) -> bool {
        self.strip_source(rel).is_some()
    }

    /// Whether `rel` names a pipeline definition.
    ///
    /// The safety review and the registration that follows it both ask this, so
    /// they agree by construction: a path the review skips can never be a path
    /// the install still writes and registers.
    pub fn is_pipeline_rel_path(&self, rel: &str) -> bool {
        self.is_in_source(rel) && rel.ends_with(PIPELINE_DEFINITION_EXTENSION) && !is_migration_archive_path(rel)
    }

    /// Whether `rel` is part of the exported database schema document tree.
    pub fn is_schema_rel_path(&self, rel: &str) -> bool {
        strip_dir_prefix(&self.schema, rel).is_some()
    }

    /// Repository-relative path of the exported schema document itself.
    pub fn schema_document_rel(&self) -> String {
        format!("{}/{SCHEMA_DOCUMENT_FILE}", self.schema)
    }

    /// Whether `rel` is part of the portable SQLite schema export.
    pub fn is_sqlite_schema_rel_path(&self, rel: &str) -> bool {
        strip_dir_prefix(&self.sqlite_schema, rel).is_some()
    }

    /// Repository-relative path of the SQLite schema export itself.
    pub fn sqlite_schema_document_rel(&self) -> String {
        format!("{}/{SQLITE_SCHEMA_DOCUMENT_FILE}", self.sqlite_schema)
    }

    /// The engine that would replay `rel`, when this layout replays it at all.
    ///
    /// The prefix is anchored, so this names the files an install actually runs
    /// and not every `.sql` a package happens to ship.
    pub fn initial_data_engine(&self, rel: &str) -> Option<&str> {
        if !rel.ends_with(".sql") {
            return None;
        }
        self.initial_data
            .iter()
            .find(|dir| strip_dir_prefix(&dir.path, rel).is_some())
            .map(|dir| dir.engine.as_str())
    }

    /// Why this layout refuses to hold `rel`, or `None` when it accepts it.
    ///
    /// The answer is phrased for the refusal message: a package that cannot be
    /// installed by anyone's approval has to say exactly what it was refused
    /// for, and "no extension" is as much an answer as `.sh`.
    pub fn refused_file_type(&self, rel: &str) -> Option<String> {
        let name = rel.rsplit('/').next().unwrap_or(rel);
        if ALWAYS_ALLOWED_FILE_NAMES.contains(&name.to_ascii_lowercase().as_str()) {
            return None;
        }
        match file_extension(name) {
            Some(extension)
                if self
                    .allowed_extensions
                    .iter()
                    .any(|item| *item == extension) =>
            {
                None
            }
            Some(extension) => Some(format!("extension '.{extension}'")),
            None => Some("a name with no extension".to_string()),
        }
    }
}

/// The suffix a file name is judged by, lowercase and without the dot.
///
/// A leading dot marks a hidden file rather than a suffix, so `.env` has no
/// extension to judge and is refused as an unnamed type -- which is the answer
/// that case needs anyway.
fn file_extension(name: &str) -> Option<String> {
    let (stem, extension) = name.rsplit_once('.')?;
    if stem.is_empty() || extension.is_empty() {
        return None;
    }
    Some(extension.to_ascii_lowercase())
}

/// `rel` with `dir` and its separator removed, or `None` when `rel` is not
/// under `dir`. Anchored on a whole segment, so `pipelines-old/x` is not
/// treated as living under `pipelines`.
pub fn strip_dir_prefix<'a>(dir: &str, rel: &'a str) -> Option<&'a str> {
    // An empty declaration names the repository root, so everything is inside
    // it and nothing has a prefix to remove.
    if dir.is_empty() {
        return Some(rel);
    }
    rel.strip_prefix(dir)?.strip_prefix('/')
}

impl ZebflowJson {
    /// Effective repository layout for this project.
    pub fn layout(&self) -> ResolvedProjectLayout {
        self.configs.layout.resolve()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonPipelines {
    #[serde(default)]
    pub logging: ZebflowJsonLogging,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_timeout_secs: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonData {}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonFiles {
    /// The native store this project's `files/` live in.
    ///
    /// Absent means the platform default, so a project written before this
    /// entry existed keeps the store it already used. It is not the place a
    /// pipeline reads an outside bucket from — that is a connection, not a
    /// backend.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backend: Option<String>,
    #[serde(default)]
    pub uploads: ZebflowJsonUploads,
}

impl ZebflowJsonFiles {
    /// The declared backend, or the default a project inherits by declaring
    /// nothing. An unknown word is refused rather than defaulted.
    pub fn effective_backend(&self) -> Result<FileBackend, ZebFsError> {
        FileBackend::resolve(self.backend.as_deref())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonUploads {
    /// Max allowed size in MB for a single uploaded asset file (5–1024, default 10).
    #[serde(default = "default_max_asset_size_mb")]
    pub max_asset_size_mb: u32,
    /// Max allowed size in MB for one webhook request body.
    ///
    /// This controls the per-project logical limit enforced by `/wh/...` handlers.
    /// Route-level Axum buffering still uses a higher fallback ceiling so project
    /// overrides can be enforced inside the request handler.
    #[serde(default = "default_webhook_body_max_mb")]
    pub webhook_body_max_mb: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_file_size_mb: Option<u32>,
}

impl Default for ZebflowJsonUploads {
    fn default() -> Self {
        Self {
            max_asset_size_mb: default_max_asset_size_mb(),
            webhook_body_max_mb: default_webhook_body_max_mb(),
            max_file_size_mb: None,
        }
    }
}

impl ZebflowJsonUploads {
    pub fn effective_max_asset_size_mb(&self) -> u32 {
        self.max_asset_size_mb.clamp(5, MAX_UPLOAD_SIZE_MB)
    }

    pub fn effective_webhook_body_max_mb(&self) -> u32 {
        self.webhook_body_max_mb
            .clamp(default_webhook_body_max_mb(), MAX_UPLOAD_SIZE_MB)
    }

    pub fn effective_max_file_size_mb(&self) -> u32 {
        self.max_file_size_mb
            .unwrap_or(MAX_UPLOAD_SIZE_MB)
            .clamp(5, MAX_UPLOAD_SIZE_MB)
    }
}

impl ZebflowJsonPipelines {
    pub fn effective_node_timeout_secs(&self) -> u64 {
        self.node_timeout_secs
            .unwrap_or_else(default_pipeline_node_timeout_secs)
            .clamp(5, 3600)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonDistribution {
    #[serde(default)]
    pub hub: ZebflowJsonDistributionHub,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonDistributionHub {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub entry_url: String,
    #[serde(default)]
    pub as_app: bool,
    #[serde(default)]
    pub producer_enabled: bool,
}

/// Lock settings loaded from `zebflow.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonLocks {
    /// Template rel_paths (files or folder prefixes) blocked from agent read/write.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub templates: Vec<String>,
}

/// Git settings loaded from `zebflow.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonGit {
    #[serde(default)]
    pub remote: ZebflowJsonGitRemote,
}

/// Git remote settings loaded from `zebflow.yaml`.
/// Stores remote repository configuration for push/sync operations.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonGitRemote {
    /// Credential ID for authenticated push (references `ProjectCredential.credential_id`).
    #[serde(default)]
    pub credential_id: String,
    /// Remote repository URL (e.g. `"https://gitlab.com/user/repo.git"`).
    #[serde(default)]
    pub repo_url: String,
    /// Default branch to push to (e.g. `"main"`).
    #[serde(default)]
    pub branch: String,
}

/// RWE settings loaded from `zebflow.yaml`.
///
/// Controls project-level compile/render behaviour for all `web.response.send` template nodes.
/// Values are merged into [`crate::rwe::ReactiveWebOptions`] at execution time,
/// before each pipeline run. Node-level `--script` URLs are appended on top.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonRwe {
    /// URL patterns applied to the RWE resource allow-list (scripts and CSS).
    ///
    /// Each entry is a glob-style prefix, e.g. `https://cdnjs.cloudflare.com/*`.
    /// Blessed libraries (imported via `zeb/*`) are always allowed and do not
    /// appear here. Node-level `--script` URLs are blocked at save time if any
    /// URL does not match an entry in this list.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allow_list: Vec<String>,
    /// Enable HTML minification on rendered output. Default: false.
    #[serde(default)]
    pub minify_html: bool,
    /// Enable strict compile-time checks. Default: true.
    #[serde(default = "default_rwe_strict_mode")]
    pub strict_mode: bool,
    /// Per-project enabled `zeb/*` library declarations.
    ///
    /// Keyed by library name (e.g. `"zeb/threejs"`). An entry here locks
    /// the version for reproducibility and surfaces the library in editor
    /// tooling. All libraries are served unconditionally at
    /// `/assets/libraries/zeb/…` regardless of this map.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub libraries: ZebflowJsonRweLibraries,
    /// Base URL prefix used when generating `<script src="...">` paths for
    /// compiled RWE scripts in production.
    ///
    /// Default (`None`): `/static/{owner}/{project}/_rwe/scripts/{hash}`
    ///
    /// When set, the prefix replaces `/static/{owner}/{project}`, so the
    /// resulting path becomes `{deployment_asset_base}/_rwe/scripts/{hash}`.
    ///
    /// Useful when the app is served behind a reverse proxy that rewrites
    /// asset paths, or when static assets are hosted at a custom sub-path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deployment_asset_base: Option<String>,
}

impl Default for ZebflowJsonRwe {
    fn default() -> Self {
        Self {
            allow_list: Vec::new(),
            minify_html: false,
            strict_mode: default_rwe_strict_mode(),
            libraries: HashMap::new(),
            deployment_asset_base: None,
        }
    }
}

/// Enabled library map loaded from `rwe.libraries` in `zebflow.yaml`.
pub type ZebflowJsonRweLibraries = HashMap<String, ZebflowJsonRweLibraryEntry>;

/// One enabled library entry loaded from `zebflow.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonRweLibraryEntry {
    /// Pinned packed version string (e.g. `"bridge-0.1"`).
    pub version: String,
    /// Source kind: `"offline"` (embedded binary) or `"hub"` (installed copy).
    pub source: String,
}

pub fn default_rwe_strict_mode() -> bool {
    true
}

/// API request to update project-level RWE settings in `zebflow.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpsertRweSettingsRequest {
    #[serde(default)]
    pub allow_list: Vec<String>,
    #[serde(default)]
    pub minify_html: bool,
    #[serde(default = "default_rwe_strict_mode")]
    pub strict_mode: bool,
}

/// Logging settings loaded from `zebflow.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonLogging {
    /// Max invocation entries to retain per pipeline. Defaults to 20.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_invocations: Option<u32>,
    /// Project defaults for bounded node trace capture, overridden independently
    /// by each pipeline. Omitted fields inherit the engine defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trace_capture: Option<crate::pipeline::trace_capture::TraceCaptureSettings>,
    /// Distinct error groups kept per project (`kinds/invocation-record`,
    /// Retention). Defaults to 200.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_error_groups: Option<u32>,
    /// Occurrences remembered per group as `(run_id, at)`. Defaults to 500.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub occurrence_ring: Option<u32>,
}

impl ZebflowJsonLogging {
    pub fn effective_max_invocations(&self) -> usize {
        self.max_invocations.unwrap_or(20).max(1) as usize
    }

    pub fn error_group_bounds(&self) -> ErrorGroupBounds {
        let d = ErrorGroupBounds::default();
        ErrorGroupBounds {
            max_groups: self.max_error_groups.map(|v| v.max(1) as usize).unwrap_or(d.max_groups),
            occurrence_ring: self.occurrence_ring.map(|v| v.max(1) as usize).unwrap_or(d.occurrence_ring),
            ..d
        }
    }
}

/// One distinct failure of a pipeline, counted across occurrences
/// (`kinds/invocation-record`, Error group).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineErrorGroup {
    pub file_rel_path: String,
    pub signature: String,
    pub node_id: String,
    pub code: String,
    /// The message with runs of digits and quoted values blanked.
    pub message_pattern: String,
    pub count: u64,
    pub first_seen: i64,
    pub last_seen: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reopened_at: Option<i64>,
    pub first: PipelineInvocationEntry,
    pub latest: PipelineInvocationEntry,
    /// `(run_id, at)` of the newest occurrences.
    pub occurrences: Vec<(String, i64)>,
    /// `first-latest` or `all`.
    pub capture: String,
    /// Full records kept under `capture: all`, oldest first, up to the cap.
    #[serde(default)]
    pub captured: Vec<PipelineInvocationEntry>,
}

/// The three parts of a failure's signature: the failing node, its error
/// code, and the message. From the last trace entry that carries an error;
/// the run's own error message when no node does.
/// The trace entry that failed the run: the last one carrying an error whose
/// failure was not consumed by an `:error` edge. A `retry` or `error_routed`
/// entry is a node that failed and a run that went on, so it is not the
/// reason the run ended — and never the key of an error group.
pub fn failing_trace_entry(
    trace: &[crate::pipeline::model::NodeTraceEntry],
) -> Option<&crate::pipeline::model::NodeTraceEntry> {
    trace
        .iter()
        .rev()
        .find(|t| t.error.is_some() && t.status != "retry" && t.status != "error_routed")
}

pub fn error_group_parts(entry: &PipelineInvocationEntry) -> (String, String, String) {
    if let Some(t) = failing_trace_entry(&entry.trace) {
        let err = t.error.clone().unwrap_or_default();
        let (code, message) = match err.split_once(": ") {
            Some((c, m)) if c.len() < 48 && c.chars().all(|ch| ch.is_ascii_uppercase() || ch == '_' || ch.is_ascii_digit()) => (c.to_string(), m.to_string()),
            _ => (String::new(), err),
        };
        // A message that names its code (`ZEBFS_READ_ONLY: …`, passed through
        // a node's own) keys on that, the more precise one; any other keys on
        // the registered code the run recorded beside the message.
        let code = if code.is_empty() { t.error_code.clone().unwrap_or_default() } else { code };
        return (t.node_id.clone(), code, message);
    }
    (String::new(), String::new(), entry.error.clone().unwrap_or_default())
}

/// The message with runs of digits and quoted values blanked, so two
/// occurrences that differ only in an id or a value are one error
/// (`kinds/invocation-record`, Error group).
pub fn error_message_pattern(message: &str) -> String {
    let mut out = String::with_capacity(message.len());
    let mut chars = message.chars().peekable();
    let mut in_quote: Option<char> = None;
    while let Some(c) = chars.next() {
        if let Some(q) = in_quote {
            if c == q {
                in_quote = None;
                out.push(q);
            }
            continue;
        }
        match c {
            '"' | '\'' | '`' => {
                in_quote = Some(c);
                out.push(c);
                out.push('?');
            }
            d if d.is_ascii_digit() => {
                if !out.ends_with('#') {
                    out.push('#');
                }
                while chars.peek().is_some_and(|n| n.is_ascii_digit()) {
                    chars.next();
                }
            }
            other => out.push(other),
        }
    }
    out.chars().take(200).collect()
}

/// How many distinct errors, occurrences and full records a project keeps.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct ErrorGroupBounds {
    pub max_groups: usize,
    pub occurrence_ring: usize,
    pub capture_cap: usize,
    /// Quiet seconds after which a new occurrence reopens the group.
    pub reopen_after_secs: i64,
}

impl Default for ErrorGroupBounds {
    fn default() -> Self {
        Self { max_groups: 200, occurrence_ring: 500, capture_cap: 200, reopen_after_secs: 7 * 24 * 3600 }
    }
}

/// The retention a run's record is kept under: the pipeline's own setting
/// where it has one, else the project's.
#[derive(Debug, Clone, Copy)]
pub struct EffectivePipelineInvocationRetention {
    pub max_invocations: usize,
    pub max_age_secs: Option<i64>,
}

/// Resolves [`EffectivePipelineInvocationRetention`] for one run. Shared by
/// every path that writes a record — the API route, the webhook ingress, the
/// DSL `execute pipeline` — so all of them keep the same number of runs.
pub fn resolve_invocation_retention(
    project_cfg: &ZebflowJson,
    graph: Option<&crate::pipeline::PipelineGraph>,
) -> EffectivePipelineInvocationRetention {
    let project_max_invocations = project_cfg
        .configs
        .pipelines
        .logging
        .effective_max_invocations();
    let pipeline_retention = graph
        .and_then(|graph| graph.metadata.as_ref())
        .and_then(|metadata| metadata.settings.invocation_retention.as_ref());
    let max_invocations = pipeline_retention
        .and_then(|retention| retention.max_invocations)
        .map(|value| value.max(1) as usize)
        .unwrap_or(project_max_invocations);
    let max_age_secs = pipeline_retention
        .and_then(|retention| retention.max_age_secs)
        .map(|value| value.max(1) as i64);
    EffectivePipelineInvocationRetention {
        max_invocations,
        max_age_secs,
    }
}

/// One recorded pipeline invocation.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PipelineInvocationEntry {
    /// Stable run identifier for this execution.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub run_id: String,
    /// Unix timestamp (seconds).
    pub at: i64,
    /// Wall-clock duration of the execution in milliseconds.
    pub duration_ms: u64,
    /// `"ok"` or `"error"`.
    pub status: String,
    /// Trigger source: `"webhook"`, `"manual"`, `"schedule"`, etc.
    pub trigger: String,
    /// Short error message, present only when `status == "error"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Per-node execution trace for this invocation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub trace: Vec<crate::pipeline::model::NodeTraceEntry>,
}

/// Per-pipeline invocation log storage summary.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PipelineInvocationLogPipelineStats {
    pub file_rel_path: String,
    pub count: u64,
    pub trace_bytes: u64,
    pub largest_trace_bytes: u64,
    pub latest_at: i64,
}

/// Project-scoped invocation log storage summary.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PipelineInvocationLogStats {
    pub count: u64,
    pub trace_bytes: u64,
    pub db_bytes: u64,
    pub wal_bytes: u64,
    pub shm_bytes: u64,
    pub pipelines: Vec<PipelineInvocationLogPipelineStats>,
}

/// Assistant settings loaded from `zebflow.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct ZebflowJsonAssistant {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub high_model_credential: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub general_model_credential: Option<String>,
    #[serde(default)]
    pub max_steps: Option<u32>,
    #[serde(default)]
    pub max_replans: Option<u32>,
    #[serde(default)]
    pub chat_history_pairs: Option<u32>,
    #[serde(default)]
    pub enabled: Option<bool>,
}

/// Request payload for project creation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateProjectRequest {
    /// Project slug.
    pub project: String,
    /// Optional title.
    pub title: Option<String>,
    /// Optional initial local branch name. Defaults to "main" when None or empty.
    #[serde(default)]
    pub local_branch: Option<String>,
    /// Environment-owned runtime selection captured at create/clone time.
    #[serde(default)]
    pub runtime: ProjectRuntimeSelectionRequest,
}

/// Environment-owned runtime selection supplied during create/clone flows.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ProjectRuntimeSelectionRequest {
    /// Optional explicit runtime mode override for the project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_mode: Option<crate::infra::execution::placement::ProjectRuntimeMode>,
    /// Selected runtime host id, or `None`/`local` for the current office.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placement_worker_id: Option<String>,
}

/// Internal office registration request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ClusterWorkerRegisterRequest {
    /// Stable office id.
    pub node_id: String,
    /// Human-readable office label.
    #[serde(default)]
    pub label: String,
    /// Advertised base URL reachable by the controller or peers.
    #[serde(default)]
    pub base_url: String,
    /// Declared runtime capabilities.
    #[serde(default)]
    pub capabilities: RunnerCapabilities,
    /// Fresh random nonce the controller must answer with a proof.
    ///
    /// `offices.md` §8 wants proof in both directions. The office sends this,
    /// and refuses a response whose `proof` does not verify, so it can tell a
    /// real controller from any host that answers its base URL.
    #[serde(default)]
    pub nonce: String,
}

/// Internal office heartbeat request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ClusterWorkerHeartbeatRequest {
    /// Stable office id.
    pub node_id: String,
    /// Current status summary.
    #[serde(default)]
    pub status: String,
    /// Refreshed advertised base URL.
    #[serde(default)]
    pub base_url: String,
    /// Refreshed runtime capabilities.
    #[serde(default)]
    pub capabilities: RunnerCapabilities,
    /// Every project this office holds, whole, replacing the last list.
    #[serde(default)]
    pub projects: Vec<crate::infra::cluster::registry::OfficeHeldProject>,
}

/// Internal office registration response returned by the controller.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ClusterWorkerRegisterResponse {
    /// Whether the registration was accepted.
    pub ok: bool,
    /// Normalized registry record.
    pub worker: crate::infra::cluster::registry::WorkerRegistryRecord,
    /// HMAC over the office's nonce, keyed by this office's own secret digest.
    #[serde(default)]
    pub proof: String,
}

/// Internal office heartbeat response returned by the controller.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ClusterWorkerHeartbeatResponse {
    /// Whether the heartbeat update was accepted.
    pub ok: bool,
    /// Normalized heartbeat snapshot.
    pub heartbeat: WorkerHeartbeat,
}

/// Operator request to mint one office join token.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ClusterJoinTokenMintRequest {
    /// Office the token is issued to. Minting creates the office record when
    /// it does not exist yet, so the holder is recorded before the token is.
    pub office_id: String,
    /// Display label for a newly created office record.
    #[serde(default)]
    pub label: String,
    /// Base URL of the planned office, when the operator already knows it.
    #[serde(default)]
    pub base_url: String,
    /// Operator note recorded beside the token.
    #[serde(default)]
    pub note: String,
    /// Replace an existing token for this office rather than refusing.
    #[serde(default)]
    pub rotate: bool,
}

/// One minted token, returned once and never readable again.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ClusterMintedJoinToken {
    /// The record the controller keeps.
    pub record: PlatformOfficeJoinToken,
    /// The office record minting created or reused.
    pub office: PlatformOffice,
    /// Plaintext token, shown once. The controller stores only its digest.
    pub token: String,
}

/// One runtime target option shown in project create/clone UI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ClusterRuntimeTargetOption {
    /// Stable value posted back by forms.
    pub value: String,
    /// Human-readable office label.
    pub label: String,
    /// Short description line for selection UI.
    #[serde(default)]
    pub description: String,
}

/// Export/import artifact kind used by first-class project portability flows.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProjectTransferArtifactKind {
    /// Repository workspace plus project runtime data.
    Bundle,
    /// Project Zebflow FS object tree.
    Files,
    /// Full backup: every movable class in one archive.
    Full,
}

impl ProjectTransferArtifactKind {
    /// Stable API/storage key.
    pub fn key(self) -> &'static str {
        match self {
            Self::Bundle => "bundle",
            Self::Files => "files",
            Self::Full => "full",
        }
    }

    /// Stable archive filename used for downloads and operation artifacts.
    pub fn archive_name(self) -> &'static str {
        match self {
            Self::Bundle => "project.bundle.tar",
            Self::Files => "project.files.tar",
            Self::Full => "project.full.tar",
        }
    }

    /// The `ProjectBundle` classes this artifact kind selects.
    ///
    /// The artifact kinds are class selections of one archive format
    /// (`kinds/project-bundle/README.md`): `bundle` = repo + store, `files` =
    /// files, `full` = every movable class. The route/UI surface keeps the
    /// legacy words; the archive speaks classes.
    pub fn classes(self) -> &'static [crate::contracts::kinds::ProjectBundleClass] {
        use crate::contracts::kinds::ProjectBundleClass;
        match self {
            Self::Bundle => &[ProjectBundleClass::Repo, ProjectBundleClass::Store],
            Self::Files => &[ProjectBundleClass::Files],
            Self::Full => &[
                ProjectBundleClass::Repo,
                ProjectBundleClass::Store,
                ProjectBundleClass::Files,
            ],
        }
    }
}

/// Durable controller-side operation kind for project portability and sync flows.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProjectOperationKind {
    /// Export `repo/` + `data/`.
    ExportBundle,
    /// Export Zebflow FS files.
    ExportFiles,
    /// Import `repo/` + `data/`.
    ImportBundle,
    /// Import Zebflow FS files.
    ImportFiles,
    /// Export every movable class.
    ExportFull,
    /// Import every movable class.
    ImportFull,
    /// Platform-scope import that created this project from an archive.
    PlatformImport,
    /// Reverse swap restoring recovery copies displaced by an import.
    RollbackImport,
}

impl ProjectOperationKind {
    /// Stable storage key.
    pub fn key(self) -> &'static str {
        match self {
            Self::ExportBundle => "export_bundle",
            Self::ExportFiles => "export_files",
            Self::ImportBundle => "import_bundle",
            Self::ImportFiles => "import_files",
            Self::ExportFull => "export_full",
            Self::ImportFull => "import_full",
            Self::PlatformImport => "platform_import",
            Self::RollbackImport => "rollback_import",
        }
    }
}

/// Durable controller-side operation state.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProjectOperationStatus {
    Pending,
    Running,
    Failed,
    Completed,
}

impl ProjectOperationStatus {
    /// Stable storage key.
    pub fn key(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Running => "running",
            Self::Failed => "failed",
            Self::Completed => "completed",
        }
    }
}

/// One durable controller-tracked project operation record.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProjectOperationRecord {
    /// Stable operation id.
    pub operation_id: String,
    /// Stable project id.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub project_id: String,
    /// Stable owner id.
    pub owner: String,
    /// Stable project slug.
    pub project: String,
    /// Operation type.
    pub kind: ProjectOperationKind,
    /// Current status.
    pub status: ProjectOperationStatus,
    /// Human-readable current step.
    #[serde(default)]
    pub current_step: String,
    /// Source office id when relevant.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_office_id: Option<String>,
    /// Target office id when relevant.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_office_id: Option<String>,
    /// Relative artifact path under controller operation storage.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact_rel_path: Option<String>,
    /// Archive SHA-256 when an artifact exists.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact_sha256: Option<String>,
    /// Artifact byte size when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact_bytes: Option<u64>,
    /// Last error message when the operation failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    /// Retry count for resumed operations.
    #[serde(default)]
    pub retry_count: u32,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
    /// Unix timestamp seconds when operation reached a terminal success state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<i64>,
}

/// Request payload for platform login page/form.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoginRequest {
    /// Username/owner id.
    pub identifier: String,
    /// Password.
    pub password: String,
}

/// Request payload for `POST /api/profile/password`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangePasswordRequest {
    /// The password the account authenticates with right now.
    pub current_password: String,
    /// The replacement password.
    pub new_password: String,
}

/// Minimal auth session value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthSession {
    /// Authenticated owner id.
    pub owner: String,
}

/// Returns unix timestamp seconds.
pub fn now_ts() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    match SystemTime::now().duration_since(UNIX_EPOCH) {
        Ok(d) => d.as_secs() as i64,
        Err(_) => 0,
    }
}

/// Current UTC date as `YYYY-MM-DD`.
///
/// Every migration that writes a recovery copy into `data/recovery/` names the
/// file with this stamp (`project-directory.md` §5), so the file itself
/// records when the migration ran without a separate audit log.
pub fn recovery_date_stamp() -> String {
    chrono::Utc::now().format("%Y-%m-%d").to_string()
}

/// Slug-normalize a segment for ids/paths.
pub fn slug_segment(raw: &str) -> String {
    raw.trim()
        .to_ascii_lowercase()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect::<String>()
        .trim_matches('-')
        .to_string()
}

/// Canonicalize one virtual path used for pipeline registry hierarchy.
///
/// Rules:
/// - root is `/`
/// - removes empty segments
/// - disallows `.` and `..`
/// - each segment is slug-normalized
pub fn normalize_virtual_path(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty() || trimmed == "/" {
        return "/".to_string();
    }
    let mut parts = Vec::new();
    for seg in trimmed.split('/') {
        let seg = seg.trim();
        if seg.is_empty() || seg == "." || seg == ".." {
            continue;
        }
        let slug = slug_segment(seg);
        if !slug.is_empty() {
            parts.push(slug);
        }
    }
    if parts.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", parts.join("/"))
    }
}

fn default_true() -> bool {
    true
}

/// MCP session record (in-memory and persisted per-project).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpSession {
    /// Owner identifier.
    pub owner: String,
    /// Project slug.
    pub project: String,
    /// Capabilities allowed for this session.
    pub capabilities: Vec<ProjectCapability>,
    /// Opaque session token.
    pub token: String,
    /// Unix timestamp seconds when session was created.
    #[serde(default)]
    pub created_at: i64,
    /// Optional seconds after which this session auto-expires.
    #[serde(default)]
    pub auto_reset_seconds: Option<u64>,
    /// Whether this session is active. Token persists even when disabled.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// The user who created the session (or last granted it capabilities).
    /// A session's capabilities are whatever its creator listed, so an act
    /// reserved to the project's owner also asks whether this user may do
    /// it. Empty for a session created before this was recorded.
    #[serde(default)]
    pub granted_by: String,
}

/// Request to create an MCP session for a project.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpSessionCreateRequest {
    /// Capabilities to allow for this session (can be specified as strings or capability keys).
    pub capabilities: Vec<String>,
    /// Optional seconds after which this session auto-expires (None = no expiry).
    #[serde(default)]
    pub auto_reset_seconds: Option<u64>,
}

/// Request to toggle an MCP session enabled/disabled.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpSessionToggleRequest {
    /// Whether to enable or disable the session.
    pub enabled: bool,
}

/// Response after creating an MCP session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpSessionResponse {
    /// Opaque session token for Authorization header.
    pub token: String,
    /// Full MCP endpoint URL for this project.
    pub mcp_url: String,
    /// Allowed capabilities echoed back.
    pub capabilities: Vec<String>,
    /// Whether the session is currently accepted by the MCP handler.
    pub enabled: bool,
    /// Session creation timestamp.
    pub created_at: i64,
    /// Optional seconds after which this session auto-expires.
    #[serde(default)]
    pub auto_reset_seconds: Option<u64>,
    /// Global minimum creation timestamp required for persisted MCP sessions.
    pub rotation_epoch: i64,
}

/// Maps MCP tool name to required project capability.
pub fn mcp_tool_capability(tool_name: &str) -> Option<ProjectCapability> {
    match tool_name {
        "list_pipelines" => Some(ProjectCapability::PipelinesRead),
        "get_pipeline" => Some(ProjectCapability::PipelinesRead),
        "upsert_pipeline" => Some(ProjectCapability::PipelinesWrite),
        "activate_pipeline" => Some(ProjectCapability::PipelinesWrite),
        "deactivate_pipeline" => Some(ProjectCapability::PipelinesWrite),
        "execute_pipeline" => Some(ProjectCapability::PipelinesExecute),
        "list_templates" => Some(ProjectCapability::TemplatesRead),
        "get_template" => Some(ProjectCapability::TemplatesRead),
        "save_template" => Some(ProjectCapability::TemplatesWrite),
        "create_template" => Some(ProjectCapability::TemplatesCreate),
        "delete_template" => Some(ProjectCapability::TemplatesDelete),
        "get_credential" => Some(ProjectCapability::CredentialsRead),
        "upsert_credential" => Some(ProjectCapability::CredentialsWrite),
        "list_db_connections" => Some(ProjectCapability::TablesRead),
        "get_db_connection" => Some(ProjectCapability::TablesRead),
        "upsert_db_connection" => Some(ProjectCapability::TablesWrite),
        "update_db_connection" => Some(ProjectCapability::TablesWrite),
        "delete_db_connection" => Some(ProjectCapability::TablesWrite),
        "test_db_connection" => Some(ProjectCapability::TablesRead),
        "describe_db_connection" => Some(ProjectCapability::TablesRead),
        "query_db_connection" => Some(ProjectCapability::TablesRead),
        "list_db_connection_schemas" => Some(ProjectCapability::TablesRead),
        "list_db_connection_tables" => Some(ProjectCapability::TablesRead),
        "list_db_connection_functions" => Some(ProjectCapability::TablesRead),
        "preview_db_connection_table" => Some(ProjectCapability::TablesRead),
        "list_project_docs" => Some(ProjectCapability::ProjectRead),
        "read_project_doc" => Some(ProjectCapability::ProjectRead),
        "create_project_doc" => Some(ProjectCapability::FilesWrite),

        "list_credentials" => Some(ProjectCapability::CredentialsRead),
        // execute_pipeline_dsl temporarily disabled; keeping mapping for future re-enable
        "execute_pipeline_dsl" => Some(ProjectCapability::PipelinesExecute),
        "git_command" => Some(ProjectCapability::PipelinesWrite),
        // New domain-prefixed tool names
        "pipeline_list" => Some(ProjectCapability::PipelinesRead),
        "pipeline_get" => Some(ProjectCapability::PipelinesRead),
        "pipeline_register" => Some(ProjectCapability::PipelinesWrite),
        "pipeline_describe" => Some(ProjectCapability::PipelinesRead),
        "pipeline_check" => Some(ProjectCapability::PipelinesRead),
        "pipeline_patch" => Some(ProjectCapability::PipelinesWrite),
        "pipeline_activate" => Some(ProjectCapability::PipelinesWrite),
        "pipeline_deactivate" => Some(ProjectCapability::PipelinesWrite),
        // The 0.10 → 0.11 migration. The session needs the pipeline
        // capability, and the tool also asks whether the session's creator
        // holds `ProjectDelete` (the owner, or a superadmin), as the HTTP
        // route asks of the signed-in user: a session's capabilities are what
        // its creator listed, and `project.delete` is not grantable to one.
        "migration_plan" => Some(ProjectCapability::PipelinesRead),
        "migration_apply" => Some(ProjectCapability::PipelinesWrite),
        "pipeline_execute" => Some(ProjectCapability::PipelinesExecute),
        "pipeline_run" => Some(ProjectCapability::PipelinesExecute),
        "pipeline_get_invocations" => Some(ProjectCapability::PipelinesRead),
        // One file vocabulary over the repository. `docs_project_*` is gone with
        // it: a `.md` is a file like any other, and had no reason to be reached
        // by its own three tools.
        "file_list" => Some(ProjectCapability::TemplatesRead),
        "file_read" => Some(ProjectCapability::TemplatesRead),
        "file_create" => Some(ProjectCapability::TemplatesCreate),
        "file_write" => Some(ProjectCapability::TemplatesWrite),
        "file_search" => Some(ProjectCapability::TemplatesRead),
        "file_edit" => Some(ProjectCapability::TemplatesWrite),
        "file_outline" => Some(ProjectCapability::TemplatesRead),
        "file_deps" => Some(ProjectCapability::TemplatesRead),
        "file_batch_edit" => Some(ProjectCapability::TemplatesWrite),
        "pipeline_search" => Some(ProjectCapability::PipelinesRead),
        "connection_list" => Some(ProjectCapability::TablesRead),
        "connection_describe" => Some(ProjectCapability::TablesRead),
        "credential_list" => Some(ProjectCapability::CredentialsRead),
        "docs_agent_list" => Some(ProjectCapability::SettingsRead),
        "docs_agent_read" => Some(ProjectCapability::SettingsRead),
        "docs_agent_write" => Some(ProjectCapability::SettingsWrite),
        // Help and orientation tools
        "start_here" => Some(ProjectCapability::ProjectRead),
        "help" => Some(ProjectCapability::ProjectRead),
        "help_search" => Some(ProjectCapability::ProjectRead),
        "skill_list" => Some(ProjectCapability::ProjectRead),
        "skill_read" => Some(ProjectCapability::ProjectRead),
        // UI catalog install tools
        "list_ui_catalog" => Some(ProjectCapability::PipelinesRead),
        "install_ui_components" => Some(ProjectCapability::PipelinesWrite),
        "hub_search" => Some(ProjectCapability::PipelinesRead),
        "hub_review" => Some(ProjectCapability::PipelinesRead),
        "hub_add" => Some(ProjectCapability::PipelinesWrite),
        "route_fetch" => Some(ProjectCapability::PipelinesExecute),
        "theme_generate" => Some(ProjectCapability::ProjectRead),
        // Move resource (requires both pipelines write + templates write — use higher capability)
        "move_resource" => Some(ProjectCapability::PipelinesWrite),
        _ => None,
    }
}

#[cfg(test)]
mod error_group_tests {
    use super::*;

    /// A node's refusal carries its registered code beside the message, not
    /// inside it; the error group keys on that code.
    #[test]
    fn an_error_group_takes_the_code_the_trace_recorded() {
        let trace = serde_json::from_value(serde_json::json!([
            { "node_id": "n0", "node_kind": "trigger.webhook", "duration_ms": 0, "input": null, "output": null, "status": "ok" },
            { "node_id": "n1", "node_kind": "fs.file.delete", "duration_ms": 1, "input": null, "output": null, "status": "refused",
              "error": "'a/b' is a folder that holds files", "error_code": "FW_NODE_FS_FILE_DELETE_FOLDER" }
        ]))
        .expect("trace");
        let entry = PipelineInvocationEntry { status: "error".into(), trace, ..Default::default() };
        let (node, code, message) = error_group_parts(&entry);
        assert_eq!((node.as_str(), code.as_str()), ("n1", "FW_NODE_FS_FILE_DELETE_FOLDER"));
        assert_eq!(message, "'a/b' is a folder that holds files");

        // A contract's code the message carries is the more precise key.
        let trace = serde_json::from_value(serde_json::json!([
            { "node_id": "n1", "node_kind": "fs.file.put", "duration_ms": 1, "input": null, "output": null, "status": "failed",
              "error": "ZEBFS_READ_ONLY: the store is read-only", "error_code": "FW_NODE_FS_FILE_PUT" }
        ]))
        .expect("trace");
        let entry = PipelineInvocationEntry { status: "error".into(), trace, ..Default::default() };
        let (_, code, message) = error_group_parts(&entry);
        assert_eq!((code.as_str(), message.as_str()), ("ZEBFS_READ_ONLY", "the store is read-only"));
    }
}