persona-wire-core 0.10.0

persona-wire core: Domain (Graph + Specification + Compute + Constraint + AutoVersion + CRUD) + Application (NamedProjection registry, Use Case) + Infrastructure (SQLite storage, Rendering adapter). Transport-agnostic.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
//! Use cases — orchestration of Domain + Infrastructure for wire_* flows.

use crate::application::plugin_registry::PluginRegistry;
use crate::application::projection_registry::{ProjectionRegistry, TargetForm};
use crate::application::spec_registry::SpecRegistry;
use crate::domain::error::{DomainError, WireError, WireResult};
use crate::domain::graph::Node;
use crate::domain::port::ProjectionInput;
use crate::domain::specification::Specification;
use crate::infrastructure::storage::SqliteStorage;

/// Resolve a `TemplateEngine` from `registry` by id, falling back to the
/// `"handlebars"` default when `hint` is `None`. Surfaces a structured
/// `WireError::Storage` when neither the hinted id nor the default is
/// registered. P3a Phase 2 (b) — common helper for the 3 use_case render sites.
fn resolve_engine_render(
    registry: &PluginRegistry,
    hint: Option<&str>,
    template: &str,
    data: &serde_json::Value,
) -> WireResult<String> {
    let id = hint.unwrap_or("handlebars");
    let engine = registry
        .engine(id)
        .ok_or_else(|| WireError::Storage(format!("template engine '{id}' not registered")))?;
    engine.render(template, data)
}

/// Assert that `projection_kind` is one of the synchronous-safe values
/// (`None` or `Some("static")`). Returns a structured error otherwise so the
/// caller surfaces a clear "use the async path" message instead of silently
/// falling back to the engine-direct sync path.
///
/// P3a Phase 2 (c) — guards `wire_init` / `wire_render` (both sync). Any
/// `projection_kind` other than `"static"` only animates through
/// `wire_prompt_context`, which is async.
fn assert_static_projection_kind(
    projection_name: &str,
    projection_kind: Option<&str>,
) -> WireResult<()> {
    match projection_kind {
        None | Some("static") => Ok(()),
        Some(other) => Err(WireError::Other(format!(
            "projection '{projection_name}' has projection_kind '{other}' — \
             non-static kinds require the async path; use wire_prompt_context instead"
        ))),
    }
}

/// Build the broadcast-shape render data JSON for sync use cases
/// (`wire_init` / `wire_render`).
///
/// Shape:
/// ```json
/// { "count": N, "names": "id1, id2, …", "nodes": [...], "persona_id": "…" }
/// ```
///
/// `persona_id` is included only when `Some` is passed; `wire_render` calls
/// with `None` since it is name-addressed (no implicit persona scope).
///
/// Step C-6 phase 2 — broadcast data shape (graph spec result aggregated
/// into a single object) is distinct from the per-slot shape used by the
/// async `wire_prompt_context` path; see the crate-level "Slot vocabulary"
/// rationale in [`crate`] docs.
fn build_broadcast_render_data(matched: &[Node], persona_id: Option<&str>) -> serde_json::Value {
    let names: Vec<&str> = matched.iter().map(|n| n.name.as_str()).collect();
    let nodes_json: Vec<serde_json::Value> = matched
        .iter()
        .map(|n| {
            serde_json::json!({
                "id": n.id,
                "type": n.r#type,
                "metadata": n.metadata,
            })
        })
        .collect();
    let mut obj = serde_json::json!({
        "count": matched.len(),
        "names": names.join(", "),
        "nodes": nodes_json,
    });
    if let Some(pid) = persona_id {
        obj.as_object_mut()
            .expect("json!({...}) constructs an object")
            .insert("persona_id".to_string(), serde_json::json!(pid));
    }
    obj
}

/// Render a Projection against a pre-built data JSON via the **sync** engine
/// path (`wire_init` / `wire_render`). Encapsulates the shared post-spec
/// dispatch: plugin parts extraction, static-kind guard, engine render, and
/// `RenderedProjection` construction.
///
/// Non-static projection kinds (e.g. `llm`) surface a structured error so the
/// caller hops to `wire_prompt_context` (async) instead of silently falling
/// back to engine-direct rendering.
///
/// Step C-6 phase 2 — shared by both sync use cases; the async path uses
/// `resolve_projection_render_async` (full plugin Projection dispatch).
fn render_named_projection_sync(
    proj: &crate::domain::entity::Projection,
    data: &serde_json::Value,
    registry: &PluginRegistry,
) -> WireResult<RenderedProjection> {
    let (engine_hint, kind_hint, _config) = proj.plugin().to_optional_parts();
    assert_static_projection_kind(proj.name().as_str(), kind_hint)?;
    let rendered = resolve_engine_render(registry, engine_hint, proj.template().as_str(), data)?;
    Ok(RenderedProjection {
        name: proj.name().as_str().to_owned(),
        target_form: proj.target_form(),
        rendered,
    })
}

/// Async render path that dispatches through `PluginRegistry`'s `Projection`
/// axis. Used by `wire_prompt_context` (already async). Sync use cases
/// short-circuit through `resolve_engine_render` after
/// `assert_static_projection_kind`.
///
/// Resolution order:
/// - `template_engine_hint` (defaults to `"handlebars"`) — sanity-checked against
///   the registry to surface unknown-engine errors early; the actual engine is
///   held by the resolved [`ProjectionRenderer`] adapter (Hole-1 解消).
/// - `projection_kind_hint` (defaults to `"static"`)
///
/// Both must be registered in `registry`; missing ids surface a structured
/// `WireError::Storage`.
///
/// P3a Phase 2 (c) — the actual consumer of `NamedProjection.projection_kind`.
///
/// [`ProjectionRenderer`]: crate::domain::port::ProjectionRenderer
#[allow(clippy::too_many_arguments)]
async fn resolve_projection_render_async(
    registry: &PluginRegistry,
    template_engine_hint: Option<&str>,
    projection_kind_hint: Option<&str>,
    template: &str,
    target_form: TargetForm,
    spec_result: &serde_json::Value,
    persona_id: Option<&str>,
    config: Option<&serde_json::Value>,
) -> WireResult<String> {
    let engine_id = template_engine_hint.unwrap_or("handlebars");
    if registry.engine(engine_id).is_none() {
        return Err(WireError::Storage(format!(
            "template engine '{engine_id}' not registered"
        )));
    }
    let kind_id = projection_kind_hint.unwrap_or("static");
    let projection = registry
        .projection(kind_id)
        .ok_or_else(|| WireError::Storage(format!("projection kind '{kind_id}' not registered")))?;
    let null = serde_json::Value::Null;
    let input = ProjectionInput {
        spec_result,
        template,
        target_form,
        persona_id,
        config: config.unwrap_or(&null),
    };
    projection.render(input).await
}

// ---- wire_init ----

pub struct WireInitInput {
    pub persona_id: String,
}

#[derive(Debug)]
pub struct RenderedProjection {
    pub name: String,
    pub target_form: TargetForm,
    pub rendered: String,
}

pub struct WireInitOutput {
    pub persona_id: String,
    pub projections: Vec<RenderedProjection>,
    pub warnings: Vec<String>,
}

/// Run every registered NamedProjection against the current graph and return
/// the rendered context bundle. **P1 互換 (sync)** = wire 内 graph の data 本体
/// を render する旧 path。 新規 `wire_prompt_context` (async + Adapter 経由) で
/// Layer 6 Adapter fresh fetch 経路に置き換える前提、 本 fn は P1 contract / test
/// 維持のため sync で残す。
pub fn wire_init(
    input: WireInitInput,
    storage: &SqliteStorage,
    registry: &PluginRegistry,
) -> WireResult<WireInitOutput> {
    let spec_reg = SpecRegistry::new(storage);
    let proj_reg = ProjectionRegistry::new(storage);

    let mut projections = Vec::new();
    let mut warnings = Vec::new();

    for name in proj_reg.list()? {
        let Some(proj) = proj_reg.get(&name)? else {
            continue;
        };
        let Some(spec) = spec_reg.get(proj.spec_ref().as_str())? else {
            warnings.push(format!(
                "projection '{name}': spec_ref '{}' not registered",
                proj.spec_ref()
            ));
            continue;
        };

        let matched = collect_matching_nodes(storage, &spec)?;
        let data = build_broadcast_render_data(&matched, Some(input.persona_id.as_str()));
        projections.push(render_named_projection_sync(&proj, &data, registry)?);
    }

    Ok(WireInitOutput {
        persona_id: input.persona_id,
        projections,
        warnings,
    })
}

// ---- wire_prompt_context (Layer 6 Adapter + persona-pack 配線 SoT 経路) ----

#[derive(Debug)]
pub struct WirePromptContextInput {
    pub persona_id: String,
    /// `Some(["active", "ng"])` で該当 slot のみ render、 `None` で全 slot。
    pub projection_names: Option<Vec<String>>,
    /// `Some(["mail", "news"])` で該当 slot を除外、 `None` で除外なし。
    /// `projection_names` と組み合わせ可 — semantics は AND NOT:
    ///
    /// | projection_names | projection_exclude_names | 結果集合                            |
    /// |------------------|--------------------------|-------------------------------------|
    /// | None             | None                     | 全 projection (現挙動互換)          |
    /// | Some([...])      | None                     | include 集合のみ (現挙動互換)       |
    /// | None             | Some([...])              | 全 projection \ exclude             |
    /// | Some([...])      | Some([...])              | include \ exclude (AND NOT)         |
    ///
    /// 交差時は exclude が優先 (= 明示除外が勝つ)、 未登録 name は無視
    /// (warning なし、 後方互換性優先)、 結果空集合は空 context 返却。
    pub projection_exclude_names: Option<Vec<String>>,
}

#[derive(Debug)]
pub struct WirePromptContextOutput {
    pub persona_id: String,
    /// 全 projection を rendered block 化して concat した PromptContext literal。
    pub prompt_context: String,
    /// 個別 rendered block (= 各 projection 1 件)。
    pub projections: Vec<RenderedProjection>,
    pub warnings: Vec<String>,
}

/// 各 slot 1 件の Phase 1 sync collect 結果。
struct CollectedSlot {
    slot: String,
    source_uri: String,
    target_form: TargetForm,
    template: String,
    /// P3a Phase 2 (b) — NamedProjection 由来の `template_engine` を Phase 2
    /// render dispatch まで運ぶ。 None → `"handlebars"` default。
    template_engine: Option<String>,
    /// P3a Phase 2 (c) — NamedProjection 由来の `projection_kind` を Phase 2
    /// render dispatch まで運ぶ。 None → `"static"` default。
    projection_kind: Option<String>,
    /// P3a Phase 2 (c) — NamedProjection 由来の `projection_config` を Phase 2
    /// render dispatch まで運ぶ (例: LLM endpoint / cache TTL)。
    projection_config: Option<serde_json::Value>,
    /// Projection 名 (= `<persona>.section.<slot>`)。 エラー / warning メッセージで
    /// projection を指し示すのに使う。
    projection_name: String,
}

/// 全 builtin slot (or projection_names で subset) を iterate し、 各 slot の
/// **配線 (source_uri)** を **wire DB の wiring entry `<persona>.<slot>`** から取得、
/// **template** を 3 段優先 (1: persona-pack overlay × `MergeStrategy.merge` / 2: wire
/// DB の動的 register projection `<persona>.section.<slot>` / 3: `BUILTIN_PROJECTIONS`)
/// で解決して Adapter で fresh fetch + render し、 全 slot を concat した
/// **PromptContext** を 1 call で return する `/wake` 用 entry。
///
/// 設計確定 (2026-06-16 reframe):
/// - 配線 SoT = **wire DB wiring entry**。 persona-pack には書かない (= 二重管理 drift 防止)
/// - persona-pack `[extra.persona_wire.projections.<slot>]` は **Projection template の
///   Overlay only** (persona 固有 emote / register 等を `MergeStrategy` 指定で被せる)
/// - `projection_names: Some([...])` で subset 指定可能 (= 動的 Selection)
pub async fn wire_prompt_context(
    input: WirePromptContextInput,
    storage: std::sync::Arc<std::sync::Mutex<SqliteStorage>>,
    registry: &PluginRegistry,
) -> WireResult<WirePromptContextOutput> {
    let overlays = resolve_persona_overlays(&input.persona_id, registry).await;

    let mut warnings = Vec::new();
    let collected: Vec<CollectedSlot> = {
        let s = storage.lock().map_err(|_| {
            crate::domain::error::WireError::Storage("storage mutex poisoned".to_string())
        })?;
        let proj_reg = ProjectionRegistry::new(&s);
        let slots = enumerate_slot_names(
            &s,
            &input.persona_id,
            input.projection_names.as_deref(),
            input.projection_exclude_names.as_deref(),
        )?;
        let mut out: Vec<CollectedSlot> = Vec::new();
        for slot in &slots {
            if let Some(c) = collect_slot(
                slot,
                &input.persona_id,
                &s,
                &proj_reg,
                &overlays,
                &mut warnings,
            )? {
                out.push(c);
            }
        }
        out
    };

    let mut projections = Vec::new();
    for c in &collected {
        projections.push(
            render_collected_slot_async(c, &input.persona_id, registry, &mut warnings).await?,
        );
    }

    let prompt_context = projections
        .iter()
        .map(|p| p.rendered.as_str())
        .collect::<Vec<_>>()
        .join("\n");

    Ok(WirePromptContextOutput {
        persona_id: input.persona_id,
        prompt_context,
        projections,
        warnings,
    })
}

/// Phase 0 — async overlay resolution via PluginRegistry adapter dispatch.
///
/// URI 形式 = `persona-pack://<persona_id>/projections`。 persona-pack scheme は
/// 外部 adapter crate (`persona-wire-adapter-persona-pack`) が提供する ACL Facade。
/// boot 側 (`persona-wire-mcp` / `persona-wire` bin) で registry に inject 済
/// (未 inject = scheme 未登録 → overlay 空で fallback、 adapter fetch fail も同様)。
async fn resolve_persona_overlays(
    persona_id: &str,
    registry: &PluginRegistry,
) -> std::collections::BTreeMap<String, crate::application::projection_overlay::ProjectionOverlay> {
    use crate::application::projection_overlay::parse_overlay_response;
    let overlay_uri = format!("persona-pack://{}/projections", persona_id);
    match registry.route(&overlay_uri) {
        Ok((adapter, uri)) => match adapter.fetch(&uri).await {
            Ok(v) => parse_overlay_response(&v).unwrap_or_default(),
            Err(_) => std::collections::BTreeMap::new(),
        },
        Err(_) => std::collections::BTreeMap::new(),
    }
}

/// Phase 1 helper — slot 名集合を確定する。 `explicit` で subset 指定があれば
/// そのまま使い、 None なら wire DB の wiring entry (= persona-scoped Node) を
/// spec query で全件取得し、 `wiring_mapper::extract_slot` 経由で slot 名を
/// 抽出する (storage 互換 key `metadata.axis` の直リードは禁止、
/// crate-level "Slot vocabulary" rationale 参照)。
///
/// `exclude` で除外 slot 名集合を指定すると、 `explicit` / 全件 enumerate の
/// 結果から exclude 集合を引いた残りを返す (`WirePromptContextInput`
/// docstring の AND NOT semantics 参照)。 交差時は exclude 優先 (= 明示除外が
/// 勝つ)、 未登録 name は無視。
fn enumerate_slot_names(
    storage: &SqliteStorage,
    persona_id: &str,
    explicit: Option<&[String]>,
    exclude: Option<&[String]>,
) -> WireResult<Vec<String>> {
    use crate::application::wiring_mapper;
    let base: Vec<String> = if let Some(names) = explicit {
        names.to_vec()
    } else {
        let spec = Specification::And(vec![
            Specification::TypeIs(wiring_mapper::WIRING_TYPE.to_string()),
            Specification::MetadataEq {
                path: wiring_mapper::META_PERSONA.to_string(),
                value: serde_json::json!(persona_id),
            },
        ]);
        let nodes = collect_matching_nodes(storage, &spec)?;
        nodes
            .iter()
            .filter_map(|n| wiring_mapper::extract_slot(n).map(str::to_owned))
            .collect()
    };
    if let Some(skip) = exclude {
        if !skip.is_empty() {
            let skip_set: std::collections::BTreeSet<&str> =
                skip.iter().map(String::as_str).collect();
            return Ok(base
                .into_iter()
                .filter(|s| !skip_set.contains(s.as_str()))
                .collect());
        }
    }
    Ok(base)
}

/// Phase 1 per-slot collect — 1 slot 分の wiring entry resolve + base projection
/// lookup + overlay merge を行い、 Phase 2 (async) に渡す `CollectedSlot` を返す。
///
/// 返値:
/// - `Ok(Some(_))` — 配線 + projection 完備、 render 対象
/// - `Ok(None)` — 未配線 (silent skip)、 source_uri 不在 (warning push)、
///   projection 未登録 (warning push) のいずれか
///
/// 名前 derive は `application::projection_naming` に集約 (doctor Probe 等が
/// 同じ rule で resolve できるよう single SoT 化、 issue 19d888ee / 25544968)。
fn collect_slot(
    slot: &str,
    persona_id: &str,
    storage: &SqliteStorage,
    proj_reg: &ProjectionRegistry,
    overlays: &std::collections::BTreeMap<
        String,
        crate::application::projection_overlay::ProjectionOverlay,
    >,
    warnings: &mut Vec<String>,
) -> WireResult<Option<CollectedSlot>> {
    let node_id = format!("{}.{}", persona_id, slot);
    let Some(node) = storage.get_node_by_name(&node_id)? else {
        return Ok(None);
    };
    let Some(source_uri) = crate::application::wiring_mapper::extract_source_uri(&node) else {
        warnings.push(format!(
            "wiring entry '{node_id}' lacks metadata.source_uri — slot skipped"
        ));
        return Ok(None);
    };

    let projection_name =
        crate::application::projection_naming::workflow_emit_projection_name(persona_id, slot);
    let (base_template, base_target, base_engine, base_kind, base_config) =
        match proj_reg.get(&projection_name)? {
            Some(proj) => {
                let (engine, kind, config) = proj.plugin().to_optional_parts();
                (
                    proj.template().as_str().to_owned(),
                    proj.target_form(),
                    engine.map(str::to_owned),
                    kind.map(str::to_owned),
                    config.cloned(),
                )
            }
            None => {
                warnings.push(format!(
                    "slot '{slot}' has no registered projection \
                     '{projection_name}' — slot skipped"
                ));
                return Ok(None);
            }
        };

    // overlay merge (MergeStrategy 経由)。 template_engine / projection_kind
    // / projection_config は overlay schema にまだ field がないため、
    // NamedProjection 由来をそのまま運ぶ (P3a Phase 2 (c))。
    let (final_template, final_target) = if let Some(o) = overlays.get(slot) {
        (o.strategy.merge(&base_template, &o.template), o.target_form)
    } else {
        (base_template, base_target)
    };

    Ok(Some(CollectedSlot {
        slot: slot.to_string(),
        source_uri: source_uri.to_string(),
        target_form: final_target,
        template: final_template,
        template_engine: base_engine,
        projection_kind: base_kind,
        projection_config: base_config,
        projection_name,
    }))
}

/// Phase 2 per-slot async fetch + render — Adapter dispatch で fresh fetch、
/// `Projection` trait dispatch で render、 `RenderedProjection` を返す。
///
/// fetch fail / route fail は `serde_json::Value::Null` に倒して warning push
/// で先に進む (= 個別 slot の失敗で全体を落とさない best-effort)。
///
/// P3a Phase 2 (c) — `projection_kind` default は `"static"` (=
/// `StaticProjection` = engine-direct 相当)、 外部 Projection plugin (例 `llm`)
/// はここを経由してのみ animate する (sync use cases は通らない)。
async fn render_collected_slot_async(
    c: &CollectedSlot,
    persona_id: &str,
    registry: &PluginRegistry,
    warnings: &mut Vec<String>,
) -> WireResult<RenderedProjection> {
    let fetched = match registry.route(&c.source_uri) {
        Ok((adapter, uri)) => match adapter.fetch(&uri).await {
            Ok(v) => v,
            Err(e) => {
                warnings.push(format!(
                    "adapter fetch failed for slot '{}' (uri={}): {e}",
                    c.slot, c.source_uri
                ));
                serde_json::Value::Null
            }
        },
        Err(e) => {
            warnings.push(format!(
                "registry route failed for slot '{}' (uri={}): {e}",
                c.slot, c.source_uri
            ));
            serde_json::Value::Null
        }
    };
    let entries = vec![serde_json::json!({
        "wiring_entry": {
            "slot": c.slot,
            "source_uri": c.source_uri,
        },
        "fetched_data": fetched,
    })];
    let data = serde_json::json!({
        "count": 1,
        "slot": c.slot,
        "entries": entries,
        "persona_id": persona_id,
    });
    let rendered = resolve_projection_render_async(
        registry,
        c.template_engine.as_deref(),
        c.projection_kind.as_deref(),
        &c.template,
        c.target_form,
        &data,
        Some(persona_id),
        c.projection_config.as_ref(),
    )
    .await?;
    Ok(RenderedProjection {
        name: c.projection_name.clone(),
        target_form: c.target_form,
        rendered,
    })
}

/// Iterate every registered node type and collect nodes matching `spec`.
fn collect_matching_nodes(storage: &SqliteStorage, spec: &Specification) -> WireResult<Vec<Node>> {
    let mut out = Vec::new();
    for t in storage.list_types_by_kind("node")? {
        for n in storage.list_nodes_by_type(&t)? {
            if spec.is_satisfied_by(&n) {
                out.push(n);
            }
        }
    }
    Ok(out)
}

// ---- graph scan (shared by wire_close + wire_doctor) ----

/// Shared graph health summary used by `wire_close` (persona-scoped report)
/// and `wire_doctor` (orphan-only diagnostic).
pub struct GraphScanSummary {
    pub orphan_node_count: usize,
    pub total_node_count: usize,
    pub total_edge_count: usize,
}

/// A wiring entry is "self-attached" — and therefore not an orphan — when it
/// carries either a `metadata.source_uri` (it points at an external SoT via
/// Layer 6 Adapter and stands alone without edges; per onboarding §2 edges
/// are "optional but recommended") or `metadata.maintenance_exempt = true`
/// (the node is explicitly opted-out of session-cyclic maintenance, e.g.
/// `priorities` / `tick_log` / `journal` slots).
///
/// Without this guard, `wire_doctor` reports every wiring entry as orphan
/// (issue `15a46ce6` — 41/41 false-positive on the shi dogfood session).
pub(crate) fn is_self_attached_wiring(node: &crate::domain::graph::Node) -> bool {
    use crate::application::wiring_mapper;
    if !node.metadata.is_object() {
        return false;
    }
    let has_source_uri = wiring_mapper::extract_source_uri(node)
        .map(|s| !s.is_empty())
        .unwrap_or(false);
    let is_exempt = wiring_mapper::extract_maintenance_exempt(node);
    has_source_uri || is_exempt
}

/// Walk every node type and tally totals + orphan count. A node is counted as
/// an orphan only when it has no in- or out-edges **and** is not a
/// self-attached wiring entry (see `is_self_attached_wiring`). Shared scan
/// primitive for `wire_close` / `wire_doctor`; P3 daemon will extend this with
/// stale / asymmetric / high-fanout checks.
///
/// `workflow_def` Node は graph axis 検知対象集合に含まれない (issue
/// `f3bb100e` — Workflow Entity は trigger / action で動作完結、 edge を
/// 持たないのが正常) ため、 本集計でも除外する。 さもなくば `wire_close`
/// 経路でも workflow node を orphan として false-positive 算入していた。
pub fn graph_scan_summary(storage: &SqliteStorage) -> WireResult<GraphScanSummary> {
    use crate::application::workflow_mapper::WORKFLOW_TYPE;
    let mut total_nodes = 0_usize;
    let mut total_edges = 0_usize;
    let mut orphan = 0_usize;

    for t in storage.list_types_by_kind("node")? {
        if t == WORKFLOW_TYPE {
            continue;
        }
        for n in storage.list_nodes_by_type(&t)? {
            total_nodes += 1;
            let out_edges = storage.list_edges_from(&n.id)?;
            let in_edges = storage.list_edges_to(&n.id)?;
            total_edges += out_edges.len();
            if out_edges.is_empty() && in_edges.is_empty() && !is_self_attached_wiring(&n) {
                orphan += 1;
            }
        }
    }

    Ok(GraphScanSummary {
        orphan_node_count: orphan,
        total_node_count: total_nodes,
        total_edge_count: total_edges,
    })
}

// ---- wire_close ----

pub struct WireCloseInput {
    pub persona_id: String,
}

pub struct WireCloseOutput {
    pub persona_id: String,
    pub orphan_node_count: usize,
    pub total_node_count: usize,
    pub total_edge_count: usize,
    pub report_markdown: String,
}

/// Minimal lifecycle scan for the `/work-close` auto-call. P1 reports orphan
/// nodes (no in- or out-edges) and graph totals. P3 will expand this to
/// stale / asymmetric / high-fanout scan + Daily report emit.
pub fn wire_close(input: WireCloseInput, storage: &SqliteStorage) -> WireResult<WireCloseOutput> {
    let summary = graph_scan_summary(storage)?;
    let persona = &input.persona_id;
    let report_markdown = format!(
        "# wire_close report for `{persona}`\n\n\
         - total nodes: {total_nodes}\n\
         - total edges: {total_edges}\n\
         - orphan nodes (no edges, not self-attached): {orphan}\n",
        total_nodes = summary.total_node_count,
        total_edges = summary.total_edge_count,
        orphan = summary.orphan_node_count,
    );

    Ok(WireCloseOutput {
        persona_id: input.persona_id,
        orphan_node_count: summary.orphan_node_count,
        total_node_count: summary.total_node_count,
        total_edge_count: summary.total_edge_count,
        report_markdown,
    })
}

// ---- wire_doctor ----

/// Finding-driven 2-axis (graph / workflow) health diagnostic output.
pub struct WireDoctorOutput {
    pub report_markdown: String,
}

/// Finding-driven 2-axis (graph / workflow) health diagnostic (design §3-§8).
///
/// `persona_id = None` → Full mode (全 persona 横串)。
/// `persona_id = Some(id)` → Persona-scoped mode (当該 persona に紐づく
/// Finding のみ列挙、 main thread context を汚さない用)。
///
/// 内部は [`crate::application::doctor::run`] (Probe registry) に完全委譲、
/// Finding 列挙 + verdict 集約形式の Markdown を返す (design §5 / §8)。
/// 数値カウントが必要なら [`graph_scan_summary`] を別途呼ぶ。
pub fn wire_doctor(
    storage: &SqliteStorage,
    persona_id: Option<String>,
) -> WireResult<WireDoctorOutput> {
    let report_markdown = crate::application::doctor::run(storage, persona_id)?;
    Ok(WireDoctorOutput { report_markdown })
}

// ---- wire_query ----

#[derive(Debug)]
pub struct WireQueryInput {
    /// Either an inline `Specification` AST or a reference to a registered
    /// spec by name. Exactly one of the two must be Some (validated at
    /// the entry).
    pub spec: Option<Specification>,
    pub spec_ref: Option<String>,
    /// Maximum number of matched nodes to return. `None` = unlimited.
    pub limit: Option<usize>,
    /// Number of leading matched nodes to skip. `None` = 0.
    pub offset: Option<usize>,
}

#[derive(Debug)]
pub struct WireQueryNode {
    pub id: String,
    pub name: String,
    pub r#type: String,
    pub metadata: serde_json::Value,
}

#[derive(Debug)]
pub struct WireQueryOutput {
    pub matched: Vec<WireQueryNode>,
    pub total_count: usize,
    pub returned_count: usize,
}

/// Ad-hoc query: evaluate `spec` (inline or by registered name) against the
/// whole graph and return matched nodes in a slim form (id + type + metadata
/// only). Field-level output filtering is a separate concern carried to a
/// future "output values filter" surface (mirrors mini-app's `output_fields`).
pub fn wire_query(input: WireQueryInput, storage: &SqliteStorage) -> WireResult<WireQueryOutput> {
    let resolved: Specification = match (input.spec, input.spec_ref.as_deref()) {
        (Some(s), None) => s,
        (None, Some(id_or_name)) => {
            // spec_ref accepts ULID id OR registered name.
            let name = match storage.resolve_specification_id_or_name(id_or_name)? {
                Some(id) => storage.get_specification_name_by_id(&id)?.ok_or_else(|| {
                    crate::domain::error::WireError::Domain(DomainError::NotFound(format!(
                        "spec: {id_or_name} (resolved id {id} has no row)"
                    )))
                })?,
                None => {
                    return Err(crate::domain::error::WireError::Domain(
                        DomainError::NotFound(format!("spec: {id_or_name}")),
                    ));
                }
            };
            SpecRegistry::new(storage).get(&name)?.ok_or_else(|| {
                crate::domain::error::WireError::Domain(DomainError::NotFound(format!(
                    "spec: {name}"
                )))
            })?
        }
        (Some(_), Some(_)) => {
            return Err(crate::domain::error::WireError::Domain(
                DomainError::InvalidSpec("spec and spec_ref are mutually exclusive".into()),
            ));
        }
        (None, None) => {
            return Err(crate::domain::error::WireError::Domain(
                DomainError::InvalidSpec("either spec or spec_ref is required".into()),
            ));
        }
    };

    let all = collect_matching_nodes(storage, &resolved)?;
    let total_count = all.len();
    let offset = input.offset.unwrap_or(0);
    let slice: Vec<Node> = match input.limit {
        Some(lim) => all.into_iter().skip(offset).take(lim).collect(),
        None => all.into_iter().skip(offset).collect(),
    };
    let returned_count = slice.len();
    let matched = slice
        .into_iter()
        .map(|n| WireQueryNode {
            id: n.id.to_string(),
            name: n.name,
            r#type: n.r#type,
            metadata: n.metadata,
        })
        .collect();

    Ok(WireQueryOutput {
        matched,
        total_count,
        returned_count,
    })
}

// ---- wire_render ----

#[derive(Debug)]
pub struct WireRenderInput {
    /// Name of a registered NamedProjection to evaluate + render.
    pub projection_ref: String,
}

#[derive(Debug)]
pub struct WireRenderOutput {
    pub name: String,
    pub target_form: TargetForm,
    pub rendered: String,
}

/// Render a single registered NamedProjection by name. Counterpart to
/// `wire_init` (which renders every projection at once): use `wire_render`
/// when you want exactly one rendered context, identified by name.
///
/// Ad-hoc inline rendering (spec + template + target_form passed inline,
/// without registration) is carried to a follow-up surface — see
/// `docs/wire-query-spec.md` §8 Future expansion.
pub fn wire_render(
    input: WireRenderInput,
    storage: &SqliteStorage,
    registry: &PluginRegistry,
) -> WireResult<WireRenderOutput> {
    // projection_ref accepts ULID id OR name (v0.7+ id_or_name resolver).
    let projection_name = match storage.resolve_projection_id_or_name(&input.projection_ref)? {
        Some(id) => storage.get_projection_name_by_id(&id)?.ok_or_else(|| {
            crate::domain::error::WireError::Domain(DomainError::NotFound(format!(
                "projection: {} (resolved id {} has no row)",
                input.projection_ref, id
            )))
        })?,
        None => {
            return Err(crate::domain::error::WireError::Domain(
                DomainError::NotFound(format!("projection: {}", input.projection_ref)),
            ));
        }
    };
    let proj = ProjectionRegistry::new(storage)
        .get(&projection_name)?
        .ok_or_else(|| {
            crate::domain::error::WireError::Domain(DomainError::NotFound(format!(
                "projection: {}",
                input.projection_ref
            )))
        })?;
    let spec = SpecRegistry::new(storage)
        .get(proj.spec_ref().as_str())?
        .ok_or_else(|| {
            crate::domain::error::WireError::Domain(DomainError::NotFound(format!(
                "spec_ref (dangling): {}",
                proj.spec_ref()
            )))
        })?;
    let matched = collect_matching_nodes(storage, &spec)?;
    let data = build_broadcast_render_data(&matched, None);
    let r = render_named_projection_sync(&proj, &data, registry)?;
    Ok(WireRenderOutput {
        name: r.name,
        target_form: r.target_form,
        rendered: r.rendered,
    })
}

// ---- wire_context_get (ContextWiring read-aggregate / persona 1-call) ----

/// Input for `wire_context_get`. Just the persona scope.
#[derive(Debug)]
pub struct WireContextGetInput {
    pub persona_id: String,
}

/// Application-layer summary of one `Wiring`. Carries only the fields a
/// caller (MCP / CLI / orchestrator) needs to make routing decisions —
/// the typed `Wiring` Domain Entity stays internal to the entity layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WiringSummary {
    pub slot: String,
    pub source_uri: String,
    /// Registered NamedProjection for this slot, derived as
    /// `<persona>.section.<slot>` (see
    /// [`crate::application::projection_naming::workflow_emit_projection_name`]).
    /// `None` when no projection is registered for the slot yet.
    pub projection_ref: Option<String>,
    pub maintenance_exempt: bool,
}

/// 1-call read view of a `ContextWiring` (per-persona Aggregate boundary).
///
/// Returns the persona's `Wiring` set + `Workflow` set as application-layer
/// summary DTOs. This is the structured counterpart of
/// `wire_prompt_context` (which returns rendered string instead of raw
/// aggregate). Use it when an orchestrator needs the persona's complete
/// wiring topology in one call — e.g. to plan a reset, to inspect routing,
/// or as the pre-render snapshot consumed by future write-side use cases.
#[derive(Debug)]
pub struct WireContextGetOutput {
    pub persona_id: String,
    pub wirings: Vec<WiringSummary>,
    pub workflows: Vec<WorkflowSummary>,
}

/// Walk one persona's consistency boundary and return a structured
/// snapshot. Wiring nodes whose metadata cannot be parsed (drift) are
/// skipped silently — the doctor probes are the surface that flag them.
///
/// Layering: the `ContextWiring` Aggregate Root stays an identity marker
/// in `domain::entity`; this use case owns the Repository traversal so the
/// domain layer keeps no dependency on `application` / `infrastructure`.
pub fn wire_context_get(
    input: WireContextGetInput,
    storage: &SqliteStorage,
) -> WireResult<WireContextGetOutput> {
    use crate::application::wiring_mapper;
    use crate::application::workflow_mapper::WORKFLOW_TYPE;
    use crate::domain::entity::context_wiring::ContextWiring;
    use crate::domain::entity::persona_id::PersonaId;

    let persona = PersonaId::new(input.persona_id.clone())?;
    let context = ContextWiring::new(persona.clone());

    let wirings = list_persona_wirings(&context, storage)?;
    let workflows = list_persona_workflow_summaries(&context, storage)?;

    // Sort by slot / id for stable output (callers compare snapshots).
    let mut wirings = wirings;
    wirings.sort_by(|a, b| a.slot.cmp(&b.slot));
    let mut workflows = workflows;
    workflows.sort_by(|a, b| a.id.cmp(&b.id));

    // Touch the constants once so the wiring spec helper keeps the
    // workflow_def literal aligned with the mapper SoT.
    let _ = (wiring_mapper::WIRING_TYPE, WORKFLOW_TYPE);

    Ok(WireContextGetOutput {
        persona_id: context.persona_id().as_str().to_owned(),
        wirings,
        workflows,
    })
}

/// Persona-scoped wiring summaries. Translates wiring nodes via the
/// `wiring_mapper` and resolves `projection_ref` against the registered
/// `<persona>.section.<slot>` convention.
fn list_persona_wirings(
    context: &crate::domain::entity::context_wiring::ContextWiring,
    storage: &SqliteStorage,
) -> WireResult<Vec<WiringSummary>> {
    use crate::application::projection_naming::workflow_emit_projection_name;
    use crate::application::wiring_mapper::{self, WIRING_TYPE};
    use crate::domain::specification::Specification;

    let spec = Specification::And(vec![
        Specification::TypeIs(WIRING_TYPE.to_string()),
        Specification::MetadataEq {
            path: wiring_mapper::META_PERSONA.to_string(),
            value: serde_json::Value::String(context.persona_id().as_str().to_owned()),
        },
    ]);
    let nodes = collect_matching_nodes(storage, &spec)?;
    let registry = ProjectionRegistry::new(storage);

    let mut out = Vec::with_capacity(nodes.len());
    for node in &nodes {
        let Some(slot) = wiring_mapper::extract_slot(node) else {
            continue;
        };
        let Some(source_uri) = wiring_mapper::extract_source_uri(node) else {
            continue;
        };
        let derived = workflow_emit_projection_name(context.persona_id().as_str(), slot);
        let projection_ref = if registry.get(&derived)?.is_some() {
            Some(derived)
        } else {
            None
        };
        out.push(WiringSummary {
            slot: slot.to_owned(),
            source_uri: source_uri.to_owned(),
            projection_ref,
            maintenance_exempt: wiring_mapper::extract_maintenance_exempt(node),
        });
    }
    Ok(out)
}

/// Persona-scoped workflow summaries. Reuses the tolerant `node_to_summary`
/// path so doctor-surfaced drift rows still appear in the snapshot.
fn list_persona_workflow_summaries(
    context: &crate::domain::entity::context_wiring::ContextWiring,
    storage: &SqliteStorage,
) -> WireResult<Vec<WorkflowSummary>> {
    use crate::application::workflow_mapper::{self, WORKFLOW_TYPE};
    use crate::domain::specification::Specification;

    let spec = Specification::And(vec![
        Specification::TypeIs(WORKFLOW_TYPE.to_string()),
        Specification::MetadataEq {
            path: workflow_mapper::META_PERSONA.to_string(),
            value: serde_json::Value::String(context.persona_id().as_str().to_owned()),
        },
    ]);
    let nodes = collect_matching_nodes(storage, &spec)?;
    let summaries = nodes
        .into_iter()
        .filter_map(|n| node_to_summary(n).ok())
        .collect();
    Ok(summaries)
}

// ---- wire_node_update (P3a Phase 2 (d) — wiring-entry metadata tuning) ----

/// Merge strategy for `wire_node_update`. Mirrors RFC 7396 shallow merge for
/// `Merge` and a full replacement for `Replace`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WireNodeUpdateMode {
    /// Shallow merge: top-level keys in `metadata_patch` overwrite the
    /// corresponding keys on the existing node metadata; keys absent from the
    /// patch are preserved. `null` values in the patch DELETE the matching key
    /// (RFC 7396 §1).
    Merge,
    /// Full replacement: the existing metadata is discarded and the patch
    /// becomes the new metadata.
    Replace,
}

impl WireNodeUpdateMode {
    pub fn as_str(self) -> &'static str {
        match self {
            WireNodeUpdateMode::Merge => "merge",
            WireNodeUpdateMode::Replace => "replace",
        }
    }

    pub fn parse(s: &str) -> WireResult<Self> {
        match s {
            "merge" => Ok(WireNodeUpdateMode::Merge),
            "replace" => Ok(WireNodeUpdateMode::Replace),
            other => Err(WireError::Other(format!(
                "unknown wire_node_update mode '{other}' — expected 'merge' or 'replace'"
            ))),
        }
    }
}

#[derive(Debug)]
pub struct WireNodeUpdateInput {
    pub id: String,
    /// Object whose top-level keys are applied to the existing node metadata
    /// per `mode`. Non-object values are rejected.
    pub metadata_patch: serde_json::Value,
    pub mode: WireNodeUpdateMode,
}

#[derive(Debug)]
pub struct WireNodeUpdateOutput {
    pub id: String,
    pub mode: WireNodeUpdateMode,
    /// Final metadata after the update (= what is now persisted on the node).
    pub metadata: serde_json::Value,
}

/// Update a node's `metadata` in place.
///
/// `mode = Merge`: shallow top-level merge over the existing metadata
/// (RFC 7396); `null` values in the patch delete the matching key.
/// `mode = Replace`: full replacement of the node metadata with `metadata_patch`.
///
/// Other node fields (`type` / `sot_ref` / lifecycle timestamps) are NOT
/// touched on this path — the UC backing this surface is wiring-entry tuning
/// (`source_uri` / `axis` / `maintained_by`), which is metadata-only. To
/// change the node type or lifecycle fields, delete + re-create.
///
/// Errors:
/// - `metadata_patch` is not a JSON object
/// - `id` does not match any existing node row (returns `WireError::NotFound`)
pub fn wire_node_update(
    input: WireNodeUpdateInput,
    storage: &SqliteStorage,
) -> WireResult<WireNodeUpdateOutput> {
    if !input.metadata_patch.is_object() {
        return Err(WireError::Other(format!(
            "wire_node_update: metadata_patch must be a JSON object, got {}",
            type_name_of(&input.metadata_patch)
        )));
    }
    let resolved = storage
        .resolve_node_id_or_name(&input.id)?
        .ok_or_else(|| WireError::Domain(DomainError::NotFound(format!("node: {}", input.id))))?;
    let Some(existing) = storage.get_node(&resolved)? else {
        return Err(WireError::Domain(DomainError::NotFound(format!(
            "node: {}",
            input.id
        ))));
    };

    let final_metadata = match input.mode {
        WireNodeUpdateMode::Replace => input.metadata_patch.clone(),
        WireNodeUpdateMode::Merge => {
            let mut base = match existing.metadata {
                serde_json::Value::Object(map) => map,
                _ => serde_json::Map::new(),
            };
            if let serde_json::Value::Object(patch_obj) = &input.metadata_patch {
                for (k, v) in patch_obj {
                    if v.is_null() {
                        base.remove(k);
                    } else {
                        base.insert(k.clone(), v.clone());
                    }
                }
            }
            serde_json::Value::Object(base)
        }
    };

    let updated = storage.update_node_metadata(&resolved, &final_metadata)?;
    if !updated {
        // Defensive: get_node saw a row but UPDATE matched 0 — should not
        // happen under single-writer SQLite, but surface explicitly if it does.
        return Err(WireError::Storage(format!(
            "wire_node_update: row '{}' vanished between read and write",
            input.id
        )));
    }
    Ok(WireNodeUpdateOutput {
        id: input.id,
        mode: input.mode,
        metadata: final_metadata,
    })
}

fn type_name_of(v: &serde_json::Value) -> &'static str {
    match v {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "bool",
        serde_json::Value::Number(_) => "number",
        serde_json::Value::String(_) => "string",
        serde_json::Value::Array(_) => "array",
        serde_json::Value::Object(_) => "object",
    }
}

// ---- delete surface (P2c-bis、 メンテ運用必須) ----

#[derive(Debug)]
pub struct WireDeleteInput {
    /// Node id / Edge id / Spec name / Projection name (kind に応じた identifier)
    pub id_or_name: String,
}

#[derive(Debug)]
pub struct WireDeleteOutput {
    pub kind: &'static str,
    pub id_or_name: String,
    pub deleted: bool,
}

/// Delete a node by id. Edges referencing the node (as src or tgt) are
/// **cascade-deleted in the same storage transaction** — edges table FK is
/// NOT-NULL (`REFERENCES nodes(id)`) so dangling state is not representable
/// in normal operation. The `graph.dangling_edge` Probe is retained as a
/// defensive sensor against external DB drift / migration corruption /
/// direct SQL writes that bypass this transaction.
pub fn wire_node_delete(
    input: WireDeleteInput,
    storage: &SqliteStorage,
) -> WireResult<WireDeleteOutput> {
    let deleted = match storage.resolve_node_id_or_name(&input.id_or_name)? {
        None => false,
        Some(id) => storage.delete_node(&id)?,
    };
    Ok(WireDeleteOutput {
        kind: "node",
        id_or_name: input.id_or_name,
        deleted,
    })
}

/// Delete an edge by id.
pub fn wire_edge_delete(
    input: WireDeleteInput,
    storage: &SqliteStorage,
) -> WireResult<WireDeleteOutput> {
    let deleted = match storage.resolve_edge_id_or_name(&input.id_or_name)? {
        None => false,
        Some(id) => storage.delete_edge(&id)?,
    };
    Ok(WireDeleteOutput {
        kind: "edge",
        id_or_name: input.id_or_name,
        deleted,
    })
}

/// Delete a Specification by ULID id or name. Projections referencing it via
/// spec_ref will start returning dangling-spec errors at render time
/// (existing wire_render contract).
pub fn wire_spec_delete(
    input: WireDeleteInput,
    storage: &SqliteStorage,
) -> WireResult<WireDeleteOutput> {
    let deleted = match storage.resolve_specification_id_or_name(&input.id_or_name)? {
        Some(id) => storage.delete_specification(&id)?,
        None => false,
    };
    Ok(WireDeleteOutput {
        kind: "spec",
        id_or_name: input.id_or_name,
        deleted,
    })
}

/// Delete a NamedProjection by ULID id or name.
pub fn wire_projection_delete(
    input: WireDeleteInput,
    storage: &SqliteStorage,
) -> WireResult<WireDeleteOutput> {
    let deleted = match storage.resolve_projection_id_or_name(&input.id_or_name)? {
        Some(id) => storage.delete_projection(&id)?,
        None => false,
    };
    Ok(WireDeleteOutput {
        kind: "projection",
        id_or_name: input.id_or_name,
        deleted,
    })
}

// ---- wire_nodes_create_batch ----

pub struct WireNodesCreateBatchInput {
    pub nodes: Vec<Node>,
}

pub struct WireBatchOutput {
    pub inserted_count: usize,
    /// 0-based index of the first item that failed; `None` if all succeeded.
    pub failed_at: Option<usize>,
    pub error_message: Option<String>,
}

/// Insert a batch of nodes by iterating `insert_node` 1 row at a time. Stops
/// on the first failure (non-atomic), reports counts so the caller can
/// decide whether to retry / patch / rollback. P2c scope: minimal bulk
/// surface; atomic SQLite Tx wrap is carried until usage observation.
pub fn wire_nodes_create_batch(
    input: WireNodesCreateBatchInput,
    storage: &SqliteStorage,
) -> WireResult<WireBatchOutput> {
    for (i, n) in input.nodes.iter().enumerate() {
        if let Err(e) = storage.insert_node(n) {
            return Ok(WireBatchOutput {
                inserted_count: i,
                failed_at: Some(i),
                error_message: Some(e.to_string()),
            });
        }
    }
    Ok(WireBatchOutput {
        inserted_count: input.nodes.len(),
        failed_at: None,
        error_message: None,
    })
}

// ---- wire_edges_create_batch ----

pub struct WireEdgesCreateBatchInput {
    pub edges: Vec<crate::domain::graph::Edge>,
}

/// Insert a batch of edges by iterating `insert_edge` 1 row at a time. Same
/// non-atomic semantics as `wire_nodes_create_batch`.
pub fn wire_edges_create_batch(
    input: WireEdgesCreateBatchInput,
    storage: &SqliteStorage,
) -> WireResult<WireBatchOutput> {
    for (i, e) in input.edges.iter().enumerate() {
        if let Err(err) = storage.insert_edge(e) {
            return Ok(WireBatchOutput {
                inserted_count: i,
                failed_at: Some(i),
                error_message: Some(err.to_string()),
            });
        }
    }
    Ok(WireBatchOutput {
        inserted_count: input.edges.len(),
        failed_at: None,
        error_message: None,
    })
}

// ---- wire_workflow_* (P5-a seed) ---------------------------------------
//
// `docs/wire-workflow-spec.md` の declarative WorkflowEngine seed。 Workflow を
// 既存 Node type `workflow_def` に metadata で trigger + action を埋める form で
// 表現する (新 store / 新 type 追加なし)。
//
// 本 P5-a scope:
//   - register / list / delete + fire の resolution (= どの workflow が hit し
//     て、 どんな action を取るか の descriptor 返却)
//   - trigger: on_demand / on_event の 2 kind
//   - action: no_op / emit_projection の 2 kind (validate のみ、 emit_projection
//     の実 invocation は呼び出し側 = MCP layer が wire_prompt_context を叩く)
//
// carry (P5-b 以降):
//   - cron / metadata_changed trigger (daemon 前提)
//   - set_metadata / fire_mailbox action
//   - wire_update (cross-ref 自動維持)

use crate::application::workflow_mapper::{
    node_to_workflow, parse_action, parse_trigger, workflow_to_node, WORKFLOW_TYPE,
};
use crate::domain::entity::workflow::{Action, Trigger, Workflow, WorkflowId};
use crate::domain::entity::PersonaId;

#[derive(Debug)]
pub struct WireWorkflowRegisterInput {
    pub id: String,
    pub persona_id: Option<String>,
    pub trigger: serde_json::Value,
    pub action: serde_json::Value,
    pub enabled: Option<bool>,
}

#[derive(Debug)]
pub struct WireWorkflowRegisterOutput {
    pub id: String,
}

/// Register a Workflow as a `workflow_def` Node. Routes through the
/// [`Workflow`] Domain Entity for all invariant checks (trigger / action
/// shape, P5-a kind subset) and through [`workflow_mapper`] for the
/// Entity ↔ Node mapping; this function is now a thin orchestrator over
/// the mapper boundary so observability via `wire_query({TypeIs:
/// "workflow_def"})` continues to work out of the box.
///
/// design §7.3 Phase 5 — `register / fire / delete` lifecycle invariants
/// are owned by the Entity (`Workflow::new` + `Trigger::on_event` +
/// `Action::emit_projection` constructors); use cases are pure orchestration.
pub fn wire_workflow_register(
    input: WireWorkflowRegisterInput,
    storage: &SqliteStorage,
) -> WireResult<WireWorkflowRegisterOutput> {
    let workflow = build_workflow_from_register_input(input)?;
    let node = workflow_to_node(&workflow);
    storage.insert_node(&node)?;
    Ok(WireWorkflowRegisterOutput {
        id: workflow.id().as_str().to_owned(),
    })
}

/// Construct a [`Workflow`] from the raw register input JSON, applying all
/// VO invariants at the Entity boundary. Surfaces structured
/// `DomainError::InvalidSpec` (via the mapper / Entity constructors) on
/// invalid trigger / action shape.
fn build_workflow_from_register_input(input: WireWorkflowRegisterInput) -> WireResult<Workflow> {
    let id = WorkflowId::new(input.id)?;
    let persona_id = match input.persona_id {
        Some(p) => Some(PersonaId::new(p)?),
        None => None,
    };
    let trigger = parse_trigger(&input.trigger)?;
    let action = parse_action(&input.action)?;
    Ok(Workflow::new(
        id,
        persona_id,
        trigger,
        action,
        input.enabled.unwrap_or(true),
    ))
}

#[derive(Debug)]
pub struct WireWorkflowListInput {
    pub persona_id: Option<String>,
    pub trigger_kind: Option<String>,
    pub enabled_only: Option<bool>,
}

#[derive(Debug)]
pub struct WorkflowSummary {
    pub id: String,
    pub persona_id: Option<String>,
    pub trigger: serde_json::Value,
    pub action: serde_json::Value,
    pub enabled: bool,
}

#[derive(Debug)]
pub struct WireWorkflowListOutput {
    pub workflows: Vec<WorkflowSummary>,
}

/// List registered Workflows (= Nodes of type `workflow_def`), with optional
/// `persona_id` / `trigger.kind` / enabled filtering applied in-memory.
pub fn wire_workflow_list(
    input: WireWorkflowListInput,
    storage: &SqliteStorage,
) -> WireResult<WireWorkflowListOutput> {
    let spec = Specification::TypeIs(WORKFLOW_TYPE.to_string());
    let nodes = collect_matching_nodes(storage, &spec)?;
    let enabled_only = input.enabled_only.unwrap_or(true);
    let workflows = nodes
        .into_iter()
        .filter_map(|n| node_to_summary(n).ok())
        .filter(|w| {
            if enabled_only && !w.enabled {
                return false;
            }
            if let Some(p) = input.persona_id.as_ref() {
                if w.persona_id.as_deref() != Some(p.as_str()) {
                    return false;
                }
            }
            if let Some(tk) = input.trigger_kind.as_ref() {
                if w.trigger.get("kind").and_then(|v| v.as_str()) != Some(tk.as_str()) {
                    return false;
                }
            }
            true
        })
        .collect();
    Ok(WireWorkflowListOutput { workflows })
}

/// Translate a persisted `workflow_def` Node into a [`WorkflowSummary`].
///
/// **Tolerant listing path**: `wire_workflow_list` is consumed by
/// `wire_doctor` probes that explicitly surface drift (= persisted
/// workflows whose trigger / action shape doesn't match the current
/// P5-a Entity invariants — e.g. a `cron` trigger kind injected by
/// future tooling or test scenarios). Routing this through the strict
/// `node_to_workflow` mapper would silently filter such rows out, which
/// is exactly what the doctor probes need to see. So this stays on raw
/// JSON extraction; only `wire_workflow_register` (write path) and
/// `wire_workflow_fire` (typed gating) go through the Entity mapper.
fn node_to_summary(node: Node) -> WireResult<WorkflowSummary> {
    use crate::application::workflow_mapper;
    let persona_id = workflow_mapper::extract_persona(&node).map(str::to_owned);
    let trigger = workflow_mapper::extract_trigger_value(&node);
    let action = workflow_mapper::extract_action_value(&node);
    let enabled = workflow_mapper::extract_enabled(&node);
    Ok(WorkflowSummary {
        id: node.name,
        persona_id,
        trigger,
        action,
        enabled,
    })
}

#[derive(Debug)]
pub struct WireWorkflowFireInput {
    /// Single-workflow fire by id (mutually exclusive with `event`).
    pub id: Option<String>,
    /// Event-name fan-out (matches every `on_event` workflow whose
    /// `trigger.event` equals this value).
    pub event: Option<String>,
    /// Optional scoping for event fan-out (matches metadata.persona).
    pub persona_id: Option<String>,
    pub dry_run: Option<bool>,
}

/// A workflow resolved for firing, with its action descriptor surfaced so the
/// caller (= MCP layer or external orchestrator) can dispatch the side
/// effect. P5-a keeps action invocation out of core to avoid the
/// async/Arc<Mutex> coupling — `emit_projection` is dispatched by calling
/// `wire_prompt_context` from the caller using `action_emit_projection_names`.
#[derive(Debug)]
pub struct ResolvedFire {
    pub id: String,
    pub persona_id: Option<String>,
    pub action_kind: String,
    /// Populated when `action_kind == "emit_projection"`; else None.
    pub action_emit_projection_names: Option<Vec<String>>,
    pub dry_run: bool,
}

#[derive(Debug)]
pub struct WireWorkflowFireOutput {
    pub fired: Vec<ResolvedFire>,
    pub skipped: Vec<(String, String)>, // (id, reason)
}

/// Resolve the workflows that would fire for the given input. **Does not**
/// invoke the action itself in P5-a; the returned `ResolvedFire` describes
/// what should happen so the caller can dispatch (= keeps core sync, keeps
/// emit_projection's async machinery at the MCP layer).
pub fn wire_workflow_fire(
    input: WireWorkflowFireInput,
    storage: &SqliteStorage,
) -> WireResult<WireWorkflowFireOutput> {
    if input.id.is_some() == input.event.is_some() {
        return Err(crate::domain::error::WireError::Domain(
            DomainError::InvalidSpec("exactly one of `id` or `event` is required".to_string()),
        ));
    }
    let dry_run = input.dry_run.unwrap_or(false);

    // Collect candidate workflows as Domain Entities. Gating below dispatches
    // on the typed `Trigger` / `Action` sum types instead of JSON probing.
    let candidates: Vec<Workflow> = if let Some(id) = input.id.as_ref() {
        let resolved = storage.resolve_node_id_or_name(id)?;
        let Some(node_id) = resolved else {
            return Ok(WireWorkflowFireOutput {
                fired: vec![],
                skipped: vec![(id.clone(), "workflow not found".to_string())],
            });
        };
        let Some(node) = storage.get_node(&node_id)? else {
            return Ok(WireWorkflowFireOutput {
                fired: vec![],
                skipped: vec![(id.clone(), "workflow not found".to_string())],
            });
        };
        if node.r#type != WORKFLOW_TYPE {
            return Ok(WireWorkflowFireOutput {
                fired: vec![],
                skipped: vec![(
                    id.clone(),
                    format!("node type is '{}', expected '{WORKFLOW_TYPE}'", node.r#type),
                )],
            });
        }
        vec![node_to_workflow(&node)?]
    } else {
        // event-driven: match every on_event workflow whose trigger.event == event
        let spec = Specification::TypeIs(WORKFLOW_TYPE.to_string());
        collect_matching_nodes(storage, &spec)?
            .iter()
            .filter_map(|n| node_to_workflow(n).ok())
            .collect()
    };

    let mut fired = Vec::new();
    let mut skipped = Vec::new();
    let event = input.event.as_deref();

    for w in candidates {
        let id_str = w.id().as_str().to_owned();
        if !w.enabled() {
            skipped.push((id_str, "enabled=false".to_string()));
            continue;
        }
        if let Some(persona_filter) = input.persona_id.as_ref() {
            if w.persona_id().map(|p| p.as_str()) != Some(persona_filter.as_str()) {
                skipped.push((
                    id_str,
                    format!("persona scope mismatch (want={persona_filter})"),
                ));
                continue;
            }
        }
        // Trigger gating (typed)
        if let Some(ev) = event {
            match w.trigger() {
                Trigger::OnEvent { event: wf_event } => {
                    if wf_event != ev {
                        skipped.push((id_str, format!("trigger.event='{wf_event}' != '{ev}'")));
                        continue;
                    }
                }
                Trigger::OnDemand => {
                    skipped.push((
                        id_str,
                        "trigger.kind='on_demand' does not match event fan-out".to_string(),
                    ));
                    continue;
                }
            }
        }
        // Resolve action (typed)
        let (action_kind, action_emit_projection_names) = match w.action() {
            Action::NoOp => ("no_op".to_string(), None),
            Action::EmitProjection { slots } => (
                "emit_projection".to_string(),
                Some(slots.iter().map(|s| s.as_str().to_owned()).collect()),
            ),
        };
        fired.push(ResolvedFire {
            id: w.id().as_str().to_owned(),
            persona_id: w.persona_id().map(|p| p.as_str().to_owned()),
            action_kind,
            action_emit_projection_names,
            dry_run,
        });
    }

    Ok(WireWorkflowFireOutput { fired, skipped })
}

// wire_workflow_check (P5-a') 関数 + 関連 struct は削除 (2026-06-20、 issue 7069dede)。
// 同等の coverage audit は Probe registry の Workflow Probes 経由で wire_doctor から行う
// (declared_covered / declared_uncovered / undeclared / exempt の 4 bucket は
// Workflow Probes の Finding emit に置換)。

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::entity::projection::{PluginDispatch, Projection};
    use crate::domain::graph::{ulid_from_seed, Edge, Node};
    use serde_json::json;

    fn setup() -> SqliteStorage {
        let s = SqliteStorage::open_in_memory().unwrap();
        s.migrate().unwrap();
        s.seed_default_types().unwrap();
        s
    }

    fn default_registry() -> PluginRegistry {
        PluginRegistry::default_for_wire().unwrap()
    }

    fn bare_node(id: &str, type_: &str) -> Node {
        Node {
            id: ulid_from_seed(id),
            name: id.into(),
            r#type: type_.into(),
            sot_ref: None,
            confidence: None,
            applicability: None,
            last_verified_at: None,
            review_due: None,
            version: 1,
            prev_id: None,
            metadata: json!({}),
        }
    }

    #[test]
    fn wire_init_with_no_projections_yields_empty() {
        let s = setup();
        let out = wire_init(
            WireInitInput {
                persona_id: "alpha".into(),
            },
            &s,
            &default_registry(),
        )
        .unwrap();
        assert_eq!(out.persona_id, "alpha");
        assert!(out.projections.is_empty());
        assert!(out.warnings.is_empty());
    }

    #[test]
    fn wire_init_renders_registered_projection() {
        let s = setup();
        // Insert 2 personas
        s.insert_node(&bare_node("alpha", "persona")).unwrap();
        s.insert_node(&bare_node("beta", "persona")).unwrap();
        // Register Specification
        SpecRegistry::new(&s)
            .register("active_personas", &Specification::TypeIs("persona".into()))
            .unwrap();
        // Register Projection
        ProjectionRegistry::new(&s)
            .register(
                &Projection::from_parts(
                    "_persona_toc",
                    "active_personas",
                    "Personas ({{count}}): {{names}}",
                    TargetForm::Prompt,
                    PluginDispatch::Default,
                )
                .unwrap(),
            )
            .unwrap();

        let out = wire_init(
            WireInitInput {
                persona_id: "alpha".into(),
            },
            &s,
            &default_registry(),
        )
        .unwrap();
        assert_eq!(out.projections.len(), 1);
        let p = &out.projections[0];
        assert_eq!(p.name, "_persona_toc");
        assert_eq!(p.target_form, TargetForm::Prompt);
        assert!(p.rendered.contains("Personas (2):"));
        assert!(p.rendered.contains("beta"));
        assert!(p.rendered.contains("alpha"));
        assert!(out.warnings.is_empty());
    }

    #[test]
    fn wire_init_warns_on_unknown_spec_ref() {
        let s = setup();
        ProjectionRegistry::new(&s)
            .register(
                &Projection::from_parts(
                    "broken",
                    "no_such_spec",
                    "x",
                    TargetForm::Prompt,
                    PluginDispatch::Default,
                )
                .unwrap(),
            )
            .unwrap();
        let out = wire_init(
            WireInitInput {
                persona_id: "alpha".into(),
            },
            &s,
            &default_registry(),
        )
        .unwrap();
        assert!(out.projections.is_empty());
        assert_eq!(out.warnings.len(), 1);
        assert!(out.warnings[0].contains("no_such_spec"));
    }

    #[test]
    fn wire_close_reports_orphans_and_totals() {
        let s = setup();
        // 3 personas, 1 directional edge: a -> b. c is orphan.
        for id in ["a", "b", "c"] {
            s.insert_node(&bare_node(id, "persona")).unwrap();
        }
        s.insert_edge(&Edge {
            id: ulid_from_seed("e1"),
            name: Some("e1".into()),
            src_node: ulid_from_seed("a"),
            tgt_node: ulid_from_seed("b"),
            kind: "routes_to".into(),
            severity: None,
            metadata: json!({}),
            version: 1,
            prev_id: None,
        })
        .unwrap();

        let out = wire_close(
            WireCloseInput {
                persona_id: "alpha".into(),
            },
            &s,
        )
        .unwrap();
        assert_eq!(out.total_node_count, 3);
        assert_eq!(out.total_edge_count, 1);
        assert_eq!(out.orphan_node_count, 1);
        assert!(out
            .report_markdown
            .contains("orphan nodes (no edges, not self-attached): 1"));
        assert!(out.report_markdown.contains("total nodes: 3"));
    }

    #[test]
    fn graph_scan_excludes_self_attached_wiring_from_orphans() {
        // issue 15a46ce6 regression: wiring entries that hold metadata.source_uri
        // or metadata.maintenance_exempt=true must NOT be reported as orphans,
        // even when they carry no edges (onboarding §2 — edges are optional).
        let s = setup();

        // wiring entry with source_uri — should NOT count as orphan
        use crate::application::wiring_mapper;
        use crate::domain::entity::{PersonaId, Slot, Source};
        let mut n1 = bare_node("p.mailbox", wiring_mapper::WIRING_TYPE);
        n1.metadata = wiring_mapper::wiring_metadata_object(
            &PersonaId::new("p").unwrap(),
            &Slot::new("mailbox").unwrap(),
            &Source::new("mini-app://mailbox?alias=for_p").unwrap(),
            None,
        );
        s.insert_node(&n1).unwrap();

        // wiring entry with maintenance_exempt=true — should NOT count as orphan.
        // mapper has no first-class Source for the maintenance-only sketch, so
        // construct the metadata Map directly via the mapper key constants and
        // pass it as `extras` against a placeholder Source.
        let mut n2 = bare_node("p.priorities", wiring_mapper::WIRING_TYPE);
        let mut extras = serde_json::Map::new();
        extras.insert(wiring_mapper::META_MAINTENANCE_EXEMPT.into(), json!(true));
        // build metadata without a real source_uri; remove the placeholder
        // afterwards so the legacy sketch (source_uri absent + maintenance
        // exempt) survives the round-trip.
        let mut metadata = wiring_mapper::wiring_metadata_object(
            &PersonaId::new("p").unwrap(),
            &Slot::new("priorities").unwrap(),
            &Source::new("placeholder://x").unwrap(),
            Some(extras),
        );
        metadata
            .as_object_mut()
            .unwrap()
            .remove(wiring_mapper::META_SOURCE_URI);
        n2.metadata = metadata;
        s.insert_node(&n2).unwrap();

        // bare persona node with no metadata + no edges — SHOULD count as orphan
        s.insert_node(&bare_node("p", "persona")).unwrap();

        let out = wire_doctor(&s, None).unwrap();
        let summary = graph_scan_summary(&s).unwrap();
        assert_eq!(summary.total_node_count, 3);
        assert_eq!(summary.total_edge_count, 0);
        assert_eq!(
            summary.orphan_node_count, 1,
            "only the bare persona node is orphan; the 2 wiring entries are self-attached"
        );
        // Finding-driven format (design §8): orphan Probe land 後に再導入。
        assert!(out.report_markdown.contains("scope: full"));
    }

    // ---- wire_doctor 2-axis regression tests ----

    #[test]
    fn wire_doctor_returns_2axis_integrated_report() {
        let storage = setup();
        let out = wire_doctor(&storage, None).expect("wire_doctor should pass on empty setup");
        // Finding-driven format (design §8): scope + verdict + axis sections。
        assert!(
            out.report_markdown.contains("## Graph axis"),
            "report_markdown should contain '## Graph axis' header"
        );
        assert!(
            out.report_markdown.contains("## Workflow axis"),
            "report_markdown should contain '## Workflow axis' header"
        );
        assert!(out.report_markdown.contains("scope: full"));
        // empty setup → GraphEdgesZero probe fires (error) → BROKEN。
        assert!(out.report_markdown.contains("verdict: BROKEN"));
        assert!(out.report_markdown.contains("graph.edges_zero"));
    }

    #[test]
    fn wire_close_empty_graph_zero_everything() {
        let s = setup();
        let out = wire_close(
            WireCloseInput {
                persona_id: "alpha".into(),
            },
            &s,
        )
        .unwrap();
        assert_eq!(out.total_node_count, 0);
        assert_eq!(out.total_edge_count, 0);
        assert_eq!(out.orphan_node_count, 0);
    }

    // ---- delete surface tests ----

    #[test]
    fn wire_node_delete_returns_true_when_row_exists() {
        let s = setup();
        s.insert_node(&bare_node("a", "persona")).unwrap();
        let out = wire_node_delete(
            WireDeleteInput {
                id_or_name: "a".into(),
            },
            &s,
        )
        .unwrap();
        assert_eq!(out.kind, "node");
        assert_eq!(out.id_or_name, "a");
        assert!(out.deleted);
        // 二重削除 → false
        let out2 = wire_node_delete(
            WireDeleteInput {
                id_or_name: "a".into(),
            },
            &s,
        )
        .unwrap();
        assert!(!out2.deleted);
    }

    #[test]
    fn wire_node_delete_returns_false_when_row_missing() {
        let s = setup();
        let out = wire_node_delete(
            WireDeleteInput {
                id_or_name: "ghost".into(),
            },
            &s,
        )
        .unwrap();
        assert!(!out.deleted);
    }

    #[test]
    fn wire_edge_delete_returns_true_when_row_exists() {
        let s = setup();
        s.insert_node(&bare_node("a", "persona")).unwrap();
        s.insert_node(&bare_node("b", "persona")).unwrap();
        s.insert_edge(&Edge {
            id: ulid_from_seed("e1"),
            name: Some("e1".into()),
            src_node: ulid_from_seed("a"),
            tgt_node: ulid_from_seed("b"),
            kind: "routes_to".into(),
            severity: None,
            metadata: json!({}),
            version: 1,
            prev_id: None,
        })
        .unwrap();
        let out = wire_edge_delete(
            WireDeleteInput {
                id_or_name: "e1".into(),
            },
            &s,
        )
        .unwrap();
        assert_eq!(out.kind, "edge");
        assert!(out.deleted);
    }

    #[test]
    fn wire_spec_delete_returns_true_when_row_exists() {
        let s = setup();
        SpecRegistry::new(&s)
            .register("active_personas", &Specification::TypeIs("persona".into()))
            .unwrap();
        let out = wire_spec_delete(
            WireDeleteInput {
                id_or_name: "active_personas".into(),
            },
            &s,
        )
        .unwrap();
        assert_eq!(out.kind, "spec");
        assert!(out.deleted);
    }

    #[test]
    fn wire_projection_delete_returns_true_when_row_exists() {
        let s = setup();
        SpecRegistry::new(&s)
            .register("p", &Specification::TypeIs("persona".into()))
            .unwrap();
        ProjectionRegistry::new(&s)
            .register(
                &Projection::from_parts(
                    "doomed",
                    "p",
                    "x",
                    TargetForm::Prompt,
                    PluginDispatch::Default,
                )
                .unwrap(),
            )
            .unwrap();
        let out = wire_projection_delete(
            WireDeleteInput {
                id_or_name: "doomed".into(),
            },
            &s,
        )
        .unwrap();
        assert_eq!(out.kind, "projection");
        assert!(out.deleted);
        // 削除済 projection は wire_init / wire_render の list() から消える
        assert!(ProjectionRegistry::new(&s).list().unwrap().is_empty());
    }

    // ---- wire_workflow_* (P5-a) tests ----

    #[test]
    fn workflow_register_round_trips_via_list() {
        let s = setup();
        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "alpha.workflow.review_close".into(),
                persona_id: Some("alpha".into()),
                trigger: json!({"kind":"on_event","event":"session_close"}),
                action: json!({"kind":"emit_projection","projection_names":["review_pending"]}),
                enabled: None,
            },
            &s,
        )
        .unwrap();
        let out = wire_workflow_list(
            WireWorkflowListInput {
                persona_id: Some("alpha".into()),
                trigger_kind: None,
                enabled_only: None,
            },
            &s,
        )
        .unwrap();
        assert_eq!(out.workflows.len(), 1);
        let w = &out.workflows[0];
        assert_eq!(w.id, "alpha.workflow.review_close");
        assert_eq!(w.persona_id.as_deref(), Some("alpha"));
        assert!(w.enabled);
        assert_eq!(w.trigger["kind"], "on_event");
        assert_eq!(w.action["kind"], "emit_projection");
    }

    #[test]
    fn workflow_register_rejects_unsupported_trigger_kind() {
        let s = setup();
        let err = wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "x".into(),
                persona_id: None,
                trigger: json!({"kind":"cron","cron_spec":"0 9 * * *"}),
                action: json!({"kind":"no_op"}),
                enabled: None,
            },
            &s,
        )
        .unwrap_err();
        assert!(err.to_string().contains("cron"));
    }

    #[test]
    fn workflow_register_rejects_on_event_without_event_field() {
        let s = setup();
        let err = wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "x".into(),
                persona_id: None,
                trigger: json!({"kind":"on_event"}),
                action: json!({"kind":"no_op"}),
                enabled: None,
            },
            &s,
        )
        .unwrap_err();
        assert!(err.to_string().contains("event"));
    }

    #[test]
    fn workflow_register_rejects_emit_projection_without_names() {
        let s = setup();
        let err = wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "x".into(),
                persona_id: None,
                trigger: json!({"kind":"on_demand"}),
                action: json!({"kind":"emit_projection"}),
                enabled: None,
            },
            &s,
        )
        .unwrap_err();
        assert!(err.to_string().contains("projection_names"));
    }

    #[test]
    fn workflow_list_filters_by_trigger_kind_and_enabled() {
        let s = setup();
        for (id, kind, enabled) in [
            ("w1", "on_demand", true),
            ("w2", "on_event", true),
            ("w3", "on_demand", false),
        ] {
            let trig = if kind == "on_event" {
                json!({"kind":"on_event","event":"e"})
            } else {
                json!({"kind":"on_demand"})
            };
            wire_workflow_register(
                WireWorkflowRegisterInput {
                    id: id.into(),
                    persona_id: None,
                    trigger: trig,
                    action: json!({"kind":"no_op"}),
                    enabled: Some(enabled),
                },
                &s,
            )
            .unwrap();
        }
        // default: enabled_only = true
        let out = wire_workflow_list(
            WireWorkflowListInput {
                persona_id: None,
                trigger_kind: Some("on_demand".into()),
                enabled_only: None,
            },
            &s,
        )
        .unwrap();
        let ids: Vec<&str> = out.workflows.iter().map(|w| w.id.as_str()).collect();
        assert_eq!(ids, vec!["w1"]);
        // enabled_only=false includes the disabled one
        let out2 = wire_workflow_list(
            WireWorkflowListInput {
                persona_id: None,
                trigger_kind: Some("on_demand".into()),
                enabled_only: Some(false),
            },
            &s,
        )
        .unwrap();
        let mut ids2: Vec<&str> = out2.workflows.iter().map(|w| w.id.as_str()).collect();
        ids2.sort();
        assert_eq!(ids2, vec!["w1", "w3"]);
    }

    #[test]
    fn workflow_fire_by_id_returns_resolved_emit_projection() {
        let s = setup();
        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "w1".into(),
                persona_id: Some("alpha".into()),
                trigger: json!({"kind":"on_demand"}),
                action: json!({"kind":"emit_projection","projection_names":["slot_a","slot_b"]}),
                enabled: None,
            },
            &s,
        )
        .unwrap();
        let out = wire_workflow_fire(
            WireWorkflowFireInput {
                id: Some("w1".into()),
                event: None,
                persona_id: None,
                dry_run: None,
            },
            &s,
        )
        .unwrap();
        assert_eq!(out.fired.len(), 1);
        assert!(out.skipped.is_empty());
        let f = &out.fired[0];
        assert_eq!(f.id, "w1");
        assert_eq!(f.action_kind, "emit_projection");
        assert_eq!(
            f.action_emit_projection_names.as_deref(),
            Some(&["slot_a".to_string(), "slot_b".to_string()][..])
        );
    }

    #[test]
    fn workflow_fire_by_event_skips_unrelated_and_disabled() {
        let s = setup();
        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "match_open".into(),
                persona_id: Some("alpha".into()),
                trigger: json!({"kind":"on_event","event":"session_open"}),
                action: json!({"kind":"no_op"}),
                enabled: None,
            },
            &s,
        )
        .unwrap();
        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "match_close".into(),
                persona_id: Some("alpha".into()),
                trigger: json!({"kind":"on_event","event":"session_close"}),
                action: json!({"kind":"no_op"}),
                enabled: None,
            },
            &s,
        )
        .unwrap();
        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "disabled_close".into(),
                persona_id: Some("alpha".into()),
                trigger: json!({"kind":"on_event","event":"session_close"}),
                action: json!({"kind":"no_op"}),
                enabled: Some(false),
            },
            &s,
        )
        .unwrap();
        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "demand_only".into(),
                persona_id: Some("alpha".into()),
                trigger: json!({"kind":"on_demand"}),
                action: json!({"kind":"no_op"}),
                enabled: None,
            },
            &s,
        )
        .unwrap();
        let out = wire_workflow_fire(
            WireWorkflowFireInput {
                id: None,
                event: Some("session_close".into()),
                persona_id: Some("alpha".into()),
                dry_run: None,
            },
            &s,
        )
        .unwrap();
        let fired_ids: Vec<&str> = out.fired.iter().map(|f| f.id.as_str()).collect();
        assert_eq!(fired_ids, vec!["match_close"]);
        // 3 skipped: match_open (event mismatch), disabled_close (enabled=false),
        // demand_only (trigger kind mismatch)
        assert_eq!(out.skipped.len(), 3);
    }

    #[test]
    fn workflow_fire_requires_exactly_one_of_id_or_event() {
        let s = setup();
        let err = wire_workflow_fire(
            WireWorkflowFireInput {
                id: None,
                event: None,
                persona_id: None,
                dry_run: None,
            },
            &s,
        )
        .unwrap_err();
        assert!(err.to_string().contains("id"));
    }

    #[test]
    fn workflow_fire_by_id_handles_missing() {
        let s = setup();
        let out = wire_workflow_fire(
            WireWorkflowFireInput {
                id: Some("ghost".into()),
                event: None,
                persona_id: None,
                dry_run: None,
            },
            &s,
        )
        .unwrap();
        assert!(out.fired.is_empty());
        assert_eq!(out.skipped.len(), 1);
        assert_eq!(out.skipped[0].0, "ghost");
    }

    #[test]
    fn workflow_delete_uses_node_delete() {
        let s = setup();
        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "w1".into(),
                persona_id: None,
                trigger: json!({"kind":"on_demand"}),
                action: json!({"kind":"no_op"}),
                enabled: None,
            },
            &s,
        )
        .unwrap();
        let out = wire_node_delete(
            WireDeleteInput {
                id_or_name: "w1".into(),
            },
            &s,
        )
        .unwrap();
        assert!(out.deleted);
        // gone from list
        assert!(wire_workflow_list(
            WireWorkflowListInput {
                persona_id: None,
                trigger_kind: None,
                enabled_only: Some(false),
            },
            &s,
        )
        .unwrap()
        .workflows
        .is_empty());
    }

    // wire_workflow_check tests deleted (2026-06-20、 issue 7069dede)。

    #[test]
    fn wire_node_delete_cascades_to_referencing_edges() {
        // node 削除は src / tgt どちらで参照されている edge も同 Tx 内で削除する
        // (schema が NOT-NULL FK edges→nodes なので orphan edge は表現不能、 cascade 一択)。
        let s = setup();
        s.insert_node(&bare_node("a", "persona")).unwrap();
        s.insert_node(&bare_node("b", "persona")).unwrap();
        s.insert_node(&bare_node("c", "persona")).unwrap();
        s.insert_edge(&Edge {
            id: ulid_from_seed("e_ab"),
            name: Some("e_ab".into()),
            src_node: ulid_from_seed("a"),
            tgt_node: ulid_from_seed("b"),
            kind: "routes_to".into(),
            severity: None,
            metadata: json!({}),
            version: 1,
            prev_id: None,
        })
        .unwrap();
        s.insert_edge(&Edge {
            id: ulid_from_seed("e_ca"),
            name: Some("e_ca".into()),
            src_node: ulid_from_seed("c"),
            tgt_node: ulid_from_seed("a"),
            kind: "routes_to".into(),
            severity: None,
            metadata: json!({}),
            version: 1,
            prev_id: None,
        })
        .unwrap();
        // 無関係 edge
        s.insert_edge(&Edge {
            id: ulid_from_seed("e_bc"),
            name: Some("e_bc".into()),
            src_node: ulid_from_seed("b"),
            tgt_node: ulid_from_seed("c"),
            kind: "routes_to".into(),
            severity: None,
            metadata: json!({}),
            version: 1,
            prev_id: None,
        })
        .unwrap();

        wire_node_delete(
            WireDeleteInput {
                id_or_name: "a".into(),
            },
            &s,
        )
        .unwrap();
        // a を参照する edge は両方消える、 無関係 edge は残る
        assert!(s.get_edge(&ulid_from_seed("e_ab")).unwrap().is_none());
        assert!(s.get_edge(&ulid_from_seed("e_ca")).unwrap().is_none());
        assert!(s.get_edge(&ulid_from_seed("e_bc")).unwrap().is_some());
    }

    // ---- P3a Phase 2 (c) — projection_kind dispatch ----

    #[test]
    fn wire_init_rejects_non_static_projection_kind() {
        // P3a Phase 2 (c) — sync use_cases (wire_init / wire_render) only
        // permit projection_kind None / Some("static"). Non-static kinds
        // surface a structured error so the caller hops to wire_prompt_context.
        let s = setup();
        SpecRegistry::new(&s)
            .register("p", &Specification::TypeIs("persona".into()))
            .unwrap();
        ProjectionRegistry::new(&s)
            .register(
                &Projection::from_parts(
                    "async_only",
                    "p",
                    "x",
                    TargetForm::Prompt,
                    PluginDispatch::custom("handlebars", "llm", None).unwrap(),
                )
                .unwrap(),
            )
            .unwrap();
        let result = wire_init(
            WireInitInput {
                persona_id: "alpha".into(),
            },
            &s,
            &default_registry(),
        );
        let err = match result {
            Err(e) => e.to_string(),
            Ok(_) => panic!("expected non-static projection_kind to fail"),
        };
        assert!(err.contains("async_only"), "err: {err}");
        assert!(err.contains("llm"), "err: {err}");
        assert!(err.contains("wire_prompt_context"), "err: {err}");
    }

    #[test]
    fn wire_render_rejects_non_static_projection_kind() {
        let s = setup();
        SpecRegistry::new(&s)
            .register("p", &Specification::TypeIs("persona".into()))
            .unwrap();
        ProjectionRegistry::new(&s)
            .register(
                &Projection::from_parts(
                    "summarized",
                    "p",
                    "x",
                    TargetForm::Prompt,
                    PluginDispatch::custom("handlebars", "cache", None).unwrap(),
                )
                .unwrap(),
            )
            .unwrap();
        let result = wire_render(
            WireRenderInput {
                projection_ref: "summarized".into(),
            },
            &s,
            &default_registry(),
        );
        let err = match result {
            Err(e) => e.to_string(),
            Ok(_) => panic!("expected non-static projection_kind to fail"),
        };
        assert!(err.contains("summarized"), "err: {err}");
        assert!(err.contains("cache"), "err: {err}");
        assert!(err.contains("wire_prompt_context"), "err: {err}");
    }

    #[test]
    fn wire_init_accepts_explicit_static_projection_kind() {
        // explicit Some("static") must behave identically to None (= default).
        let s = setup();
        s.insert_node(&bare_node("alpha", "persona")).unwrap();
        SpecRegistry::new(&s)
            .register("p", &Specification::TypeIs("persona".into()))
            .unwrap();
        ProjectionRegistry::new(&s)
            .register(
                &Projection::from_parts(
                    "explicit_static",
                    "p",
                    "n={{count}}",
                    TargetForm::Prompt,
                    PluginDispatch::custom("handlebars", "static", None).unwrap(),
                )
                .unwrap(),
            )
            .unwrap();
        let out = wire_init(
            WireInitInput {
                persona_id: "alpha".into(),
            },
            &s,
            &default_registry(),
        )
        .unwrap();
        assert_eq!(out.projections.len(), 1);
        assert_eq!(out.projections[0].rendered, "n=1");
    }

    // ---- P3a Phase 2 (d) — wire_node_update ----

    fn seed_wiring_node(s: &SqliteStorage, id: &str, source_uri: &str) {
        use crate::application::wiring_mapper;
        use crate::domain::entity::{PersonaId, Slot, Source};
        s.insert_node(&Node {
            id: ulid_from_seed(id),
            name: id.into(),
            r#type: wiring_mapper::WIRING_TYPE.into(),
            sot_ref: None,
            confidence: Some(1.0),
            applicability: None,
            last_verified_at: None,
            review_due: None,
            version: 1,
            prev_id: None,
            metadata: wiring_mapper::wiring_metadata_object(
                &PersonaId::new("shi").unwrap(),
                &Slot::new("mailbox").unwrap(),
                &Source::new(source_uri).unwrap(),
                None,
            ),
        })
        .unwrap();
    }

    #[test]
    fn node_update_merge_overwrites_one_key_preserves_others() {
        let s = setup();
        seed_wiring_node(&s, "shi.mailbox", "mini-app://mailbox?alias=for_shi");
        let out = wire_node_update(
            WireNodeUpdateInput {
                id: "shi.mailbox".into(),
                metadata_patch: json!({
                    "source_uri": "mini-app://mailbox?alias=for_shi&limit=10",
                }),
                mode: WireNodeUpdateMode::Merge,
            },
            &s,
        )
        .unwrap();
        // source_uri が新値に、 persona / slot (= 旧 axis 互換 key) は維持される
        use crate::application::wiring_mapper;
        assert_eq!(out.id, "shi.mailbox");
        assert_eq!(out.mode, WireNodeUpdateMode::Merge);
        let synthetic = Node {
            id: ulid_from_seed(&out.id),
            name: out.id.clone(),
            r#type: wiring_mapper::WIRING_TYPE.into(),
            sot_ref: None,
            confidence: None,
            applicability: None,
            last_verified_at: None,
            review_due: None,
            version: 1,
            prev_id: None,
            metadata: out.metadata.clone(),
        };
        assert_eq!(
            wiring_mapper::extract_source_uri(&synthetic),
            Some("mini-app://mailbox?alias=for_shi&limit=10")
        );
        assert_eq!(wiring_mapper::extract_persona(&synthetic), Some("shi"));
        assert_eq!(wiring_mapper::extract_slot(&synthetic), Some("mailbox"));
        // 永続化検証
        let stored = s.get_node_by_name("shi.mailbox").unwrap().unwrap();
        assert_eq!(
            wiring_mapper::extract_source_uri(&stored),
            Some("mini-app://mailbox?alias=for_shi&limit=10")
        );
    }

    #[test]
    fn node_update_merge_null_value_deletes_key() {
        use crate::application::wiring_mapper;
        let s = setup();
        seed_wiring_node(&s, "shi.tmp", "mini-app://x");
        let out = wire_node_update(
            WireNodeUpdateInput {
                id: "shi.tmp".into(),
                metadata_patch: json!({ wiring_mapper::META_SLOT: null }),
                mode: WireNodeUpdateMode::Merge,
            },
            &s,
        )
        .unwrap();
        // slot key (legacy `axis`) は消える、 persona と source_uri は残る
        let synthetic = Node {
            id: ulid_from_seed(&out.id),
            name: out.id.clone(),
            r#type: wiring_mapper::WIRING_TYPE.into(),
            sot_ref: None,
            confidence: None,
            applicability: None,
            last_verified_at: None,
            review_due: None,
            version: 1,
            prev_id: None,
            metadata: out.metadata.clone(),
        };
        assert!(wiring_mapper::extract_slot(&synthetic).is_none());
        assert_eq!(wiring_mapper::extract_persona(&synthetic), Some("shi"));
        assert_eq!(
            wiring_mapper::extract_source_uri(&synthetic),
            Some("mini-app://x")
        );
    }

    #[test]
    fn node_update_replace_swaps_metadata_wholesale() {
        let s = setup();
        seed_wiring_node(&s, "shi.tmp", "mini-app://x");
        let out = wire_node_update(
            WireNodeUpdateInput {
                id: "shi.tmp".into(),
                metadata_patch: json!({"only_field": 42}),
                mode: WireNodeUpdateMode::Replace,
            },
            &s,
        )
        .unwrap();
        // 全 key が新値で置き換わる
        use crate::application::wiring_mapper;
        assert_eq!(out.metadata, json!({"only_field": 42}));
        let synthetic = Node {
            id: ulid_from_seed(&out.id),
            name: out.id.clone(),
            r#type: wiring_mapper::WIRING_TYPE.into(),
            sot_ref: None,
            confidence: None,
            applicability: None,
            last_verified_at: None,
            review_due: None,
            version: 1,
            prev_id: None,
            metadata: out.metadata.clone(),
        };
        assert!(wiring_mapper::extract_persona(&synthetic).is_none());
    }

    #[test]
    fn node_update_unknown_id_returns_not_found() {
        let s = setup();
        let result = wire_node_update(
            WireNodeUpdateInput {
                id: "does.not.exist".into(),
                metadata_patch: json!({"x": 1}),
                mode: WireNodeUpdateMode::Merge,
            },
            &s,
        );
        let err = match result {
            Err(e) => e.to_string(),
            Ok(_) => panic!("expected NotFound"),
        };
        assert!(err.contains("does.not.exist"), "err: {err}");
    }

    #[test]
    fn node_update_rejects_non_object_patch() {
        let s = setup();
        seed_wiring_node(&s, "shi.tmp", "mini-app://x");
        let result = wire_node_update(
            WireNodeUpdateInput {
                id: "shi.tmp".into(),
                metadata_patch: json!("not an object"),
                mode: WireNodeUpdateMode::Merge,
            },
            &s,
        );
        let err = match result {
            Err(e) => e.to_string(),
            Ok(_) => panic!("expected non-object patch to fail"),
        };
        assert!(err.contains("must be a JSON object"), "err: {err}");
    }

    #[test]
    fn node_update_mode_parse_rejects_unknown() {
        assert_eq!(
            WireNodeUpdateMode::parse("merge").unwrap(),
            WireNodeUpdateMode::Merge
        );
        assert_eq!(
            WireNodeUpdateMode::parse("replace").unwrap(),
            WireNodeUpdateMode::Replace
        );
        assert!(WireNodeUpdateMode::parse("upsert").is_err());
    }

    // ---- wire_context_get (ContextWiring read-aggregate) tests ----

    /// Helper: insert a wiring node `<persona>.<slot>` with optional
    /// `maintenance_exempt` flag.
    fn seed_wiring(
        s: &SqliteStorage,
        persona: &str,
        slot: &str,
        source_uri: &str,
        maintenance_exempt: bool,
    ) {
        let meta = if maintenance_exempt {
            json!({
                "persona": persona,
                "axis": slot,
                "source_uri": source_uri,
                "maintenance_exempt": true,
            })
        } else {
            json!({
                "persona": persona,
                "axis": slot,
                "source_uri": source_uri,
            })
        };
        let mut n = bare_node(&format!("{persona}.{slot}"), "outline_node");
        n.metadata = meta;
        s.insert_node(&n).unwrap();
    }

    #[test]
    fn context_get_returns_wirings_and_workflows_for_persona() {
        let s = setup();
        seed_wiring(
            &s,
            "alpha",
            "mailbox",
            "mini-app://mailbox?alias=for_alpha",
            false,
        );
        seed_wiring(&s, "alpha", "mail", "mini-app://mail?alias=for_alpha", true);
        // Different persona — must NOT appear in alpha's snapshot.
        seed_wiring(
            &s,
            "beta",
            "mailbox",
            "mini-app://mailbox?alias=for_beta",
            false,
        );

        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "alpha.workflow.session_close".into(),
                persona_id: Some("alpha".into()),
                trigger: json!({"kind":"on_event","event":"session_close"}),
                action: json!({"kind":"emit_projection","projection_names":["mailbox"]}),
                enabled: None,
            },
            &s,
        )
        .unwrap();
        // Different persona's workflow — also excluded.
        wire_workflow_register(
            WireWorkflowRegisterInput {
                id: "beta.workflow.session_close".into(),
                persona_id: Some("beta".into()),
                trigger: json!({"kind":"on_demand"}),
                action: json!({"kind":"no_op"}),
                enabled: None,
            },
            &s,
        )
        .unwrap();

        let out = wire_context_get(
            WireContextGetInput {
                persona_id: "alpha".into(),
            },
            &s,
        )
        .unwrap();

        assert_eq!(out.persona_id, "alpha");
        // Sorted by slot: "mail" < "mailbox".
        assert_eq!(out.wirings.len(), 2);
        assert_eq!(out.wirings[0].slot, "mail");
        assert!(out.wirings[0].maintenance_exempt);
        assert_eq!(out.wirings[1].slot, "mailbox");
        assert!(!out.wirings[1].maintenance_exempt);

        assert_eq!(out.workflows.len(), 1);
        assert_eq!(out.workflows[0].id, "alpha.workflow.session_close");
        assert_eq!(out.workflows[0].persona_id.as_deref(), Some("alpha"));
    }

    #[test]
    fn context_get_resolves_projection_ref_via_naming_convention() {
        let s = setup();
        seed_wiring(
            &s,
            "alpha",
            "mailbox",
            "mini-app://mailbox?alias=for_alpha",
            false,
        );
        // Register the projection at the convention-derived name.
        ProjectionRegistry::new(&s)
            .register(
                &Projection::from_parts(
                    "alpha.section.mailbox",
                    "spec_ignored_here",
                    "tpl",
                    TargetForm::Prompt,
                    PluginDispatch::Default,
                )
                .unwrap(),
            )
            .unwrap();

        let out = wire_context_get(
            WireContextGetInput {
                persona_id: "alpha".into(),
            },
            &s,
        )
        .unwrap();

        assert_eq!(out.wirings.len(), 1);
        assert_eq!(
            out.wirings[0].projection_ref.as_deref(),
            Some("alpha.section.mailbox"),
            "projection_ref must resolve via <persona>.section.<slot> naming convention",
        );
    }

    #[test]
    fn context_get_leaves_projection_ref_none_when_not_registered() {
        let s = setup();
        seed_wiring(
            &s,
            "alpha",
            "mailbox",
            "mini-app://mailbox?alias=for_alpha",
            false,
        );

        let out = wire_context_get(
            WireContextGetInput {
                persona_id: "alpha".into(),
            },
            &s,
        )
        .unwrap();

        assert_eq!(out.wirings.len(), 1);
        assert!(out.wirings[0].projection_ref.is_none());
    }

    #[test]
    fn context_get_returns_empty_for_unknown_persona() {
        let s = setup();
        seed_wiring(
            &s,
            "alpha",
            "mailbox",
            "mini-app://mailbox?alias=for_alpha",
            false,
        );

        let out = wire_context_get(
            WireContextGetInput {
                persona_id: "ghost".into(),
            },
            &s,
        )
        .unwrap();

        assert_eq!(out.persona_id, "ghost");
        assert!(out.wirings.is_empty());
        assert!(out.workflows.is_empty());
    }

    #[test]
    fn context_get_rejects_empty_persona_id() {
        let s = setup();
        let err = wire_context_get(
            WireContextGetInput {
                persona_id: String::new(),
            },
            &s,
        )
        .expect_err("empty persona id must reject");
        assert!(matches!(
            err,
            WireError::Domain(DomainError::InvalidPersonaId(_))
        ));
    }

    #[test]
    fn context_get_skips_drift_wiring_nodes_silently() {
        let s = setup();
        // Wiring node missing the source_uri metadata — drift case.
        let mut drift = bare_node("alpha.mailbox", "outline_node");
        drift.metadata = json!({
            "persona": "alpha",
            "axis": "mailbox",
            // source_uri missing
        });
        s.insert_node(&drift).unwrap();
        // Valid wiring alongside.
        seed_wiring(
            &s,
            "alpha",
            "mail",
            "mini-app://mail?alias=for_alpha",
            false,
        );

        let out = wire_context_get(
            WireContextGetInput {
                persona_id: "alpha".into(),
            },
            &s,
        )
        .unwrap();

        // Only the valid wiring survives; drift is doctored, not surfaced.
        assert_eq!(out.wirings.len(), 1);
        assert_eq!(out.wirings[0].slot, "mail");
    }

    // ---- enumerate_slot_names: projection_names / projection_exclude_names filter ----
    //
    // 4 case (両 None / include only / exclude only / both) + 3 edge (交差優先 /
    // 未登録 name / 空集合)。 `WirePromptContextInput` docstring の AND NOT
    // semantics に対応する。

    fn seed_three_slots(s: &SqliteStorage) {
        seed_wiring(s, "alpha", "news", "mini-app://news?alias=for_alpha", false);
        seed_wiring(s, "alpha", "mail", "mini-app://mail?alias=for_alpha", false);
        seed_wiring(s, "alpha", "todo", "mini-app://todo?alias=for_alpha", false);
    }

    fn sorted(mut v: Vec<String>) -> Vec<String> {
        v.sort();
        v
    }

    #[test]
    fn enumerate_slots_both_none_returns_all() {
        let s = setup();
        seed_three_slots(&s);
        let got = enumerate_slot_names(&s, "alpha", None, None).unwrap();
        assert_eq!(
            sorted(got),
            vec!["mail".to_string(), "news".into(), "todo".into()]
        );
    }

    #[test]
    fn enumerate_slots_include_only_returns_explicit_set() {
        let s = setup();
        seed_three_slots(&s);
        let include = vec!["news".to_string(), "mail".into()];
        let got = enumerate_slot_names(&s, "alpha", Some(&include), None).unwrap();
        // explicit はそのままの順序 (= 現挙動互換、 ソート前提にしない)。
        assert_eq!(got, vec!["news".to_string(), "mail".into()]);
    }

    #[test]
    fn enumerate_slots_exclude_only_subtracts_from_all() {
        let s = setup();
        seed_three_slots(&s);
        let exclude = vec!["mail".to_string()];
        let got = enumerate_slot_names(&s, "alpha", None, Some(&exclude)).unwrap();
        assert_eq!(sorted(got), vec!["news".to_string(), "todo".into()]);
    }

    #[test]
    fn enumerate_slots_both_include_and_exclude_and_not() {
        let s = setup();
        seed_three_slots(&s);
        let include = vec!["news".to_string(), "mail".into(), "todo".into()];
        let exclude = vec!["mail".to_string()];
        let got = enumerate_slot_names(&s, "alpha", Some(&include), Some(&exclude)).unwrap();
        // include の順序を保ったまま exclude を引く。
        assert_eq!(got, vec!["news".to_string(), "todo".into()]);
    }

    #[test]
    fn enumerate_slots_intersection_exclude_wins() {
        // include / exclude が交差した name (= "mail") は exclude が優先 (除外)。
        let s = setup();
        seed_three_slots(&s);
        let include = vec!["news".to_string(), "mail".into()];
        let exclude = vec!["mail".to_string()];
        let got = enumerate_slot_names(&s, "alpha", Some(&include), Some(&exclude)).unwrap();
        assert_eq!(got, vec!["news".to_string()]);
    }

    #[test]
    fn enumerate_slots_unknown_exclude_name_is_ignored() {
        // exclude に未登録 name を含めても warning なく無視 (後方互換性優先)。
        let s = setup();
        seed_three_slots(&s);
        let exclude = vec!["nonexistent".to_string()];
        let got = enumerate_slot_names(&s, "alpha", None, Some(&exclude)).unwrap();
        assert_eq!(
            sorted(got),
            vec!["mail".to_string(), "news".into(), "todo".into()]
        );
    }

    #[test]
    fn enumerate_slots_empty_result_returns_empty_vec() {
        // include 集合 ⊆ exclude 集合 のとき結果は空集合。 None 両指定 (= 全件)
        // とは区別され、 caller の明示意図を尊重する。
        let s = setup();
        seed_three_slots(&s);
        let include = vec!["news".to_string(), "mail".into()];
        let exclude = vec!["news".to_string(), "mail".into()];
        let got = enumerate_slot_names(&s, "alpha", Some(&include), Some(&exclude)).unwrap();
        assert!(got.is_empty());
    }

    #[test]
    fn enumerate_slots_exclude_empty_vec_is_noop() {
        // exclude=Some(&[]) は exclude=None と同等 (= 全件返却)。
        let s = setup();
        seed_three_slots(&s);
        let empty: Vec<String> = vec![];
        let got = enumerate_slot_names(&s, "alpha", None, Some(&empty)).unwrap();
        assert_eq!(
            sorted(got),
            vec!["mail".to_string(), "news".into(), "todo".into()]
        );
    }
}