persona-wire-core 0.14.5

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
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
//! 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::adapter::Adapter;
use crate::infrastructure::filter::WireFilters;
use crate::infrastructure::storage::SqliteStorage;
use crate::infrastructure::wire_uri::WireUri;

/// Current wall-clock time as Unix epoch seconds. Used by [`wire_materialize`]
/// to stamp the snapshot `fetched_at` / item `observed_at`.
fn current_epoch_secs() -> WireResult<i64> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .map_err(|e| WireError::Other(format!("system clock before unix epoch: {e}")))
}

/// 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,
    /// Wiring entry's `metadata.auth` (credential reference key, never a
    /// secret — see `application::auth` module docs). `None` when the entry
    /// authenticates via the adapter's literal default service name.
    /// Consumed by `render_collected_slot_async` via [`merge_auth_query`].
    auth: Option<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 auth = crate::application::wiring_mapper::extract_auth(&node).map(str::to_owned);

    // Explicit `metadata.projection_ref` wins over the naming convention —
    // this is what lets one registered projection serve multiple personas
    // and makes the bundle `[[wirings]].projection_ref` field functional.
    // Absent → `<persona>.section.<slot>` convention (the common case).
    let projection_name = match crate::application::wiring_mapper::extract_projection_ref(&node) {
        Some(explicit) => explicit.to_owned(),
        None => {
            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,
        auth,
    }))
}

/// 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> {
    // Indirect auth reference layer — `c.auth` is the
    // wiring entry's `metadata.auth` (credential reference key, never a
    // secret). Merge it into the raw `source_uri` as `?auth=<key>` for this
    // one fetch, unless the URI already declares its own `auth` param (URI
    // wins, never overwritten). `c.source_uri` itself (and the
    // `wiring_entry.source_uri` field surfaced below) stays the stored,
    // unmerged value — only the URI actually routed/fetched carries the
    // merge.
    let fetch_uri = merge_auth_query(&c.source_uri, c.auth.as_deref());
    let fetched = match registry.route(&fetch_uri) {
        Ok((adapter, uri)) => match fetch_with_post_filters(&*adapter, &uri, &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 fetched_is_null = fetched.is_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?;
    // Adapter returned data but the template produced nothing — the typical
    // cause is a field-path typo against the adapter's return shape (e.g.
    // `fetched_data.content` vs the file adapter's `fetched_data.body`).
    // Handlebars resolves missing paths to empty strings, so without this
    // warning the mistake is invisible. Preview the raw shape via wire_fetch.
    if !fetched_is_null && rendered.trim().is_empty() {
        warnings.push(format!(
            "slot '{}' rendered empty output despite non-null fetched_data — \
             check the template's field paths against `wire_fetch` output \
             (projection '{}')",
            c.slot, c.projection_name
        ));
    }
    Ok(RenderedProjection {
        name: c.projection_name.clone(),
        target_form: c.target_form,
        rendered,
    })
}

/// Adapter dispatch + wire-layer post-filter stage (GH #10) — the one fetch
/// path both `render_collected_slot_async` and [`wire_fetch`] go through.
///
/// When the URI requests a filter-vocabulary key the adapter did not declare
/// AND the wire layer can apply it post-hoc
/// ([`WireFilters::split_post`] — `query` on `items[]`, `lines`/`tail` on
/// `body`), the key is stripped from the URI before the adapter sees it, the
/// fetch runs unfiltered for that key, and the filter is applied in memory
/// here, marking the response with `post_filtered: [<keys>]`. Native
/// requests (declared caps) pass through byte-identical — no split, no
/// marker.
///
/// Opt-out: adapters whose query namespace is passthrough
/// ([`Adapter::post_filterable`] `== false`, e.g. `mcp://`) never get keys
/// stripped; their own parse/forwarding behavior is unchanged.
async fn fetch_with_post_filters(
    adapter: &dyn Adapter,
    uri: &WireUri,
    raw_fetch_uri: &str,
) -> WireResult<serde_json::Value> {
    let plan = if adapter.post_filterable() {
        WireFilters::split_post(uri, adapter.filter_caps())?
    } else {
        None
    };
    match plan {
        None => adapter.fetch(uri).await,
        Some(plan) => {
            let stripped = strip_query_params(raw_fetch_uri, &plan.strip_keys);
            let stripped_uri = WireUri::parse(&stripped)?;
            let mut fetched = adapter.fetch(&stripped_uri).await?;
            plan.apply(&mut fetched)?;
            Ok(fetched)
        }
    }
}

/// Removes the given query keys from `raw_uri`'s query string (raw
/// string-level, the inverse of [`append_query_param`]). Drops the `?` when
/// no query pairs remain; any `#fragment` is preserved. Scheme/host/path are
/// never re-interpreted (same policy as [`append_query_param`]).
fn strip_query_params(raw_uri: &str, keys: &[&str]) -> String {
    let (base, fragment) = match raw_uri.split_once('#') {
        Some((b, f)) => (b, Some(f)),
        None => (raw_uri, None),
    };
    let (path, query) = match base.split_once('?') {
        Some((p, q)) => (p, q),
        None => return raw_uri.to_string(),
    };
    let kept: Vec<&str> = query
        .split('&')
        .filter(|pair| {
            let key = pair.split_once('=').map(|(k, _)| k).unwrap_or(pair);
            !keys.contains(&key)
        })
        .collect();
    let rebuilt = if kept.is_empty() {
        path.to_string()
    } else {
        format!("{path}?{}", kept.join("&"))
    };
    match fragment {
        Some(f) => format!("{rebuilt}#{f}"),
        None => rebuilt,
    }
}

/// Merges a wiring entry's `metadata.auth` service key into `source_uri` as
/// an `?auth=<key>` query param, per the convention documented in
/// `infrastructure::adapter`'s "External service integration policy".
///
/// - `meta_auth: None` (no `metadata.auth` on the wiring entry) → `source_uri`
///   unchanged.
/// - `meta_auth: Some(key)` and `source_uri` has **no** `auth` query param →
///   `key` is appended.
/// - `meta_auth: Some(key)` but `source_uri` **already** declares its own
///   `auth` query param → `source_uri` unchanged (URI wins, never
///   overwritten — a URI-declared `auth` always takes precedence over the
///   wiring entry's `metadata.auth`).
/// - `source_uri` fails to parse as a [`WireUri`] → unchanged; the real
///   parse error surfaces downstream from `PluginRegistry::route` instead
///   of being masked here.
fn merge_auth_query(source_uri: &str, meta_auth: Option<&str>) -> String {
    let Some(key) = meta_auth else {
        return source_uri.to_string();
    };
    match WireUri::parse(source_uri) {
        Ok(parsed) if parsed.query_get("auth").is_none() => {
            append_query_param(source_uri, "auth", key)
        }
        _ => source_uri.to_string(),
    }
}

/// Appends a `key=value` query param to `raw_uri`, choosing `?` or `&` based
/// on whether a query string is already present, and re-inserting any
/// `#fragment` after the new param (fragments always trail the query
/// string per RFC 3986). Operates on the raw string only — does not
/// re-interpret scheme/host/path, which stay the exclusive concern of
/// [`WireUri::parse`] and the adapters.
fn append_query_param(raw_uri: &str, key: &str, value: &str) -> String {
    let (base, fragment) = match raw_uri.split_once('#') {
        Some((b, f)) => (b, Some(f)),
        None => (raw_uri, None),
    };
    let sep = if base.contains('?') { '&' } else { '?' };
    let merged = format!("{base}{sep}{key}={value}");
    match fragment {
        Some(f) => format!("{merged}#{f}"),
        None => merged,
    }
}

// ---- wire_slot_register / wire_slot_delete (one-shot slot setup) ----

/// Input for [`wire_slot_register`] — the minimal real information a slot
/// needs. Everything else (node name, spec body, projection name) is derived
/// from the `(persona_id, slot)` pair by the same conventions the render
/// path applies.
#[derive(Debug)]
pub struct WireSlotRegisterInput {
    pub persona_id: String,
    pub slot: String,
    pub source_uri: String,
    /// Handlebars template rendered against the `wire_prompt_context` data
    /// shape (`entries[].fetched_data` — preview via [`wire_fetch`]).
    pub template: String,
    pub target_form: TargetForm,
    /// `Some(_)` overwrites the flag; `None` leaves an existing value alone.
    pub maintenance_exempt: Option<bool>,
    /// Optional credential reference key (never a secret) — stored as
    /// `metadata.auth`, merged into the fetch URI at render time.
    pub auth: Option<String>,
}

#[derive(Debug)]
pub struct WireSlotRegisterOutput {
    /// Wiring node name (`<persona>.<slot>`).
    pub node_name: String,
    /// Wiring node ULID (fresh on create; preserved on upsert).
    pub node_id: String,
    /// `true` when the wiring node was created; `false` when an existing
    /// node's metadata was updated in place.
    pub node_created: bool,
    /// Auto-registered boilerplate spec name (`<persona>.spec.<slot>`).
    pub spec_name: String,
    /// Registered projection name (`<persona>.section.<slot>`).
    pub projection_name: String,
}

/// One-shot slot setup — a macro over the three registrations the onboarding
/// guide walks through by hand (`wire_node_create` + `wire_spec_register` +
/// `wire_projection_register`), collapsing the caller-facing surface to the
/// five values that carry real information: persona / slot / source_uri /
/// template / target_form.
///
/// Derivations (single SoT with the render path):
/// - node name = `<persona>.<slot>` (`Wiring::storage_node_id` form)
/// - spec name = `<persona>.spec.<slot>`, body = the standard 3-clause shape
///   (`TypeIs(outline_node) AND persona AND axis`)
/// - projection name = `<persona>.section.<slot>`
///   (`projection_naming::workflow_emit_projection_name`)
///
/// Upsert semantics: the spec / projection registries already upsert by
/// name; the wiring node is matched by name and its canonical metadata keys
/// are merged in place (ULID preserved, passthrough keys kept). Re-invoking
/// with changed values tunes the slot without a delete + recreate dance.
pub fn wire_slot_register(
    input: WireSlotRegisterInput,
    storage: &SqliteStorage,
) -> WireResult<WireSlotRegisterOutput> {
    use crate::application::wiring_mapper;
    use crate::domain::entity::{PersonaId, Slot, Source};

    // VO validation up front — fail before any write.
    let persona = PersonaId::new(input.persona_id.clone())?;
    let slot = Slot::new(input.slot.clone())?;
    let source = Source::new(input.source_uri.clone())?;

    let node_name = format!("{}.{}", persona.as_str(), slot.as_str());
    let spec_name = format!("{}.spec.{}", persona.as_str(), slot.as_str());
    let projection_name = crate::application::projection_naming::workflow_emit_projection_name(
        persona.as_str(),
        slot.as_str(),
    );

    // 1) Wiring node — upsert by name (merge canonical keys, keep the rest).
    let mut extras = serde_json::Map::new();
    if let Some(flag) = input.maintenance_exempt {
        extras.insert(
            wiring_mapper::META_MAINTENANCE_EXEMPT.to_string(),
            serde_json::Value::Bool(flag),
        );
    }
    if let Some(auth) = &input.auth {
        extras.insert(
            wiring_mapper::META_AUTH.to_string(),
            serde_json::Value::String(auth.clone()),
        );
    }
    let canonical = wiring_mapper::wiring_metadata_object(&persona, &slot, &source, Some(extras));

    let (node_id, node_created) = match storage.get_node_by_name(&node_name)? {
        Some(existing) => {
            let mut base = match existing.metadata {
                serde_json::Value::Object(map) => map,
                _ => serde_json::Map::new(),
            };
            if let serde_json::Value::Object(patch) = &canonical {
                for (k, v) in patch {
                    base.insert(k.clone(), v.clone());
                }
            }
            let updated =
                storage.update_node_metadata(&existing.id, &serde_json::Value::Object(base))?;
            if !updated {
                return Err(WireError::Storage(format!(
                    "wire_slot_register: node '{node_name}' vanished between read and write"
                )));
            }
            (existing.id, false)
        }
        None => {
            let node = Node {
                id: crate::domain::graph::Ulid::new(),
                name: node_name.clone(),
                r#type: wiring_mapper::WIRING_TYPE.to_string(),
                sot_ref: None,
                confidence: None,
                applicability: None,
                last_verified_at: None,
                review_due: None,
                version: 1,
                prev_id: None,
                metadata: canonical,
            };
            storage.insert_node(&node)?;
            (node.id, true)
        }
    };

    // 2) Boilerplate spec — the standard 3-clause per-slot shape. Registered
    //    for compatibility with the granular surface (`wire_query` /
    //    `wire_render` / `wire_projection_register.spec_ref`); the
    //    prompt-context hot path resolves by name convention and does not
    //    evaluate it.
    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.as_str()),
        },
        Specification::MetadataEq {
            path: wiring_mapper::META_SLOT.to_string(),
            value: serde_json::json!(slot.as_str()),
        },
    ]);
    SpecRegistry::new(storage).register(&spec_name, &spec)?;

    // 3) Projection — convention name, referencing the auto spec.
    let projection = crate::domain::entity::projection::Projection::from_parts(
        projection_name.clone(),
        spec_name.clone(),
        input.template,
        input.target_form,
        crate::domain::entity::projection::PluginDispatch::Default,
    )?;
    ProjectionRegistry::new(storage).register(&projection)?;

    Ok(WireSlotRegisterOutput {
        node_name,
        node_id: node_id.to_string(),
        node_created,
        spec_name,
        projection_name,
    })
}

#[derive(Debug)]
pub struct WireSlotDeleteInput {
    pub persona_id: String,
    pub slot: String,
}

#[derive(Debug)]
pub struct WireSlotDeleteOutput {
    pub node_name: String,
    pub node_deleted: bool,
    pub spec_name: String,
    pub spec_deleted: bool,
    pub projection_name: String,
    pub projection_deleted: bool,
}

/// Counterpart to [`wire_slot_register`] — removes the wiring node, the
/// auto-registered spec, and the convention-named projection. Idempotent:
/// missing artifacts report `false` instead of erroring.
pub fn wire_slot_delete(
    input: WireSlotDeleteInput,
    storage: &SqliteStorage,
) -> WireResult<WireSlotDeleteOutput> {
    let node_name = format!("{}.{}", input.persona_id, input.slot);
    let spec_name = format!("{}.spec.{}", input.persona_id, input.slot);
    let projection_name = crate::application::projection_naming::workflow_emit_projection_name(
        &input.persona_id,
        &input.slot,
    );

    let node_deleted = match storage.lookup_node_id_by_name(&node_name)? {
        Some(id) => storage.delete_node(&id)?,
        None => false,
    };
    let spec_deleted = match storage.resolve_specification_id_or_name(&spec_name)? {
        Some(id) => storage.delete_specification(&id)?,
        None => false,
    };
    let projection_deleted = match storage.resolve_projection_id_or_name(&projection_name)? {
        Some(id) => storage.delete_projection(&id)?,
        None => false,
    };

    Ok(WireSlotDeleteOutput {
        node_name,
        node_deleted,
        spec_name,
        spec_deleted,
        projection_name,
        projection_deleted,
    })
}

// ---- wire_fetch (raw adapter preview) ----

/// Input for [`wire_fetch`] — either a raw `source_uri`, or a
/// `(persona_id, slot)` pair resolving an existing wiring entry (which also
/// applies the entry's `metadata.auth` merge, matching what the render path
/// fetches). Exactly one of the two forms must be supplied.
#[derive(Debug)]
pub struct WireFetchInput {
    pub source_uri: Option<String>,
    pub persona_id: Option<String>,
    pub slot: Option<String>,
}

#[derive(Debug)]
pub struct WireFetchOutput {
    /// The stored / supplied URI (auth merge, when any, is not echoed —
    /// mirrors `wiring_entry.source_uri` staying unmerged in render context).
    pub source_uri: String,
    /// The adapter's return value verbatim — exactly what templates see as
    /// `entries[].fetched_data`.
    pub fetched_data: serde_json::Value,
}

/// Raw adapter preview — routes a URI through the same `PluginRegistry`
/// dispatch the render path uses and returns the adapter output verbatim.
/// This closes the template-authoring loop: preview the `fetched_data`
/// shape, then write the handlebars against it. Adapter errors fail loud
/// (no silent `Null` fallback — unlike the render path's best-effort mode,
/// a preview call wants to see the failure).
pub async fn wire_fetch(
    input: WireFetchInput,
    storage: std::sync::Arc<std::sync::Mutex<SqliteStorage>>,
    registry: &PluginRegistry,
) -> WireResult<WireFetchOutput> {
    let (stored_uri, fetch_uri) = match (&input.source_uri, &input.persona_id, &input.slot) {
        (Some(uri), None, None) => (uri.clone(), uri.clone()),
        (None, Some(persona), Some(slot)) => {
            let node_name = format!("{persona}.{slot}");
            let node = {
                let s = storage
                    .lock()
                    .map_err(|_| WireError::Storage("storage mutex poisoned".to_string()))?;
                s.get_node_by_name(&node_name)?.ok_or_else(|| {
                    WireError::Domain(DomainError::NotFound(format!("wiring entry: {node_name}")))
                })?
            };
            let source_uri = crate::application::wiring_mapper::extract_source_uri(&node)
                .ok_or_else(|| {
                    WireError::Domain(DomainError::InvalidMetadata(format!(
                        "wiring entry '{node_name}' lacks metadata.source_uri"
                    )))
                })?
                .to_owned();
            let auth = crate::application::wiring_mapper::extract_auth(&node);
            let merged = merge_auth_query(&source_uri, auth);
            (source_uri, merged)
        }
        _ => {
            return Err(WireError::Other(
                "wire_fetch: supply either `source_uri` alone, or `persona_id` + `slot`"
                    .to_string(),
            ))
        }
    };

    let (adapter, uri) = registry.route(&fetch_uri)?;
    let fetched_data = fetch_with_post_filters(&*adapter, &uri, &fetch_uri).await?;

    Ok(WireFetchOutput {
        source_uri: stored_uri,
        fetched_data,
    })
}

// ---- wire_materialize (fetch + persist into the Tank) -----------------------

/// Input for [`wire_materialize`] — the wiring entry to fetch, plus optional
/// shred hints. `wire_fetch` is the read-only preview; `wire_materialize` is
/// its persisting counterpart (fetch → shred → dedup → append to the Tank).
#[derive(Debug)]
pub struct WireMaterializeInput {
    /// Persona owning the wiring entry (`<persona>.<slot>`).
    pub persona_id: String,
    /// Slot of the wiring entry to materialize.
    pub slot: String,
    /// JSON Pointer (RFC 6901) to the item array in the fetch result (e.g.
    /// `"/items"`). `None` (and no persisted hint) = the whole response is a
    /// single item.
    pub item_path: Option<String>,
    /// Item field name carrying a stable identity (e.g. `"id"` / `"guid"`).
    /// Items missing the key (or with a null value) fall back to a content
    /// hash. `None` (and no persisted hint) = every item is content-hashed.
    pub item_id_key: Option<String>,
}

/// Output of [`wire_materialize`].
#[derive(Debug)]
pub struct WireMaterializeOutput {
    /// The Tank URI the persisted items are addressable by (`tank://<p>/<s>`).
    pub tank_uri: String,
    /// ULID of the snapshot (observation batch) just recorded.
    pub snapshot_id: String,
    /// Item count after shred.
    pub item_count: usize,
    /// Newly appended item count after dedup.
    pub new_item_count: usize,
    /// Items dropped as duplicates (`item_count - new_item_count`).
    pub deduped_count: usize,
    /// ULID of the SnapshotRegistry node (fresh on create, preserved on
    /// upsert).
    pub registry_node_id: String,
    /// `true` when the SnapshotRegistry node was created this call.
    pub registry_created: bool,
}

/// Fetch the upstream Source behind a wiring entry, shred the response into
/// items, dedup against the existing timeline, and append them to the Tank —
/// creating (idempotently) the SnapshotRegistry node + `archives` edge that
/// expose the Tank as a `tank://` Source.
///
/// Storage lock discipline: the wiring/registry read and the Tank write each
/// take the mutex in a short block; the fetch (`await`) runs with no lock held
/// (mirrors [`wire_fetch`]).
pub async fn wire_materialize(
    input: WireMaterializeInput,
    storage: std::sync::Arc<std::sync::Mutex<SqliteStorage>>,
    registry: &PluginRegistry,
) -> WireResult<WireMaterializeOutput> {
    use crate::application::wiring_mapper;
    use crate::domain::graph::{Edge, Ulid};
    use crate::infrastructure::storage::{TankItemRecord, TankSnapshotRecord};

    let persona = &input.persona_id;
    let slot = &input.slot;
    let node_name = format!("{persona}.{slot}");
    let registry_name = format!("{persona}.tank.{slot}");
    let tank_key = format!("{persona}/{slot}");
    let tank_uri = format!("tank://{persona}/{slot}");

    // Step 1 (read lock, closed before the fetch await): resolve the wiring
    // entry's source_uri + auth, and read any persisted shred hints off an
    // existing SnapshotRegistry node.
    let (source_uri, fetch_uri, wiring_node_id, reg_item_path, reg_item_id_key) = {
        let s = storage
            .lock()
            .map_err(|_| WireError::Storage("storage mutex poisoned".to_string()))?;
        let node = s.get_node_by_name(&node_name)?.ok_or_else(|| {
            WireError::Domain(DomainError::NotFound(format!("wiring entry: {node_name}")))
        })?;
        let source_uri = wiring_mapper::extract_source_uri(&node)
            .ok_or_else(|| {
                WireError::Domain(DomainError::InvalidMetadata(format!(
                    "wiring entry '{node_name}' lacks metadata.source_uri"
                )))
            })?
            .to_owned();
        let auth = wiring_mapper::extract_auth(&node).map(str::to_owned);
        let fetch_uri = merge_auth_query(&source_uri, auth.as_deref());
        let existing_reg = s.get_node_by_name(&registry_name)?;
        let reg_item_path = existing_reg
            .as_ref()
            .and_then(|n| n.metadata.get("item_path").and_then(|v| v.as_str()))
            .map(str::to_owned);
        let reg_item_id_key = existing_reg
            .as_ref()
            .and_then(|n| n.metadata.get("item_id_key").and_then(|v| v.as_str()))
            .map(str::to_owned);
        (
            source_uri,
            fetch_uri,
            node.id,
            reg_item_path,
            reg_item_id_key,
        )
    };

    // Step 2: guard — materializing a tank:// into itself is a loop.
    if WireUri::parse(&source_uri)
        .map(|u| u.scheme() == "tank")
        .unwrap_or(false)
    {
        return Err(WireError::Storage(
            "wire_materialize: cannot materialize a tank:// source into itself".to_string(),
        ));
    }

    // Step 4: resolve shred config (input > persisted registry hint > default).
    let item_path = input.item_path.clone().or(reg_item_path);
    let item_id_key = input.item_id_key.clone().or(reg_item_id_key);

    // Step 3: fetch (no lock held). Fail loud, matching wire_fetch (a preview /
    // ingestion call wants to see the failure, not a best-effort Null).
    let (adapter, uri) = registry.route(&fetch_uri)?;
    let fetched = fetch_with_post_filters(&*adapter, &uri, &fetch_uri).await?;

    // Step 5: shred into items.
    let items: Vec<serde_json::Value> = match &item_path {
        Some(path) => {
            let arr_node = fetched.pointer(path).ok_or_else(|| {
                WireError::Storage(format!(
                    "wire_materialize: item_path '{path}' not found in fetched data"
                ))
            })?;
            let arr = arr_node.as_array().ok_or_else(|| {
                WireError::Storage(format!(
                    "wire_materialize: item_path '{path}' is not an array"
                ))
            })?;
            arr.clone()
        }
        None => vec![fetched.clone()],
    };

    // Step 6 + 8 prep: identities + item records. observed_at = fetched_at.
    // ULIDs are minted via a monotonic `Generator` so that within one
    // materialize (where every item shares `observed_at`), the `ORDER BY id`
    // tie-break in `tank_query_items` reflects the fetch array order
    // (`Ulid::new()` is NOT monotonic within a millisecond).
    let now = current_epoch_secs()?;
    let content_hash = tank_content_hash(&fetched)?;
    let mut id_gen = ulid::Generator::new();
    let mut item_records: Vec<TankItemRecord> = Vec::with_capacity(items.len());
    for item in &items {
        let identity = tank_item_identity(item, item_id_key.as_deref())?;
        let id = id_gen
            .generate()
            .map_err(|e| WireError::Storage(format!("wire_materialize: ulid generation: {e}")))?;
        item_records.push(TankItemRecord {
            id,
            identity,
            observed_at: now,
            payload: item.clone(),
            mime_type: "application/json".to_string(),
        });
    }

    // The upstream URI's query map, recorded on the snapshot for audit.
    let filters_applied = match WireUri::parse(&source_uri) {
        Ok(u) => serde_json::Value::Object(
            u.query()
                .iter()
                .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
                .collect(),
        ),
        Err(_) => serde_json::json!({}),
    };

    // Step 7 + 8 (write lock): ensure the registry node + archives edge, then
    // record the snapshot and append the deduped items.
    let (registry_node_id, registry_created, snapshot_id, item_count, new_item_count) = {
        let s = storage
            .lock()
            .map_err(|_| WireError::Storage("storage mutex poisoned".to_string()))?;

        // -- SnapshotRegistry node (upsert by name, ULID preserved). --
        let mut reg_meta = serde_json::Map::new();
        reg_meta.insert("source_uri".to_string(), serde_json::json!(tank_uri));
        reg_meta.insert("upstream".to_string(), serde_json::json!(source_uri));
        if let Some(p) = &item_path {
            reg_meta.insert("item_path".to_string(), serde_json::json!(p));
        }
        if let Some(k) = &item_id_key {
            reg_meta.insert("item_id_key".to_string(), serde_json::json!(k));
        }
        reg_meta.insert(
            "prov".to_string(),
            serde_json::json!({ "wasDerivedFrom": source_uri }),
        );

        let (registry_node_id, registry_created) = match s.get_node_by_name(&registry_name)? {
            Some(existing) => {
                let mut base = match existing.metadata {
                    serde_json::Value::Object(map) => map,
                    _ => serde_json::Map::new(),
                };
                for (k, v) in &reg_meta {
                    base.insert(k.clone(), v.clone());
                }
                let updated =
                    s.update_node_metadata(&existing.id, &serde_json::Value::Object(base))?;
                if !updated {
                    return Err(WireError::Storage(format!(
                        "wire_materialize: registry node '{registry_name}' vanished \
                         between read and write"
                    )));
                }
                (existing.id, false)
            }
            None => {
                let node = Node {
                    id: Ulid::new(),
                    name: registry_name.clone(),
                    r#type: "snapshot_registry".to_string(),
                    sot_ref: None,
                    confidence: None,
                    applicability: None,
                    last_verified_at: None,
                    review_due: None,
                    version: 1,
                    prev_id: None,
                    metadata: serde_json::Value::Object(reg_meta.clone()),
                };
                s.insert_node(&node)?;
                (node.id, true)
            }
        };

        // -- archives edge (registry → wiring entry), inserted once. --
        let already_linked = s
            .list_edges_from(&registry_node_id)?
            .iter()
            .any(|e| e.tgt_node == wiring_node_id && e.kind == "archives");
        if !already_linked {
            let edge = Edge {
                id: Ulid::new(),
                name: None,
                src_node: registry_node_id,
                tgt_node: wiring_node_id,
                kind: "archives".to_string(),
                severity: None,
                metadata: serde_json::json!({ "prov": "wasDerivedFrom" }),
                version: 1,
                prev_id: None,
            };
            s.insert_edge(&edge)?;
        }

        // -- Tank write: snapshot first (FK), append items, backfill count. --
        let snapshot_id = Ulid::new();
        let item_count = item_records.len();
        s.tank_insert_snapshot(&TankSnapshotRecord {
            id: snapshot_id,
            tank_key: tank_key.clone(),
            source_uri: source_uri.clone(),
            fetched_at: now,
            filters_applied,
            content_hash,
            item_count,
            new_item_count: 0,
        })?;
        let new_item_count = s.tank_append_items(&tank_key, &snapshot_id, &item_records)?;
        s.tank_update_snapshot_new_count(&snapshot_id, new_item_count)?;

        (
            registry_node_id,
            registry_created,
            snapshot_id,
            item_count,
            new_item_count,
        )
    };

    Ok(WireMaterializeOutput {
        tank_uri,
        snapshot_id: snapshot_id.to_string(),
        item_count,
        new_item_count,
        deduped_count: item_count - new_item_count,
        registry_node_id: registry_node_id.to_string(),
        registry_created,
    })
}

/// SHA-256 hex of a JSON value's canonical string form. serde_json serialises
/// `Object`s with sorted keys (its `Map` is a `BTreeMap` unless the
/// `preserve_order` feature is on, which this workspace does not enable), so
/// the digest is stable across runs and Rust versions — a requirement for a
/// persisted dedup identity that `std::hash::DefaultHasher` cannot meet.
fn tank_content_hash(v: &serde_json::Value) -> WireResult<String> {
    use sha2::{Digest, Sha256};
    let s = serde_json::to_string(v).map_err(|e| WireError::Storage(e.to_string()))?;
    let mut hasher = Sha256::new();
    hasher.update(s.as_bytes());
    Ok(format!("{:x}", hasher.finalize()))
}

/// Resolve one item's dedup identity: the `item_id_key` field (string as-is,
/// number stringified) when present and non-null, otherwise the item's
/// content hash.
fn tank_item_identity(item: &serde_json::Value, item_id_key: Option<&str>) -> WireResult<String> {
    if let Some(key) = item_id_key {
        match item.get(key) {
            Some(serde_json::Value::String(s)) => return Ok(s.clone()),
            Some(serde_json::Value::Number(n)) => return Ok(n.to_string()),
            _ => {} // missing / null / other → fall back to content hash
        }
    }
    tank_content_hash(item)
}

/// 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
/// (41/41 false-positive observed on a real 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)。
/// `registry` は登録 adapter の scheme + filter capability 一覧を `## Adapters`
/// 節に反映するために使う (adapter-filter-if Phase 1)。
/// 数値カウントが必要なら [`graph_scan_summary`] を別途呼ぶ。
pub fn wire_doctor(
    storage: &SqliteStorage,
    persona_id: Option<String>,
    registry: &PluginRegistry,
) -> WireResult<WireDoctorOutput> {
    let report_markdown = crate::application::doctor::run(storage, persona_id, registry)?;
    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;
        };
        // Explicit `metadata.projection_ref` is reported verbatim (it is what
        // the render path will use); otherwise the convention-derived name is
        // reported only when actually registered.
        let projection_ref = match wiring_mapper::extract_projection_ref(node) {
            Some(explicit) => Some(explicit.to_owned()),
            None => {
                let derived = workflow_emit_projection_name(context.persona_id().as_str(), slot);
                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, &default_registry()).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, &default_registry())
            .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_doctor_report_includes_adapters_section() {
        // adapter-filter-if Phase 1: wire_doctor renders a `## Adapters`
        // section describing registered adapter scheme + filter_caps.
        let storage = setup();
        let out = wire_doctor(&storage, None, &default_registry()).unwrap();
        assert!(
            out.report_markdown.contains("## Adapters"),
            "report_markdown should contain '## Adapters' header; got: {}",
            out.report_markdown
        );
        assert!(
            out.report_markdown
                .contains("- file: lines, tail(n_max=1000)"),
            "report_markdown should list the bundled FileAdapter's filter caps; got: {}",
            out.report_markdown
        );
    }

    #[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("alice").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, "alice.mailbox", "mini-app://mailbox?alias=for_alice");
        let out = wire_node_update(
            WireNodeUpdateInput {
                id: "alice.mailbox".into(),
                metadata_patch: json!({
                    "source_uri": "mini-app://mailbox?alias=for_alice&limit=10",
                }),
                mode: WireNodeUpdateMode::Merge,
            },
            &s,
        )
        .unwrap();
        // source_uri が新値に、 persona / slot (= 旧 axis 互換 key) は維持される
        use crate::application::wiring_mapper;
        assert_eq!(out.id, "alice.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_alice&limit=10")
        );
        assert_eq!(wiring_mapper::extract_persona(&synthetic), Some("alice"));
        assert_eq!(wiring_mapper::extract_slot(&synthetic), Some("mailbox"));
        // 永続化検証
        let stored = s.get_node_by_name("alice.mailbox").unwrap().unwrap();
        assert_eq!(
            wiring_mapper::extract_source_uri(&stored),
            Some("mini-app://mailbox?alias=for_alice&limit=10")
        );
    }

    #[test]
    fn node_update_merge_null_value_deletes_key() {
        use crate::application::wiring_mapper;
        let s = setup();
        seed_wiring_node(&s, "alice.tmp", "mini-app://x");
        let out = wire_node_update(
            WireNodeUpdateInput {
                id: "alice.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("alice"));
        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, "alice.tmp", "mini-app://x");
        let out = wire_node_update(
            WireNodeUpdateInput {
                id: "alice.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, "alice.tmp", "mini-app://x");
        let result = wire_node_update(
            WireNodeUpdateInput {
                id: "alice.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()]
        );
    }

    // ---- adapter auth — merge_auth_query / append_query_param ----

    #[test]
    fn merge_auth_query_no_metadata_auth_leaves_uri_unchanged() {
        assert_eq!(
            merge_auth_query("github://octocat/hello-world", None),
            "github://octocat/hello-world"
        );
    }

    #[test]
    fn merge_auth_query_appends_when_uri_has_no_query() {
        assert_eq!(
            merge_auth_query("github://octocat/hello-world", Some("github-alt")),
            "github://octocat/hello-world?auth=github-alt"
        );
    }

    #[test]
    fn merge_auth_query_appends_with_ampersand_when_uri_already_has_query() {
        assert_eq!(
            merge_auth_query(
                "github://octocat/hello-world?kind=issues",
                Some("github-alt")
            ),
            "github://octocat/hello-world?kind=issues&auth=github-alt"
        );
    }

    #[test]
    fn merge_auth_query_uri_side_auth_wins_no_overwrite() {
        // URI-declared auth wins: metadata.auth must never overwrite it.
        assert_eq!(
            merge_auth_query(
                "github://octocat/hello-world?auth=from-uri",
                Some("from-metadata")
            ),
            "github://octocat/hello-world?auth=from-uri"
        );
    }

    #[test]
    fn merge_auth_query_preserves_fragment_after_merged_query() {
        assert_eq!(
            merge_auth_query("file:///tmp/x#frag", Some("svc")),
            "file:///tmp/x?auth=svc#frag"
        );
    }

    #[test]
    fn merge_auth_query_unparsable_uri_left_unchanged() {
        // Not `WireUri::parse`-able (no scheme separator) — surfaced later
        // by `PluginRegistry::route`'s own parse error, not masked here.
        assert_eq!(
            merge_auth_query("not-a-uri", Some("svc")),
            "not-a-uri",
            "unparsable source_uri must pass through unchanged"
        );
    }

    #[test]
    fn append_query_param_uses_question_mark_when_absent() {
        assert_eq!(
            append_query_param("mini-app://mailbox", "auth", "k"),
            "mini-app://mailbox?auth=k"
        );
    }

    #[test]
    fn append_query_param_uses_ampersand_when_query_present() {
        assert_eq!(
            append_query_param("mini-app://mailbox?alias=x", "auth", "k"),
            "mini-app://mailbox?alias=x&auth=k"
        );
    }

    // ---- adapter auth — collect_slot auth extraction ----

    fn register_stub_projection(s: &SqliteStorage, name: &str) {
        use crate::domain::entity::projection::{PluginDispatch, Projection};
        ProjectionRegistry::new(s)
            .register(
                &Projection::from_parts(
                    name,
                    "unused_spec_ref",
                    "n={{count}}",
                    TargetForm::Prompt,
                    PluginDispatch::Default,
                )
                .unwrap(),
            )
            .unwrap();
    }

    #[test]
    fn collect_slot_extracts_auth_from_wiring_metadata() {
        use crate::application::wiring_mapper;
        use crate::domain::entity::{PersonaId, Slot, Source};

        let s = setup();
        let mut extras = serde_json::Map::new();
        extras.insert("auth".to_string(), json!("svc-x"));
        let mut node = bare_node("p.issues", wiring_mapper::WIRING_TYPE);
        node.metadata = wiring_mapper::wiring_metadata_object(
            &PersonaId::new("p").unwrap(),
            &Slot::new("issues").unwrap(),
            &Source::new("github://o/r").unwrap(),
            Some(extras),
        );
        s.insert_node(&node).unwrap();
        register_stub_projection(&s, "p.section.issues");

        let proj_reg = ProjectionRegistry::new(&s);
        let overlays = std::collections::BTreeMap::new();
        let mut warnings = Vec::new();
        let collected = collect_slot("issues", "p", &s, &proj_reg, &overlays, &mut warnings)
            .unwrap()
            .expect("wiring entry should collect");
        assert_eq!(collected.source_uri, "github://o/r");
        assert_eq!(collected.auth.as_deref(), Some("svc-x"));
        assert!(warnings.is_empty(), "warnings: {warnings:?}");
    }

    #[test]
    fn collect_slot_auth_none_when_metadata_lacks_auth() {
        use crate::application::wiring_mapper;
        use crate::domain::entity::{PersonaId, Slot, Source};

        let s = setup();
        let mut node = bare_node("p.mailbox", wiring_mapper::WIRING_TYPE);
        node.metadata = wiring_mapper::wiring_metadata_object(
            &PersonaId::new("p").unwrap(),
            &Slot::new("mailbox").unwrap(),
            &Source::new("mini-app://mailbox").unwrap(),
            None,
        );
        s.insert_node(&node).unwrap();
        register_stub_projection(&s, "p.section.mailbox");

        let proj_reg = ProjectionRegistry::new(&s);
        let overlays = std::collections::BTreeMap::new();
        let mut warnings = Vec::new();
        let collected = collect_slot("mailbox", "p", &s, &proj_reg, &overlays, &mut warnings)
            .unwrap()
            .expect("wiring entry should collect");
        assert_eq!(collected.auth, None);
    }

    // ---- wire_slot_register / wire_slot_delete ----

    fn slot_register_input(
        persona: &str,
        slot: &str,
        uri: &str,
        template: &str,
    ) -> WireSlotRegisterInput {
        WireSlotRegisterInput {
            persona_id: persona.into(),
            slot: slot.into(),
            source_uri: uri.into(),
            template: template.into(),
            target_form: TargetForm::Markdown,
            maintenance_exempt: None,
            auth: None,
        }
    }

    #[test]
    fn wire_slot_register_creates_node_spec_and_projection() {
        use crate::application::wiring_mapper;

        let s = setup();
        let out = wire_slot_register(
            slot_register_input("alpha", "notes", "file:~/notes.md", "## Notes\n{{count}}"),
            &s,
        )
        .unwrap();

        assert_eq!(out.node_name, "alpha.notes");
        assert!(out.node_created);
        assert_eq!(out.spec_name, "alpha.spec.notes");
        assert_eq!(out.projection_name, "alpha.section.notes");

        let node = s.get_node_by_name("alpha.notes").unwrap().expect("node");
        assert_eq!(wiring_mapper::extract_persona(&node), Some("alpha"));
        assert_eq!(wiring_mapper::extract_slot(&node), Some("notes"));
        assert_eq!(
            wiring_mapper::extract_source_uri(&node),
            Some("file:~/notes.md")
        );

        let spec = SpecRegistry::new(&s)
            .get("alpha.spec.notes")
            .unwrap()
            .expect("spec");
        assert!(matches!(spec, Specification::And(parts) if parts.len() == 3));

        let proj = ProjectionRegistry::new(&s)
            .get("alpha.section.notes")
            .unwrap()
            .expect("projection");
        assert_eq!(proj.template().as_str(), "## Notes\n{{count}}");
        assert_eq!(proj.spec_ref().as_str(), "alpha.spec.notes");
    }

    #[test]
    fn wire_slot_register_upserts_in_place_preserving_node_id() {
        use crate::application::wiring_mapper;

        let s = setup();
        let first = wire_slot_register(
            slot_register_input("alpha", "notes", "file:~/a.md", "v1 {{count}}"),
            &s,
        )
        .unwrap();
        // Attach a passthrough metadata key to prove merge keeps it.
        let node = s.get_node_by_name("alpha.notes").unwrap().unwrap();
        let mut meta = node.metadata.as_object().cloned().unwrap();
        meta.insert("custom_flag".into(), json!(true));
        s.update_node_metadata(&node.id, &serde_json::Value::Object(meta))
            .unwrap();

        let second = wire_slot_register(
            WireSlotRegisterInput {
                maintenance_exempt: Some(true),
                ..slot_register_input("alpha", "notes", "file:~/b.md", "v2 {{count}}")
            },
            &s,
        )
        .unwrap();

        assert!(!second.node_created, "second call must be an upsert");
        assert_eq!(first.node_id, second.node_id, "node ULID preserved");

        let node = s.get_node_by_name("alpha.notes").unwrap().unwrap();
        assert_eq!(
            wiring_mapper::extract_source_uri(&node),
            Some("file:~/b.md"),
            "canonical key overwritten"
        );
        assert!(
            wiring_mapper::extract_maintenance_exempt(&node),
            "maintenance_exempt applied"
        );
        assert_eq!(
            node.metadata.get("custom_flag"),
            Some(&json!(true)),
            "passthrough key kept"
        );

        let proj = ProjectionRegistry::new(&s)
            .get("alpha.section.notes")
            .unwrap()
            .unwrap();
        assert_eq!(proj.template().as_str(), "v2 {{count}}");
    }

    #[test]
    fn wire_slot_register_rejects_invalid_slot() {
        let s = setup();
        let err = wire_slot_register(slot_register_input("alpha", "a.b", "file:~/x.md", "t"), &s)
            .expect_err("dotted slot must reject");
        assert!(err.to_string().contains("."), "err: {err}");
        // Nothing was written.
        assert!(s.get_node_by_name("alpha.a.b").unwrap().is_none());
    }

    #[test]
    fn wire_slot_delete_removes_all_three_and_is_idempotent() {
        let s = setup();
        wire_slot_register(
            slot_register_input("alpha", "notes", "file:~/n.md", "{{count}}"),
            &s,
        )
        .unwrap();

        let del = wire_slot_delete(
            WireSlotDeleteInput {
                persona_id: "alpha".into(),
                slot: "notes".into(),
            },
            &s,
        )
        .unwrap();
        assert!(del.node_deleted && del.spec_deleted && del.projection_deleted);
        assert!(s.get_node_by_name("alpha.notes").unwrap().is_none());
        assert!(SpecRegistry::new(&s)
            .get("alpha.spec.notes")
            .unwrap()
            .is_none());
        assert!(ProjectionRegistry::new(&s)
            .get("alpha.section.notes")
            .unwrap()
            .is_none());

        let again = wire_slot_delete(
            WireSlotDeleteInput {
                persona_id: "alpha".into(),
                slot: "notes".into(),
            },
            &s,
        )
        .unwrap();
        assert!(
            !again.node_deleted && !again.spec_deleted && !again.projection_deleted,
            "second delete reports false everywhere"
        );
    }

    // ---- collect_slot: explicit projection_ref ----

    #[test]
    fn collect_slot_honors_explicit_projection_ref_over_convention() {
        use crate::application::wiring_mapper;

        let s = setup();
        let mut node = bare_node("p.mailbox", wiring_mapper::WIRING_TYPE);
        node.metadata = json!({
            "persona": "p",
            "axis": "mailbox",
            "source_uri": "mini-app://mailbox",
            "projection_ref": "shared.section.mailbox",
        });
        s.insert_node(&node).unwrap();
        // Register BOTH names — the explicit ref must win.
        register_stub_projection(&s, "p.section.mailbox");
        register_stub_projection(&s, "shared.section.mailbox");

        let proj_reg = ProjectionRegistry::new(&s);
        let overlays = std::collections::BTreeMap::new();
        let mut warnings = Vec::new();
        let collected = collect_slot("mailbox", "p", &s, &proj_reg, &overlays, &mut warnings)
            .unwrap()
            .expect("wiring entry should collect");
        assert_eq!(collected.projection_name, "shared.section.mailbox");
        assert!(warnings.is_empty(), "warnings: {warnings:?}");
    }

    #[test]
    fn collect_slot_missing_explicit_projection_ref_warns_and_skips() {
        use crate::application::wiring_mapper;

        let s = setup();
        let mut node = bare_node("p.mailbox", wiring_mapper::WIRING_TYPE);
        node.metadata = json!({
            "persona": "p",
            "axis": "mailbox",
            "source_uri": "mini-app://mailbox",
            "projection_ref": "nowhere.section.mailbox",
        });
        s.insert_node(&node).unwrap();
        // Convention name IS registered — but the explicit ref points elsewhere,
        // so the slot must NOT silently fall back (that would rebuild the trap).
        register_stub_projection(&s, "p.section.mailbox");

        let proj_reg = ProjectionRegistry::new(&s);
        let overlays = std::collections::BTreeMap::new();
        let mut warnings = Vec::new();
        let collected =
            collect_slot("mailbox", "p", &s, &proj_reg, &overlays, &mut warnings).unwrap();
        assert!(collected.is_none(), "slot must skip");
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("nowhere.section.mailbox")),
            "warning names the missing explicit ref: {warnings:?}"
        );
    }

    // ---- wire_fetch ----

    #[tokio::test]
    async fn wire_fetch_returns_raw_adapter_output_for_file_uri() {
        let dir = std::env::temp_dir().join(format!("wire-fetch-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("body.md");
        std::fs::write(&file, "hello wire_fetch").unwrap();

        let s = std::sync::Arc::new(std::sync::Mutex::new(setup()));
        let registry = default_registry();
        let out = wire_fetch(
            WireFetchInput {
                source_uri: Some(format!("file:{}", file.display())),
                persona_id: None,
                slot: None,
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        assert_eq!(out.fetched_data["body"], json!("hello wire_fetch"));
        assert_eq!(out.fetched_data["scheme"], json!("file"));
        std::fs::remove_dir_all(&dir).ok();
    }

    #[tokio::test]
    async fn wire_fetch_resolves_wiring_entry_by_persona_and_slot() {
        let dir = std::env::temp_dir().join(format!("wire-fetch-slot-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("notes.md");
        std::fs::write(&file, "slot preview").unwrap();

        let storage = setup();
        wire_slot_register(
            slot_register_input(
                "alpha",
                "notes",
                &format!("file:{}", file.display()),
                "{{count}}",
            ),
            &storage,
        )
        .unwrap();

        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = default_registry();
        let out = wire_fetch(
            WireFetchInput {
                source_uri: None,
                persona_id: Some("alpha".into()),
                slot: Some("notes".into()),
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        assert_eq!(out.fetched_data["body"], json!("slot preview"));
        std::fs::remove_dir_all(&dir).ok();
    }

    #[tokio::test]
    async fn wire_fetch_rejects_ambiguous_or_empty_input() {
        let s = std::sync::Arc::new(std::sync::Mutex::new(setup()));
        let registry = default_registry();
        let err = wire_fetch(
            WireFetchInput {
                source_uri: None,
                persona_id: None,
                slot: None,
            },
            s.clone(),
            &registry,
        )
        .await
        .expect_err("empty input must reject");
        assert!(err.to_string().contains("wire_fetch"), "err: {err}");

        let err = wire_fetch(
            WireFetchInput {
                source_uri: Some("file:~/x.md".into()),
                persona_id: Some("alpha".into()),
                slot: Some("notes".into()),
            },
            s,
            &registry,
        )
        .await
        .expect_err("both forms at once must reject");
        assert!(err.to_string().contains("wire_fetch"), "err: {err}");
    }

    // ---- wire-layer post-filter (GH #10) ----

    /// List-shaped test adapter: declares `Limit` only (no `TextQuery`), so a
    /// `?query=` request exercises the wire post-filter path. Its `fetch`
    /// re-parses with the declared caps — if the wire layer failed to strip a
    /// post key, the parse fails loud and the test catches the leak.
    struct ListyAdapter;

    #[async_trait::async_trait]
    impl Adapter for ListyAdapter {
        fn scheme(&self) -> &'static str {
            "listy"
        }
        fn filter_caps(&self) -> &'static [crate::infrastructure::filter::FilterCap] {
            &[crate::infrastructure::filter::FilterCap::Limit { max: None }]
        }
        async fn fetch(&self, uri: &WireUri) -> WireResult<serde_json::Value> {
            let _ = WireFilters::parse(uri, self.filter_caps())?;
            Ok(listy_raw_output())
        }
    }

    fn listy_raw_output() -> serde_json::Value {
        json!({
            "scheme": "listy",
            "items": [
                {"title": "alpha item"},
                {"title": "beta item"},
                {"title": "beta second"},
            ],
            "has_more": false,
        })
    }

    /// Passthrough test adapter (mcp:// stand-in): opts out of wire
    /// post-filtering, echoes whether the `query` key survived to the fetch.
    struct PassthroughAdapter;

    #[async_trait::async_trait]
    impl Adapter for PassthroughAdapter {
        fn scheme(&self) -> &'static str {
            "passx"
        }
        fn post_filterable(&self) -> bool {
            false
        }
        async fn fetch(&self, uri: &WireUri) -> WireResult<serde_json::Value> {
            Ok(json!({ "saw_query": uri.query_get("query") }))
        }
    }

    #[tokio::test]
    async fn wire_fetch_post_filters_undeclared_query_and_marks() {
        let s = std::sync::Arc::new(std::sync::Mutex::new(setup()));
        let registry = PluginRegistry::builder()
            .with_adapter(ListyAdapter)
            .build()
            .unwrap();
        let out = wire_fetch(
            WireFetchInput {
                source_uri: Some("listy://h?query=BETA".into()),
                persona_id: None,
                slot: None,
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        let items = out.fetched_data["items"].as_array().unwrap();
        assert_eq!(items.len(), 2, "narrowed case-insensitively: {items:?}");
        assert_eq!(out.fetched_data["post_filtered"], json!(["query"]));
    }

    #[tokio::test]
    async fn wire_fetch_native_request_stays_byte_identical_without_marker() {
        let s = std::sync::Arc::new(std::sync::Mutex::new(setup()));
        let registry = PluginRegistry::builder()
            .with_adapter(ListyAdapter)
            .build()
            .unwrap();
        let out = wire_fetch(
            WireFetchInput {
                source_uri: Some("listy://h?limit=2".into()),
                persona_id: None,
                slot: None,
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        assert_eq!(
            out.fetched_data,
            listy_raw_output(),
            "declared-cap request must return the adapter output verbatim (no marker)"
        );
    }

    #[tokio::test]
    async fn wire_fetch_post_query_on_document_shape_fails_loud() {
        let dir = std::env::temp_dir().join(format!("wire-postq-doc-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("doc.md");
        std::fs::write(&file, "some text").unwrap();

        let s = std::sync::Arc::new(std::sync::Mutex::new(setup()));
        let registry = default_registry();
        let err = wire_fetch(
            WireFetchInput {
                source_uri: Some(format!("file:{}?query=text", file.display())),
                persona_id: None,
                slot: None,
            },
            s,
            &registry,
        )
        .await
        .expect_err("query post-filter on a document shape must fail loud");
        assert!(err.to_string().contains("items"), "err: {err}");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[tokio::test]
    async fn wire_fetch_optout_adapter_keeps_vocabulary_keys() {
        let s = std::sync::Arc::new(std::sync::Mutex::new(setup()));
        let registry = PluginRegistry::builder()
            .with_adapter(PassthroughAdapter)
            .build()
            .unwrap();
        let out = wire_fetch(
            WireFetchInput {
                source_uri: Some("passx://h?query=abc".into()),
                persona_id: None,
                slot: None,
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        assert_eq!(
            out.fetched_data,
            json!({ "saw_query": "abc" }),
            "opt-out adapter must see the key untouched and gain no marker"
        );
    }

    #[tokio::test]
    async fn wire_prompt_context_renders_post_filtered_items() {
        let storage = setup();
        wire_slot_register(
            slot_register_input(
                "alpha",
                "feed",
                "listy://h?query=beta",
                "{{#each entries}}{{#each this.fetched_data.items}}{{this.title}};{{/each}}{{/each}}",
            ),
            &storage,
        )
        .unwrap();

        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = PluginRegistry::default_builder_for_wire()
            .with_adapter(ListyAdapter)
            .build()
            .unwrap();
        let out = wire_prompt_context(
            WirePromptContextInput {
                persona_id: "alpha".into(),
                projection_names: None,
                projection_exclude_names: None,
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        assert!(
            out.prompt_context.contains("beta item;beta second;"),
            "post-narrowed items render: {}",
            out.prompt_context
        );
        assert!(
            !out.prompt_context.contains("alpha item"),
            "filtered-out item must not render: {}",
            out.prompt_context
        );
        assert!(out.warnings.is_empty(), "warnings: {:?}", out.warnings);
    }

    // ---- strip_query_params ----

    #[test]
    fn strip_query_params_removes_only_listed_keys() {
        assert_eq!(
            strip_query_params("x://h/p?query=a&limit=3", &["query"]),
            "x://h/p?limit=3"
        );
    }

    #[test]
    fn strip_query_params_drops_question_mark_when_empty() {
        assert_eq!(strip_query_params("x://h/p?query=a", &["query"]), "x://h/p");
    }

    #[test]
    fn strip_query_params_preserves_fragment_and_no_query_uri() {
        assert_eq!(
            strip_query_params("x://h/p?query=a&k=v#frag", &["query"]),
            "x://h/p?k=v#frag"
        );
        assert_eq!(
            strip_query_params("x://h/p#frag", &["query"]),
            "x://h/p#frag"
        );
    }

    // ---- empty-render warning ----

    #[tokio::test]
    async fn wire_prompt_context_warns_on_empty_render_with_non_null_fetch() {
        let dir = std::env::temp_dir().join(format!("wire-empty-warn-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("data.md");
        std::fs::write(&file, "real content").unwrap();

        let storage = setup();
        // Template references a field path that does not exist in the file
        // adapter's return shape — renders to empty (the dogfooded mistake).
        wire_slot_register(
            slot_register_input(
                "alpha",
                "notes",
                &format!("file:{}", file.display()),
                "{{#each entries}}{{this.fetched_data.content}}{{/each}}",
            ),
            &storage,
        )
        .unwrap();

        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = default_registry();
        let out = wire_prompt_context(
            WirePromptContextInput {
                persona_id: "alpha".into(),
                projection_names: None,
                projection_exclude_names: None,
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        assert!(
            out.warnings.iter().any(|w| w.contains("rendered empty")),
            "warnings: {:?}",
            out.warnings
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[tokio::test]
    async fn wire_prompt_context_no_warning_when_template_renders_content() {
        let dir = std::env::temp_dir().join(format!("wire-nonempty-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("data.md");
        std::fs::write(&file, "real content").unwrap();

        let storage = setup();
        wire_slot_register(
            slot_register_input(
                "alpha",
                "notes",
                &format!("file:{}", file.display()),
                "{{#each entries}}{{this.fetched_data.body}}{{/each}}",
            ),
            &storage,
        )
        .unwrap();

        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = default_registry();
        let out = wire_prompt_context(
            WirePromptContextInput {
                persona_id: "alpha".into(),
                projection_names: None,
                projection_exclude_names: None,
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        assert!(
            out.warnings.is_empty(),
            "no warnings expected: {:?}",
            out.warnings
        );
        assert!(out.prompt_context.contains("real content"));
        std::fs::remove_dir_all(&dir).ok();
    }

    // ---- end-to-end: explicit projection_ref renders through shared projection ----

    #[tokio::test]
    async fn wire_prompt_context_renders_through_explicit_projection_ref() {
        use crate::application::wiring_mapper;
        use crate::domain::entity::projection::{PluginDispatch, Projection};

        let dir = std::env::temp_dir().join(format!("wire-projref-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("shared.md");
        std::fs::write(&file, "shared body").unwrap();

        let storage = setup();
        // A shared, non-convention projection…
        ProjectionRegistry::new(&storage)
            .register(
                &Projection::from_parts(
                    "shared.section.notes",
                    "unused_spec_ref",
                    "SHARED: {{#each entries}}{{this.fetched_data.body}}{{/each}}",
                    TargetForm::Markdown,
                    PluginDispatch::Default,
                )
                .unwrap(),
            )
            .unwrap();
        // …bound explicitly from the wiring entry (bundle [[wirings]] shape).
        let mut node = bare_node("beta.notes", wiring_mapper::WIRING_TYPE);
        node.metadata = json!({
            "persona": "beta",
            "axis": "notes",
            "source_uri": format!("file:{}", file.display()),
            "projection_ref": "shared.section.notes",
        });
        storage.insert_node(&node).unwrap();

        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = default_registry();
        let out = wire_prompt_context(
            WirePromptContextInput {
                persona_id: "beta".into(),
                projection_names: None,
                projection_exclude_names: None,
            },
            s,
            &registry,
        )
        .await
        .unwrap();
        assert!(
            out.prompt_context.contains("SHARED: shared body"),
            "rendered: {}",
            out.prompt_context
        );
        assert_eq!(out.projections[0].name, "shared.section.notes");
        std::fs::remove_dir_all(&dir).ok();
    }

    // ---- wire_materialize (fetch + persist into the Tank) ----

    /// Stub upstream adapter returning a fixed 2-item list-shaped payload, so a
    /// repeat materialize exercises the dedup path deterministically.
    struct StubItemsAdapter;

    #[async_trait::async_trait]
    impl Adapter for StubItemsAdapter {
        fn scheme(&self) -> &'static str {
            "stub"
        }
        async fn fetch(&self, _uri: &WireUri) -> WireResult<serde_json::Value> {
            Ok(json!({
                "items": [
                    {"id": "m1", "body": "first"},
                    {"id": "m2", "body": "second"},
                ]
            }))
        }
    }

    fn tank_query_default() -> crate::infrastructure::storage::TankQuery {
        crate::infrastructure::storage::TankQuery::default()
    }

    #[tokio::test]
    async fn wire_materialize_persists_snapshot_items_registry_and_edge() {
        let storage = setup();
        wire_slot_register(
            slot_register_input("alpha", "mailbox", "stub://mailbox", "{{count}}"),
            &storage,
        )
        .unwrap();
        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = PluginRegistry::builder()
            .with_adapter(StubItemsAdapter)
            .build()
            .unwrap();
        let out = wire_materialize(
            WireMaterializeInput {
                persona_id: "alpha".into(),
                slot: "mailbox".into(),
                item_path: Some("/items".into()),
                item_id_key: Some("id".into()),
            },
            s.clone(),
            &registry,
        )
        .await
        .unwrap();

        assert_eq!(out.tank_uri, "tank://alpha/mailbox");
        assert_eq!(out.item_count, 2);
        assert_eq!(out.new_item_count, 2);
        assert_eq!(out.deduped_count, 0);
        assert!(out.registry_created);

        let g = s.lock().unwrap();
        let reg = g
            .get_node_by_name("alpha.tank.mailbox")
            .unwrap()
            .expect("registry node");
        assert_eq!(reg.r#type, "snapshot_registry");
        assert_eq!(reg.metadata["source_uri"], "tank://alpha/mailbox");
        assert_eq!(reg.metadata["upstream"], "stub://mailbox");
        assert_eq!(reg.metadata["item_path"], "/items");
        assert_eq!(reg.metadata["item_id_key"], "id");
        assert_eq!(reg.metadata["prov"]["wasDerivedFrom"], "stub://mailbox");

        let wiring = g.get_node_by_name("alpha.mailbox").unwrap().unwrap();
        let edges = g.list_edges_from(&reg.id).unwrap();
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].kind, "archives");
        assert_eq!(edges[0].tgt_node, wiring.id);

        let (items, _) = g
            .tank_query_items("alpha/mailbox", &tank_query_default())
            .unwrap();
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].identity, "m1");
        assert_eq!(items[1].identity, "m2");
    }

    #[tokio::test]
    async fn wire_materialize_second_run_dedups_and_stays_idempotent() {
        let storage = setup();
        wire_slot_register(
            slot_register_input("alpha", "mailbox", "stub://mailbox", "{{count}}"),
            &storage,
        )
        .unwrap();
        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = PluginRegistry::builder()
            .with_adapter(StubItemsAdapter)
            .build()
            .unwrap();

        let first = wire_materialize(
            WireMaterializeInput {
                persona_id: "alpha".into(),
                slot: "mailbox".into(),
                item_path: Some("/items".into()),
                item_id_key: Some("id".into()),
            },
            s.clone(),
            &registry,
        )
        .await
        .unwrap();
        assert_eq!(first.new_item_count, 2);
        assert!(first.registry_created);

        // Second run relies on the persisted item_path / item_id_key hints
        // (both omitted here) — same identities → all deduped.
        let second = wire_materialize(
            WireMaterializeInput {
                persona_id: "alpha".into(),
                slot: "mailbox".into(),
                item_path: None,
                item_id_key: None,
            },
            s.clone(),
            &registry,
        )
        .await
        .unwrap();
        assert_eq!(second.item_count, 2);
        assert_eq!(second.new_item_count, 0, "same fetch → nothing new");
        assert_eq!(second.deduped_count, 2);
        assert!(!second.registry_created, "registry node reused");

        let g = s.lock().unwrap();
        let reg = g.get_node_by_name("alpha.tank.mailbox").unwrap().unwrap();
        assert_eq!(
            g.list_edges_from(&reg.id).unwrap().len(),
            1,
            "archives edge not duplicated"
        );
        let (items, _) = g
            .tank_query_items("alpha/mailbox", &tank_query_default())
            .unwrap();
        assert_eq!(items.len(), 2, "timeline still holds 2 items");
    }

    #[tokio::test]
    async fn wire_materialize_bad_item_path_fails_loud() {
        let storage = setup();
        wire_slot_register(
            slot_register_input("alpha", "mailbox", "stub://mailbox", "{{count}}"),
            &storage,
        )
        .unwrap();
        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = PluginRegistry::builder()
            .with_adapter(StubItemsAdapter)
            .build()
            .unwrap();
        let err = wire_materialize(
            WireMaterializeInput {
                persona_id: "alpha".into(),
                slot: "mailbox".into(),
                item_path: Some("/nonexistent".into()),
                item_id_key: None,
            },
            s,
            &registry,
        )
        .await
        .expect_err("bad JSON pointer must fail loud");
        assert!(err.to_string().contains("item_path"), "err: {err}");
    }

    #[tokio::test]
    async fn wire_materialize_rejects_tank_source_loop() {
        let storage = setup();
        wire_slot_register(
            slot_register_input("alpha", "archive", "tank://alpha/mailbox", "{{count}}"),
            &storage,
        )
        .unwrap();
        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = PluginRegistry::builder()
            .with_adapter(StubItemsAdapter)
            .with_adapter(crate::infrastructure::tank::TankAdapter::new(s.clone()))
            .build()
            .unwrap();
        let err = wire_materialize(
            WireMaterializeInput {
                persona_id: "alpha".into(),
                slot: "archive".into(),
                item_path: None,
                item_id_key: None,
            },
            s.clone(),
            &registry,
        )
        .await
        .expect_err("materializing a tank:// into itself must fail loud");
        assert!(err.to_string().contains("itself"), "err: {err}");
    }

    #[tokio::test]
    async fn wire_materialize_then_wire_fetch_tank_reads_items() {
        let storage = setup();
        wire_slot_register(
            slot_register_input("alpha", "mailbox", "stub://mailbox", "{{count}}"),
            &storage,
        )
        .unwrap();
        let s = std::sync::Arc::new(std::sync::Mutex::new(storage));
        let registry = PluginRegistry::builder()
            .with_adapter(StubItemsAdapter)
            .with_adapter(crate::infrastructure::tank::TankAdapter::new(s.clone()))
            .build()
            .unwrap();
        wire_materialize(
            WireMaterializeInput {
                persona_id: "alpha".into(),
                slot: "mailbox".into(),
                item_path: Some("/items".into()),
                item_id_key: Some("id".into()),
            },
            s.clone(),
            &registry,
        )
        .await
        .unwrap();

        // The Tank is now a Source — read it back through the same registry
        // dispatch wire_fetch uses. tail_n=1 must return the last item (m2),
        // proving the TankAdapter is really wired in.
        let out = wire_fetch(
            WireFetchInput {
                source_uri: Some("tank://alpha/mailbox?tail_n=1".into()),
                persona_id: None,
                slot: None,
            },
            s.clone(),
            &registry,
        )
        .await
        .unwrap();
        assert_eq!(out.fetched_data["kind"], "tank_items");
        let items = out.fetched_data["items"].as_array().unwrap();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0]["identity"], "m2", "last item on the timeline");
        assert_eq!(items[0]["payload"], json!({"id": "m2", "body": "second"}));
    }
}