zebflow 0.8.3

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
//! Platform domain models and configuration.

use std::collections::HashMap;
use std::path::PathBuf;

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

use crate::infra::cluster::config::ClusterSettings;
use crate::infra::cluster::registry::WorkerHeartbeat;
use crate::infra::execution::placement::{ProjectRuntimePlacement, ProjectRuntimeProfile};
use crate::infra::execution::runner::RunnerCapabilities;
use crate::infra::execution::sync::{ProjectBootstrapPlan, ProjectRuntimeBundle};

/// 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.
    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,
    /// Initial superadmin password created on first bootstrap.
    ///
    /// This should be supplied explicitly by the host (for example from
    /// `ZEBFLOW_PLATFORM_DEFAULT_PASSWORD`) rather than relying on a baked-in
    /// repository default.
    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 {
            data_root: PathBuf::from(".zebflow-platform-data"),
            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,
}

/// 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,
}

/// 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,
}

// ---------------------------------------------------------------------------
// 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)]
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)]
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,
    /// 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,
}

/// 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 published hub asset package stored by the hub service.
#[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,
    /// Public package image URL resolved from Hub artifact media.
    #[serde(default)]
    pub image_url: String,
    /// Visibility (`public`, `private`, `unlisted`).
    pub visibility: String,
    /// Search tags.
    pub tags: Vec<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.
    pub source_owner: String,
    /// Source project from which the asset was exported.
    pub source_project: String,
    /// Source kind (`pipeline` for v1).
    pub source_kind: String,
    /// Source ref such as `pipelines/foo.zf.json`.
    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,
    /// 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,
    MembersRead,
    MembersWrite,
    CredentialsRead,
    CredentialsWrite,
    TemplatesRead,
    TemplatesWrite,
    TemplatesCreate,
    TemplatesDelete,
    TemplatesMove,
    TemplatesDiagnostics,
    PipelinesRead,
    PipelinesWrite,
    PipelinesCreate,
    PipelinesDelete,
    PipelinesMove,
    PipelinesExecute,
    FilesRead,
    FilesWrite,
    FilesDelete,
    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::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::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),
            "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::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::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,
}

/// 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.json` then commits the file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateSettingsSectionRequest {
    /// Git commit message. Shown in the commit dialog before save.
    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.
    pub trigger: 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>,
    /// Flattened tree rows in display order.
    pub items: Vec<TemplateTreeItem>,
}

/// 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, 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>,
    /// SQL DEFAULT expression (e.g. `UUIDV4()`, `NOW()`, a literal value).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_value: Option<String>,
}

/// One managed Simple Table definition stored inside the project runtime DB.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SimpleTableDefinition {
    /// Stable table slug.
    pub table: String,
    /// Display title.
    pub title: 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,
    /// Unix timestamp seconds.
    pub created_at: i64,
    /// Unix timestamp seconds.
    pub updated_at: i64,
}

/// 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,
}

/// 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,
    /// 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,
    /// Optional display title.
    pub title: Option<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>,
}

/// Update payload for an existing sekejap table (attributes + indexes).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UpdateSimpleTableRequest {
    /// Optional new display title.
    pub title: Option<String>,
    /// 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.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectFileLayout {
    /// `{data_root}/users/{owner}/{project}`
    pub root: PathBuf,
    /// `.../data`
    pub data_dir: PathBuf,
    /// `.../data/runtime`
    pub data_runtime_dir: PathBuf,
    /// `.../data/runtime/pipelines`
    pub data_runtime_pipelines_dir: PathBuf,
    /// `.../files`
    pub files_dir: PathBuf,
    /// `.../repo` (git-sync workspace root).
    pub repo_dir: PathBuf,
    /// `.../repo/.git`
    pub repo_git_dir: PathBuf,
    /// `.../repo/pipelines` — unified source root: *.zf.json pipelines + *.tsx templates + *.ts scripts.
    /// Also the @/ root for the RWE compiler.
    pub repo_pipelines_dir: PathBuf,
    /// `.../repo/docs` (project docs: ERD, README.md, AGENTS.md, use cases, etc.; UI label may be "Schema")
    pub repo_docs_dir: PathBuf,
    /// `.../repo/zebflow.json` (Layer 2 non-sensitive project config, git-synced).
    pub zebflow_json_file: PathBuf,
    /// `.../data/runtime/agent_docs` (AGENTS.md, SOUL.md, MEMORY.md — agent context)
    pub agent_docs_dir: PathBuf,
    /// `.../repo/nodes` — installed composite/WASM node packages.
    pub repo_nodes_dir: PathBuf,
}

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

/// Source type of a node package.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum NodePackageSource {
    /// Composite node: function pipeline + manifest.
    Composite,
    /// WASM node: sandboxed binary module (Extism).
    Wasm,
}

/// Runtime configuration for a composite node package.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CompositeNodeRuntime {
    /// Relative filename of the inner function pipeline (e.g. `"pipeline.zf.json"`).
    pub pipeline: String,
}

/// Runtime configuration for a WASM node package (future).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WasmNodeRuntime {
    /// Relative filename of the WASM module (e.g. `"module.wasm"`).
    pub module: String,
    /// ABI identifier (e.g. `"extism-json-v1"`).
    pub abi: String,
    /// Export function map.
    #[serde(default)]
    pub exports: HashMap<String, String>,
}

/// Parsed `node.json` / `definition.json` manifest for an installed node package.
///
/// For single-node packages (v1 `node.json`), `definition` is set directly.
/// For multi-node packages (`definition.json`), the loader explodes the package
/// into one `NodePackageManifest` per node, each carrying the shared credentials
/// and functions map.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodePackageManifest {
    /// Package source type.
    pub source: NodePackageSource,
    /// Semver version string.
    pub version: String,
    /// The node definition (same struct as native nodes).
    pub definition: crate::pipeline::NodeDefinition,
    /// Custom credential type definitions provided by this package.
    #[serde(default)]
    pub credentials: Vec<CredentialTypeDef>,
    /// Composite runtime config (present when `source == Composite`, v1 single-pipeline).
    #[serde(default)]
    pub runtime: Option<CompositeNodeRuntime>,
    /// WASM runtime config (present when `source == Wasm`).
    #[serde(default)]
    pub wasm_runtime: Option<WasmNodeRuntime>,
    /// Function name → relative file path map (multi-node packages).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub functions: HashMap<String, String>,
    /// Name of the main function (action nodes in multi-node packages).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub main_function: Option<String>,
    /// Trigger configuration (composite trigger nodes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<PackageTriggerConfig>,
    /// Lifecycle hooks (on_activate, on_deactivate).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lifecycle: Option<PackageLifecycleConfig>,
    /// Package slug (directory name), set by the loader.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub package_slug: String,
}

/// Trigger configuration for a composite trigger node.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
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/{{ bot_credential_id }}"` resolves from node config.
    #[serde(default)]
    pub path_template: Option<String>,
    /// Function name that transforms inbound events.
    #[serde(default)]
    pub on_message: Option<String>,
}

/// Lifecycle hook configuration for a composite node.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PackageLifecycleConfig {
    /// Function to run when the pipeline is activated.
    #[serde(default)]
    pub on_activate: Option<String>,
    /// Function to run when the pipeline is deactivated.
    #[serde(default)]
    pub on_deactivate: Option<String>,
}

/// 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)]
pub struct MultiNodePackageDefinition {
    /// Package identifier.
    pub package: String,
    /// Semver version.
    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 type definitions shared by all nodes.
    #[serde(default)]
    pub credentials: Vec<CredentialTypeDef>,
    /// Function name → relative pipeline file path.
    #[serde(default)]
    pub functions: HashMap<String, String>,
    /// WASM runtime config shared by WASM node entries in this package.
    #[serde(default, rename = "wasm")]
    pub wasm_runtime: Option<WasmNodeRuntime>,
    /// Node entries.
    pub nodes: Vec<MultiNodeEntry>,
}

/// A single node entry within a multi-node package.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiNodeEntry {
    /// Node kind (e.g. `"n.c.tg.send"`).
    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,
    /// Main function name (action nodes).
    #[serde(default)]
    pub main: Option<String>,
    /// Trigger configuration (trigger nodes).
    #[serde(default)]
    pub trigger: Option<PackageTriggerConfig>,
    /// Lifecycle hooks.
    #[serde(default)]
    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)]
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 fields: Vec<crate::pipeline::NodeFieldDef>,
    #[serde(default)]
    pub layout: Vec<crate::pipeline::model::LayoutItem>,
    #[serde(default)]
    pub dsl_flags: Vec<crate::pipeline::model::DslFlag>,
}

/// Runtime-enriched entry for an installed node package.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstalledNodePackage {
    /// The slug (directory name under `repo/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,
    /// Whether an `icon.svg` exists in the package.
    pub has_icon: bool,
}

/// 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,
}

/// Layer 2 project config stored in `repo/zebflow.json` (git-synced, non-sensitive).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZebflowJson {
    #[serde(default = "default_zebflow_json_version")]
    pub version: String,
    #[serde(default)]
    pub metadata: ZebflowJsonMetadata,
    #[serde(default)]
    pub configs: ZebflowJsonConfigs,
    #[serde(default)]
    pub distribution: ZebflowJsonDistribution,
}

fn default_zebflow_json_version() -> String {
    "1.0".to_string()
}

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 {
            version: default_zebflow_json_version(),
            metadata: ZebflowJsonMetadata::default(),
            configs: ZebflowJsonConfigs::default(),
            distribution: ZebflowJsonDistribution::default(),
        }
    }
}

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

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ZebflowJsonConfigs {
    #[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,
}

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

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

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ZebflowJsonFiles {
    #[serde(default)]
    pub uploads: ZebflowJsonUploads,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
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)]
pub struct ZebflowJsonDistribution {
    #[serde(default)]
    pub hub: ZebflowJsonDistributionHub,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
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 stored in `zebflow.json` — controls which resources agents cannot access.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
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 section of `zebflow.json`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ZebflowJsonGit {
    #[serde(default)]
    pub remote: ZebflowJsonGitRemote,
}

/// Git remote section of `zebflow.json`.
/// Stores remote repository configuration for push/sync operations.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
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 section of `zebflow.json`.
///
/// Controls project-level compile/render behaviour for all `n.web.response` template nodes.
/// Values are merged into [`crate::rwe::ReactiveWebOptions`] at execution time,
/// before each pipeline run. Node-level `--load-scripts` is appended on top.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
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 `--load-scripts` is 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`): `/assets/{owner}/{project}/rwe/scripts/{hash}`
    ///
    /// When set, the prefix replaces `/assets/{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>,
}

/// Enabled library map stored under `rwe.libraries` in `zebflow.json`.
pub type ZebflowJsonRweLibraries = HashMap<String, ZebflowJsonRweLibraryEntry>;

/// One enabled library entry stored in `zebflow.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZebflowJsonRweLibraryEntry {
    /// Pinned packed version string (e.g. `"bridge-0.1"`).
    pub version: String,
    /// Source kind: `"offline"` (embedded binary) or `"online"` (CDN fetch).
    pub source: String,
}

/// Lock file model — stored at `repo/zeb.lock` (git-tracked).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ZebLock {
    /// Schema version; current is 1.
    pub version: u32,
    /// Locked library entries keyed by library name.
    #[serde(default)]
    pub libraries: HashMap<String, ZebLockEntry>,
}

/// One locked library entry in `zeb.lock`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZebLockEntry {
    /// Pinned packed version string (e.g. `"bridge-0.1"`).
    pub version: String,
    /// Source kind: `"offline"` or `"online"`.
    pub source: String,
    /// Relative runtime entry path (e.g. `"runtime/threejs.bundle.mjs"`).
    pub entry: String,
    /// SHA-256 integrity hash of the bundle file; `None` for embedded bridge bundles.
    pub integrity: Option<String>,
}

pub fn default_rwe_strict_mode() -> bool {
    true
}

/// API request to update the project-level RWE settings in `zebflow.json`.
#[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 section of zebflow.json.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ZebflowJsonLogging {
    /// Max invocation entries to retain per pipeline. Defaults to 10.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_invocations: Option<u32>,
}

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

/// One recorded pipeline invocation.
#[derive(Debug, Clone, Serialize, Deserialize)]
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 section of zebflow.json.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
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 control-plane payload used to materialize a project onto another office.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct ProjectRuntimeMaterializationRequest {
    /// Portable project runtime bundle.
    #[serde(default)]
    pub bundle: ProjectRuntimeBundle,
    /// Runtime credentials to materialize locally on the destination office.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub credentials: Vec<ProjectCredential>,
    /// Runtime DB connections to materialize locally on the destination office.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub db_connections: Vec<ProjectDbConnection>,
}

/// 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,
}

/// 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,
}

/// 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,
}

/// 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,
}

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

    /// 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",
        }
    }
}

/// Versioned manifest embedded in exported project portability archives.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProjectTransferManifest {
    /// Manifest schema version.
    pub schema_version: String,
    /// Stable owner id.
    pub owner: String,
    /// Stable project slug.
    pub project: String,
    /// Exported artifact type.
    pub artifact_kind: ProjectTransferArtifactKind,
    /// Office that produced the archive.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_office_id: Option<String>,
    /// Controller that instructed the export, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_controller_id: Option<String>,
    /// Unix timestamp seconds.
    pub exported_at: i64,
    /// Repo-owned runtime profile at export time.
    #[serde(default)]
    pub runtime_profile: ProjectRuntimeProfile,
    /// Environment-owned placement snapshot at export time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placement: Option<ProjectRuntimePlacement>,
    /// File count inside `repo/` when exporting a bundle.
    #[serde(default)]
    pub repo_file_count: u64,
    /// File count inside `data/` when exporting a bundle.
    #[serde(default)]
    pub data_file_count: u64,
    /// File count inside `files/` when exporting project FS objects.
    #[serde(default)]
    pub files_file_count: u64,
    /// Total exported payload bytes before tar packaging.
    #[serde(default)]
    pub total_bytes: u64,
}

/// 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,
}

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",
        }
    }
}

/// 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,
}

/// 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,
    }
}

/// 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,
}

/// 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_connections" => Some(ProjectCapability::TablesRead),
        "describe_connection" => 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),
        "describe_pipeline" => Some(ProjectCapability::PipelinesRead),
        "register_pipeline" => Some(ProjectCapability::PipelinesWrite),
        "patch_pipeline" => Some(ProjectCapability::PipelinesWrite),
        "run_ephemeral" => Some(ProjectCapability::PipelinesExecute),
        "git_command" => Some(ProjectCapability::PipelinesWrite),
        "write_template" => Some(ProjectCapability::TemplatesWrite),
        "write_doc" => Some(ProjectCapability::TemplatesWrite),
        "list_agent_docs" => Some(ProjectCapability::SettingsRead),
        "read_agent_doc" => Some(ProjectCapability::SettingsRead),
        "write_agent_doc" => Some(ProjectCapability::SettingsWrite),
        // 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_patch" => Some(ProjectCapability::PipelinesWrite),
        "pipeline_activate" => Some(ProjectCapability::PipelinesWrite),
        "pipeline_deactivate" => Some(ProjectCapability::PipelinesWrite),
        "pipeline_execute" => Some(ProjectCapability::PipelinesExecute),
        "pipeline_run" => Some(ProjectCapability::PipelinesExecute),
        "pipeline_get_invocations" => Some(ProjectCapability::PipelinesRead),
        "template_list" => Some(ProjectCapability::TemplatesRead),
        "template_get" => Some(ProjectCapability::TemplatesRead),
        "template_create" => Some(ProjectCapability::TemplatesCreate),
        "template_write" => Some(ProjectCapability::TemplatesWrite),
        "template_search" => Some(ProjectCapability::TemplatesRead),
        "template_edit" => Some(ProjectCapability::TemplatesWrite),
        "template_outline" => Some(ProjectCapability::TemplatesRead),
        "template_deps" => Some(ProjectCapability::TemplatesRead),
        "template_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_project_list" => Some(ProjectCapability::ProjectRead),
        "docs_project_read" => Some(ProjectCapability::ProjectRead),
        "docs_project_write" => Some(ProjectCapability::TemplatesWrite),
        "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),
        // UI catalog install tools
        "list_ui_catalog" => Some(ProjectCapability::PipelinesRead),
        "install_ui_components" => Some(ProjectCapability::PipelinesWrite),
        // Move resource (requires both pipelines write + templates write — use higher capability)
        "move_resource" => Some(ProjectCapability::PipelinesWrite),
        _ => None,
    }
}