git-paw 0.5.0

Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees
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
//! Agent skill template loading and rendering.
//!
//! Skills follow the agentskills.io specification: each skill is a directory containing
//! a SKILL.md file with YAML frontmatter and optional resource subdirectories
//! (scripts/, references/, assets/).
//!
//! ## Resolution order (agentskills.io compliant)
//!
//! When a skill is requested by name, the system searches in this order:
//!
//! 1. **Standard location** — `.agents/skills/<name>/SKILL.md` (walking up directory tree)
//! 2. **User override** — `<config_dir>/git-paw/agent-skills/<name>/SKILL.md`
//! 3. **Embedded default** — compiled into the binary via `include_str!`
//!
//! The first match wins. If none exist, resolution fails with [`SkillError::UnknownSkill`].
//!
//! ## Substitution rules
//!
//! During [`render`], the template content undergoes placeholder substitution:
//!
//! - `{{BRANCH_ID}}` is replaced with the slugified branch name (`feat/foo` → `feat-foo`)
//! - `{{PROJECT_NAME}}` is replaced with the project name (e.g. `"git-paw"`), used in the
//!   `paw-{{PROJECT_NAME}}` tmux session name
//! - `{{GIT_PAW_BROKER_URL}}` is substituted at render time with the actual broker URL
//! - `{{SKILL_NAME}}` is replaced with the skill name from metadata
//! - `{{SKILL_DESCRIPTION}}` is replaced with the skill description from metadata

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json;
use std::path::{Path, PathBuf};

/// The embedded coordination skill, compiled into the binary.
///
/// New embedded skills are added by adding a new `include_str!` constant
/// and a corresponding match arm in [`embedded_default`].
const COORDINATION_DEFAULT: &str = include_str!("../assets/agent-skills/coordination.md");

/// The embedded supervisor skill, compiled into the binary.
const SUPERVISOR_DEFAULT: &str = include_str!("../assets/agent-skills/supervisor.md");

/// Indicates where a resolved skill's content originated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Source {
    /// Content came from the binary's compiled-in default.
    Embedded,
    /// Content came from the agentskills.io standard location (.agents/skills/)
    AgentsStandard,
    /// Content came from the user's config directory override
    User,
}

/// Represents the format of a skill (standardized only).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum SkillFormat {
    /// Standardized format: directory with SKILL.md + optional subdirectories
    Standardized,
}

/// Standardized skill metadata following agentskills.io specification.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct StandardizedSkillMetadata {
    /// Skill name (max 64 chars, lowercase letters/numbers/hyphens only)
    pub name: String,
    /// Skill description (max 1024 chars)
    pub description: String,
    /// Optional license information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub license: Option<String>,
    /// Optional compatibility information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compatibility: Option<String>,
    /// Optional metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

/// A loaded skill template ready for rendering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillTemplate {
    /// The skill name (e.g. `"coordination"`).
    pub name: String,
    /// The unrendered template content with placeholders.
    pub content: String,
    /// Where the content was loaded from.
    pub source: Source,
    /// The format of the skill (legacy or standardized).
    pub format: SkillFormat,
    /// Optional metadata for standardized skills.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<StandardizedSkillMetadata>,
    /// Optional resource paths for standardized skills.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_paths: Option<Vec<PathBuf>>,
}

/// Errors that can occur during skill loading.
#[derive(Debug, thiserror::Error)]
pub enum SkillError {
    /// No embedded or user override found for the requested skill name.
    #[error("unknown skill '{name}' — no embedded default or user override exists")]
    UnknownSkill {
        /// The skill name that was requested.
        name: String,
    },

    /// Standardized skill validation failed.
    #[error("skill '{name}' validation failed: {reason}")]
    ValidationError {
        /// The skill name that failed validation.
        name: String,
        /// The validation error reason.
        reason: String,
    },

    /// Standardized skill directory cannot be read.
    #[error("cannot read skill directory at '{}' — check directory permissions", path.display())]
    DirectoryReadError {
        /// The path that could not be read.
        path: PathBuf,
        /// The underlying I/O error.
        source: std::io::Error,
    },

    /// User override skill file cannot be read.
    #[error("cannot read user override skill file at '{}' — check file permissions", path.display())]
    UserOverrideRead {
        /// The path that could not be read.
        path: PathBuf,
        /// The underlying I/O error.
        source: std::io::Error,
    },
}

/// Looks up the embedded default for a skill by name.
///
/// Returns `Some(content)` if an embedded skill exists with that name,
/// or `None` otherwise. New embedded skills are added by introducing a
/// new `include_str!` constant and a new match arm here.
fn embedded_default(skill_name: &str) -> Option<&'static str> {
    match skill_name {
        "coordination" => Some(COORDINATION_DEFAULT),
        "supervisor" => Some(SUPERVISOR_DEFAULT),
        _ => None,
    }
}

/// Resolves a skill template by name.
///
/// Checks for a user override first, then falls back to the embedded default.
/// Returns [`SkillError::UnknownSkill`] if neither source has the skill.
pub fn resolve(skill_name: &str) -> Result<SkillTemplate, SkillError> {
    resolve_with_config_dir(skill_name, None)
}

/// Attempts to load a standardized skill from .agents/skills/ directory.
///
/// Walks up the directory tree from current directory looking for .agents/skills/<name>/SKILL.md
/// Also checks user override location if `config_dir_override` is provided
fn try_load_standardized_skill(
    skill_name: &str,
    config_dir_override: Option<&Path>,
) -> Result<Option<SkillTemplate>, SkillError> {
    // First try user override if config directory is provided
    if let Some(config_dir) = config_dir_override
        && let Some(skill) = try_load_user_override(skill_name, config_dir)?
    {
        return Ok(Some(skill));
    }

    // Then try standardized agents directory
    try_load_from_agents_dir(skill_name)
}

/// Try loading from user override location in config directory
fn try_load_user_override(
    skill_name: &str,
    config_dir: &Path,
) -> Result<Option<SkillTemplate>, SkillError> {
    let skill_dir = config_dir
        .join("git-paw")
        .join("agent-skills")
        .join(skill_name);

    if skill_dir.is_dir() {
        let skill_md_path = skill_dir.join("SKILL.md");
        if skill_md_path.exists() {
            return load_skill_from_directory(&skill_dir, skill_name, Source::User);
        }
    }

    Ok(None)
}

/// Try loading from .agents/skills/ by walking up directory tree
fn try_load_from_agents_dir(skill_name: &str) -> Result<Option<SkillTemplate>, SkillError> {
    let Ok(mut current_dir) = std::env::current_dir() else {
        return Ok(None);
    };

    for _ in 0..5 {
        // Limit to 5 levels up to prevent infinite loops
        let agents_dir = current_dir.join(".agents").join("skills").join(skill_name);

        if agents_dir.is_dir() {
            let skill_md_path = agents_dir.join("SKILL.md");
            if skill_md_path.exists() {
                return load_skill_from_directory(&agents_dir, skill_name, Source::AgentsStandard);
            }
        }

        if !current_dir.pop() {
            break;
        }
    }

    Ok(None)
}

/// Common loading logic for both locations
fn load_skill_from_directory(
    skill_dir: &Path,
    skill_name: &str,
    source: Source,
) -> Result<Option<SkillTemplate>, SkillError> {
    let skill_md_path = skill_dir.join("SKILL.md");

    let content = match std::fs::read_to_string(&skill_md_path) {
        Ok(content) => content,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(source_err) => {
            let error = match source {
                Source::User => SkillError::UserOverrideRead {
                    path: skill_md_path.clone(),
                    source: source_err,
                },
                _ => SkillError::DirectoryReadError {
                    path: skill_dir.to_path_buf(),
                    source: source_err,
                },
            };
            return Err(error);
        }
    };

    // Parse metadata from frontmatter if present
    let (metadata, content_without_frontmatter) = parse_standardized_metadata(&content)?;

    // Collect resource paths
    let mut resource_paths = Vec::new();
    for subdir in ["scripts", "references", "assets"] {
        let subdir_path = skill_dir.join(subdir);
        if subdir_path.exists() && subdir_path.is_dir() {
            resource_paths.push(subdir_path);
        }
    }

    Ok(Some(SkillTemplate {
        name: skill_name.to_string(),
        content: content_without_frontmatter,
        source,
        format: SkillFormat::Standardized,
        metadata,
        resource_paths: if resource_paths.is_empty() {
            None
        } else {
            Some(resource_paths)
        },
    }))
}

/// Parses standardized skill metadata from YAML frontmatter.
///
/// Extracts YAML frontmatter (between --- lines) and parses it into `StandardizedSkillMetadata`.
fn parse_standardized_metadata(
    content: &str,
) -> Result<(Option<StandardizedSkillMetadata>, String), SkillError> {
    // Check if content starts with YAML frontmatter
    let lines: Vec<&str> = content.lines().collect();
    if lines.len() < 2 || !lines[0].trim().starts_with("---") {
        // No frontmatter, return None for metadata and original content
        return Ok((None, content.to_string()));
    }

    // Find the end of frontmatter
    let mut frontmatter_end = None;
    for (i, line) in lines.iter().enumerate().skip(1) {
        if line.trim().starts_with("---") {
            frontmatter_end = Some(i);
            break;
        }
    }

    let Some(frontmatter_end) = frontmatter_end else {
        return Ok((None, content.to_string())); // No closing ---, treat as no frontmatter
    };

    // Extract frontmatter YAML
    let frontmatter_lines = &lines[1..frontmatter_end];
    let frontmatter_yaml = frontmatter_lines.join("\n");

    // Parse YAML into metadata
    let metadata: StandardizedSkillMetadata = match serde_yaml::from_str(&frontmatter_yaml) {
        Ok(meta) => meta,
        Err(e) => {
            return Err(SkillError::ValidationError {
                name: "unknown".to_string(),
                reason: format!("invalid YAML frontmatter: {e}"),
            });
        }
    };

    // Validate required fields
    if metadata.name.is_empty() {
        return Err(SkillError::ValidationError {
            name: "unknown".to_string(),
            reason: "missing required 'name' field in frontmatter".to_string(),
        });
    }

    if metadata.description.is_empty() {
        return Err(SkillError::ValidationError {
            name: metadata.name.clone(),
            reason: "missing required 'description' field in frontmatter".to_string(),
        });
    }

    // Extract content after frontmatter
    let content_without_frontmatter = lines[frontmatter_end + 1..].join("\n");

    Ok((Some(metadata), content_without_frontmatter))
}

/// Internal resolver that accepts an optional config directory override for testing.
fn resolve_with_config_dir(
    skill_name: &str,
    config_dir: Option<&Path>,
) -> Result<SkillTemplate, SkillError> {
    // Try standardized format
    if let Some(skill) = try_load_standardized_skill(skill_name, config_dir)? {
        return Ok(skill);
    }

    // Try embedded default (now also uses standardized format)
    if let Some(content) = embedded_default(skill_name) {
        // Parse embedded content as standardized format
        let (metadata, content_without_frontmatter) = parse_standardized_metadata(content)?;

        return Ok(SkillTemplate {
            name: skill_name.to_string(),
            content: content_without_frontmatter,
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata,
            resource_paths: None,
        });
    }

    Err(SkillError::UnknownSkill {
        name: skill_name.to_string(),
    })
}

/// Re-export of [`crate::broker::messages::slugify_branch`] to ensure skill
/// template rendering uses the exact same slug algorithm as the broker.
fn slugify_branch(branch: &str) -> String {
    crate::broker::messages::slugify_branch(branch)
}

/// Builds the standardized boot instruction block for agent initialization.
///
/// The boot block contains instructions for four essential runtime events:
/// 1. REGISTER - Initial status publication
/// 2. DONE - Task completion reporting
/// 3. BLOCKED - Dependency waiting notification
/// 4. QUESTION - Uncertainty escalation with explicit wait instruction
///
/// # Arguments
///
/// * `branch_id` - The branch name (will be slugified)
/// * `broker_url` - The fully-qualified broker URL for curl commands
///
/// # Returns
///
/// A string containing the complete boot instruction block with all placeholders
/// substituted and curl commands pre-expanded.
pub fn build_boot_block(branch_id: &str, broker_url: &str) -> String {
    let template = include_str!("../assets/boot-block-template.md");
    let slugified_branch = slugify_branch(branch_id);

    template
        .replace("{{BRANCH_ID}}", &slugified_branch)
        .replace("{{GIT_PAW_BROKER_URL}}", broker_url)
}

/// Borrowed view of the seven gate-command templates substituted by
/// [`render`] into the supervisor skill.
///
/// Each field maps to a `{{...}}` placeholder in the skill template (see
/// [`render`] for the full list). `None` renders as the literal
/// `(not configured)` so the rendered prose stays readable and the
/// supervisor agent can machine-check the value to decide whether to skip
/// the tooling invocation for that gate.
///
/// `{{CHANGE_ID}}` is NOT a field here: it is a per-invocation placeholder
/// substituted by the supervisor agent at verification time (using the
/// change being audited), not by `render` at session boot.
///
/// Use [`SupervisorConfig::gate_commands`](crate::config::SupervisorConfig::gate_commands)
/// to build one from a config.
#[derive(Debug, Clone, Copy, Default)]
pub struct GateCommands<'a> {
    /// Renders into `{{TEST_COMMAND}}`. Gate 1 test runner.
    pub test_command: Option<&'a str>,
    /// Renders into `{{LINT_COMMAND}}`. Gate 1 lint sub-step.
    pub lint_command: Option<&'a str>,
    /// Renders into `{{BUILD_COMMAND}}`. Gate 1 build sub-step.
    pub build_command: Option<&'a str>,
    /// Renders into `{{DOC_BUILD_COMMAND}}`. Gate 4 doc builder.
    pub doc_build_command: Option<&'a str>,
    /// Renders into `{{SPEC_VALIDATE_COMMAND}}`. Gate 3 spec validator.
    /// MAY contain a `{{CHANGE_ID}}` substring that the supervisor agent
    /// expands at verification time — `render` does NOT substitute it.
    pub spec_validate_command: Option<&'a str>,
    /// Renders into `{{FMT_CHECK_COMMAND}}`. Gate 1 format check.
    pub fmt_check_command: Option<&'a str>,
    /// Renders into `{{SECURITY_AUDIT_COMMAND}}`. Gate 5 security tooling.
    pub security_audit_command: Option<&'a str>,
}

/// Renders a skill template for a specific worktree.
///
/// Substitutes the following placeholders at render time:
///
/// - `{{BRANCH_ID}}` — the slugified branch name (`feat/foo` → `feat-foo`)
/// - `{{PROJECT_NAME}}` — the project name (e.g. `"git-paw"`), used in the
///   `paw-{{PROJECT_NAME}}` tmux session name
/// - `{{GIT_PAW_BROKER_URL}}` — the fully-qualified broker URL, pre-expanded
///   here so the agent's curl commands contain a literal URL and no shell
///   expansion is needed at execution time. Pre-expanding at render time is
///   important: some CLI tools gate shell-variable expansion behind extra
///   permission prompts, which breaks the "don't ask again for `curl:*`"
///   allowlist flow.
/// - `{{TEST_COMMAND}}` — the supervisor's configured `test_command` (e.g.
///   `"just check"`). When `test_command` is `None`, the placeholder
///   substitutes to the literal `"(not configured)"` so the rendered prose
///   stays readable.
/// - `{{LINT_COMMAND}}`, `{{BUILD_COMMAND}}`, `{{DOC_BUILD_COMMAND}}`,
///   `{{SPEC_VALIDATE_COMMAND}}`, `{{FMT_CHECK_COMMAND}}`,
///   `{{SECURITY_AUDIT_COMMAND}}` — the five additional gate commands
///   from `[supervisor]` config. `None` renders as `(not configured)`,
///   identical to `{{TEST_COMMAND}}` behaviour.
///
/// `{{CHANGE_ID}}` is **not** substituted here. The spec-validate command
/// typically embeds `{{CHANGE_ID}}` as a per-invocation placeholder that
/// the supervisor agent expands at verification time using the change name
/// being audited. Substituting it at render time would freeze the rendered
/// skill to a single change, which is wrong — the supervisor verifies
/// many changes over a session lifetime.
///
/// Any remaining `{{...}}` placeholder after substitution is logged as a
/// warning to stderr but does not cause `render` to fail. The
/// `{{CHANGE_ID}}` form is whitelisted from this warning since the spec
/// expects it to survive intact (see the `agent-skills` spec delta).
///
/// For standardized skills, additional metadata placeholders may be available:
/// - `{{SKILL_NAME}}` — the skill name from metadata
/// - `{{SKILL_DESCRIPTION}}` — the skill description from metadata
pub fn render(
    template: &SkillTemplate,
    branch: &str,
    broker_url: &str,
    project: &str,
    gates: &GateCommands<'_>,
) -> String {
    const NOT_CONFIGURED: &str = "(not configured)";
    let branch_id = slugify_branch(branch);

    // Start with basic substitutions. Gate-command placeholders use the
    // literal `(not configured)` when the source value is `None` so the
    // rendered prose remains readable AND the supervisor agent can branch
    // on it to skip the tooling invocation.
    let mut output = template
        .content
        .replace("{{BRANCH_ID}}", &branch_id)
        .replace("{{PROJECT_NAME}}", project)
        .replace("{{GIT_PAW_BROKER_URL}}", broker_url)
        .replace(
            "{{TEST_COMMAND}}",
            gates.test_command.unwrap_or(NOT_CONFIGURED),
        )
        .replace(
            "{{LINT_COMMAND}}",
            gates.lint_command.unwrap_or(NOT_CONFIGURED),
        )
        .replace(
            "{{BUILD_COMMAND}}",
            gates.build_command.unwrap_or(NOT_CONFIGURED),
        )
        .replace(
            "{{DOC_BUILD_COMMAND}}",
            gates.doc_build_command.unwrap_or(NOT_CONFIGURED),
        )
        .replace(
            "{{SPEC_VALIDATE_COMMAND}}",
            gates.spec_validate_command.unwrap_or(NOT_CONFIGURED),
        )
        .replace(
            "{{FMT_CHECK_COMMAND}}",
            gates.fmt_check_command.unwrap_or(NOT_CONFIGURED),
        )
        .replace(
            "{{SECURITY_AUDIT_COMMAND}}",
            gates.security_audit_command.unwrap_or(NOT_CONFIGURED),
        );

    // `{{CHANGE_ID}}` is intentionally NOT substituted: it is a
    // per-invocation placeholder owned by the supervisor agent at
    // verification time. It survives render verbatim and is expanded
    // when the supervisor runs spec-validate against a specific change.

    // Add metadata substitutions for standardized skills
    if let Some(metadata) = &template.metadata {
        output = output
            .replace("{{SKILL_NAME}}", &metadata.name)
            .replace("{{SKILL_DESCRIPTION}}", &metadata.description);
    }

    // Warn about any remaining {{...}} placeholders that were not consumed,
    // except `{{CHANGE_ID}}` which is whitelisted (see comment above).
    let mut start = 0;
    while let Some(open) = output[start..].find("{{") {
        let abs_open = start + open;
        if let Some(close) = output[abs_open..].find("}}") {
            let placeholder = &output[abs_open..abs_open + close + 2];
            if placeholder != "{{CHANGE_ID}}" {
                eprintln!(
                    "warning: unsubstituted placeholder {placeholder} in skill '{}'",
                    template.name
                );
            }
            start = abs_open + close + 2;
        } else {
            break;
        }
    }

    output
}

/// Canonical doc names for the `[governance]` paths, in the order they
/// appear in the supervisor boot prompt: `adr`, `test_strategy`, `security`,
/// `dod`, `constitution`. The canonical name is what shows up before the
/// path in each bullet (`- adr: docs/adr/`).
const GOVERNANCE_CANONICAL_NAMES: [&str; 5] =
    ["adr", "test_strategy", "security", "dod", "constitution"];

/// Renders the supervisor boot-prompt's `## Governance documents` section
/// from the five governance path fields, in canonical order.
///
/// Returns an empty `String` when every path is `None`. When at least one
/// path is set, the result is a self-contained block:
///
/// ```text
/// ## Governance documents
///
/// The supervisor consults these documents during spec audit.
///
/// - adr: docs/adr/
/// - dod: docs/dod.md
/// ```
///
/// The bullet list is built from the configured paths only — fields whose
/// value is `None` are skipped entirely (no placeholder line). The section
/// does not include any "gates" sub-line or per-doc enforcement metadata;
/// the `governance-config` capability dropped per-doc gate flags so there
/// is nothing to convey here beyond the paths themselves.
///
/// The caller is responsible for the blank line separating the section
/// from preceding boot-prompt content. When this function returns the
/// empty string, the boot prompt remains byte-identical to its v0.4
/// shape.
pub fn governance_section_paths(
    adr: Option<&Path>,
    test_strategy: Option<&Path>,
    security: Option<&Path>,
    dod: Option<&Path>,
    constitution: Option<&Path>,
) -> String {
    let bullets: [Option<&Path>; 5] = [adr, test_strategy, security, dod, constitution];
    if bullets.iter().all(Option::is_none) {
        return String::new();
    }

    let mut out = String::with_capacity(192);
    out.push_str("## Governance documents\n");
    out.push('\n');
    out.push_str("The supervisor consults these documents during spec audit.\n");
    out.push('\n');
    for (name, path) in GOVERNANCE_CANONICAL_NAMES.iter().zip(bullets.iter()) {
        if let Some(p) = path {
            use std::fmt::Write as _;
            // `writeln!` into a `String` never fails — formatting to a
            // growable buffer cannot run out of capacity. The `let _ =`
            // discards the `fmt::Result` without panicking.
            let _ = writeln!(out, "- {name}: {}", p.display());
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;

    // 9.2: Embedded coordination skill is reachable without any user files
    #[test]
    fn embedded_coordination_is_reachable() {
        let tmpl = resolve("coordination").expect("should resolve coordination");
        assert_eq!(tmpl.source, Source::Embedded);
        assert!(!tmpl.content.is_empty());
    }

    // 9.3: Embedded coordination skill contains all four operations
    #[test]
    fn embedded_coordination_contains_all_operations() {
        let tmpl = resolve("coordination").unwrap();
        assert!(tmpl.content.contains("agent.status"));
        assert!(tmpl.content.contains("agent.artifact"));
        assert!(tmpl.content.contains("agent.blocked"));
        assert!(
            tmpl.content
                .contains("{{GIT_PAW_BROKER_URL}}/messages/{{BRANCH_ID}}")
        );
    }

    #[test]
    fn embedded_coordination_documents_supervisor_messages() {
        let tmpl = resolve("coordination").unwrap();
        assert!(tmpl.content.contains("agent.verified"));
        assert!(tmpl.content.contains("agent.feedback"));
        assert!(tmpl.content.contains("re-publish"));
    }

    // === forward-coordination: existing-scenario coverage gaps ===

    #[test]
    fn coordination_skill_documents_automatic_status_publishing() {
        let tmpl = resolve("coordination").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("publishes your status automatically")
                || lowered.contains("status publishing is automatic")
                || lowered.contains("publishes status automatically"),
            "coordination skill should indicate that agent.status publishing is automatic"
        );
        assert!(
            !tmpl.content.contains("MUST publish agent.status"),
            "coordination skill must not contain the legacy 'MUST publish agent.status' instruction"
        );
    }

    #[test]
    fn coordination_skill_contains_cherry_pick_instructions() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("git cherry-pick"),
            "coordination skill should contain the literal 'git cherry-pick' command"
        );
        assert!(
            tmpl.content.contains("Cherry-pick peer commits"),
            "coordination skill should contain a 'Cherry-pick peer commits' heading"
        );
    }

    // === forward-coordination: agent.intent skill content ===

    #[test]
    fn coordination_skill_contains_before_you_start_editing_heading() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("Before you start editing"),
            "coordination skill should contain 'Before you start editing' heading"
        );
    }

    #[test]
    fn coordination_skill_contains_agent_intent_curl_example() {
        let tmpl = resolve("coordination").unwrap();
        let curl_pos = tmpl
            .content
            .find("agent.intent")
            .expect("coordination skill should mention agent.intent");
        // Look at a window around the intent example and assert all required
        // payload fields appear there.
        let window_start = curl_pos.saturating_sub(200);
        let window_end = (curl_pos + 800).min(tmpl.content.len());
        let window = &tmpl.content[window_start..window_end];
        assert!(
            window.contains("curl"),
            "agent.intent example should be a curl invocation"
        );
        assert!(
            window.contains("\"files\""),
            "agent.intent example should include the files field"
        );
        assert!(
            window.contains("\"summary\""),
            "agent.intent example should include the summary field"
        );
        assert!(
            window.contains("\"valid_for_seconds\""),
            "agent.intent example should include valid_for_seconds"
        );
    }

    #[test]
    fn coordination_skill_contains_while_youre_editing_heading() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("While you're editing"),
            "coordination skill should contain 'While you're editing' heading"
        );
    }

    #[test]
    fn coordination_skill_instructs_republish_on_scope_growth() {
        let tmpl = resolve("coordination").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("scope grows") || lowered.contains("scope grow"),
            "coordination skill should instruct re-publishing when scope grows"
        );
        assert!(
            lowered.contains("re-publish"),
            "coordination skill should mention re-publishing the intent"
        );
    }

    #[test]
    fn coordination_skill_instructs_question_on_peer_intent_overlap() {
        let tmpl = resolve("coordination").unwrap();
        // The skill should tell agents to send agent.question on overlap, not
        // race the peer.
        assert!(
            tmpl.content.contains("agent.question"),
            "coordination skill should reference agent.question"
        );
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("overlap") || lowered.contains("overlapping"),
            "coordination skill should call out overlap as the trigger for agent.question"
        );
    }

    #[test]
    fn coordination_skill_contains_must_not_anti_pattern_statements() {
        let tmpl = resolve("coordination").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("must not"),
            "coordination skill should contain explicit MUST NOT statements"
        );
        assert!(
            lowered.contains("pairwise"),
            "coordination skill should reject pairwise check-ins"
        );
        assert!(
            lowered.contains("go-ahead") || lowered.contains("go ahead"),
            "coordination skill should reject waiting for go-ahead"
        );
        assert!(
            lowered.contains("broker silence") || lowered.contains("silence"),
            "coordination skill should reject blocking on broker silence"
        );
    }

    #[test]
    fn supervisor_skill_contains_watch_peer_intents_section() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            tmpl.content.contains("Watch peer intents"),
            "supervisor skill should contain 'Watch peer intents' heading"
        );
        assert!(
            tmpl.content.contains("agent.intent"),
            "supervisor skill should mention agent.intent"
        );
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("not part of this release") || lowered.contains("conflict-detection"),
            "supervisor skill should note that automatic conflict-warning logic is not part of this release"
        );
    }

    /// `supervisor-bugfixes-v0-5-x` §3.10: the rendered supervisor skill SHALL
    /// invoke `.git-paw/scripts/sweep.sh` for snapshot / capture / approve /
    /// verified / feedback-gate, and SHALL NOT include legacy multi-pane
    /// `for p in …; do tmux capture-pane` loops.
    #[test]
    fn supervisor_skill_references_bundled_sweep_helper() {
        let tmpl = resolve("supervisor").unwrap();
        let required = [
            ".git-paw/scripts/sweep.sh snapshot",
            ".git-paw/scripts/sweep.sh capture",
            ".git-paw/scripts/sweep.sh approve",
            ".git-paw/scripts/sweep.sh verified",
            ".git-paw/scripts/sweep.sh feedback-gate",
        ];
        for needle in required {
            assert!(
                tmpl.content.contains(needle),
                "supervisor skill should reference {needle:?}; content does not"
            );
        }
        assert!(
            !tmpl.content.contains("for p in 2 3 4 5"),
            "supervisor skill should not contain legacy `for p in 2 3 4 5` capture-pane loops"
        );
    }

    // 9.4: Standard location skill loading
    #[test]
    #[serial(directory_changes)]
    fn standard_location_skill_loading() {
        let dir = tempfile::tempdir().unwrap();
        let project_dir = dir.path().join("my-project");
        std::fs::create_dir_all(&project_dir).unwrap();

        // Create skill in standard location
        let skill_dir = project_dir
            .join(".agents")
            .join("skills")
            .join("coordination");
        std::fs::create_dir_all(&skill_dir).unwrap();

        let skill_md_content = "---\nname: coordination\ndescription: Custom coordination skill\n---\n\ncustom skill content";
        std::fs::write(skill_dir.join("SKILL.md"), skill_md_content).unwrap();

        // Change to project directory
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&project_dir).unwrap();

        let tmpl = resolve("coordination").expect("should resolve");
        assert_eq!(tmpl.source, Source::AgentsStandard);
        assert!(tmpl.content.contains("custom skill content"));

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();
    }

    // 9.9: Unknown skill name returns error
    #[test]
    fn unknown_skill_returns_error() {
        let result = resolve("nonexistent");
        assert!(
            matches!(result, Err(SkillError::UnknownSkill { ref name }) if name == "nonexistent"),
            "expected UnknownSkill error, got {result:?}"
        );
    }

    // 9.10: {{BRANCH_ID}} is substituted
    #[test]
    fn branch_id_is_substituted() {
        let tmpl = SkillTemplate {
            name: "test".into(),
            content: "agent_id:\"{{BRANCH_ID}}\"".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let output = render(
            &tmpl,
            "feat/http-broker",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        assert!(output.contains("feat-http-broker"));
        assert!(!output.contains("{{BRANCH_ID}}"));
    }

    // 9.11: {{GIT_PAW_BROKER_URL}} is substituted at render time
    #[test]
    fn broker_url_placeholder_substituted() {
        let tmpl = SkillTemplate {
            name: "test".into(),
            content: "curl {{GIT_PAW_BROKER_URL}}/status".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let output = render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        assert!(output.contains("http://127.0.0.1:9119/status"));
        assert!(!output.contains("{{GIT_PAW_BROKER_URL}}"));
    }

    // 9.12: Slug substitution matches slugify_branch
    #[test]
    fn slug_substitution_matches_slugify_branch() {
        let tmpl = SkillTemplate {
            name: "test".into(),
            content: "id={{BRANCH_ID}}".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let output = render(
            &tmpl,
            "Feature/HTTP_Broker",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        let expected = slugify_branch("Feature/HTTP_Broker");
        assert_eq!(output, format!("id={expected}"));
    }

    // 9.13: Render is deterministic
    #[test]
    fn render_is_deterministic() {
        let tmpl = resolve("coordination").unwrap();
        let a = render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        let b = render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        assert_eq!(a, b);
    }

    // 9.14: Render performs no I/O (resolve then render after "deletion")
    #[test]
    #[serial(directory_changes)]
    fn render_performs_no_io() {
        let dir = tempfile::tempdir().unwrap();
        let project_dir = dir.path().join("my-project");
        std::fs::create_dir_all(&project_dir).unwrap();

        let skill_dir = project_dir
            .join(".agents")
            .join("skills")
            .join("coordination");
        std::fs::create_dir_all(&skill_dir).unwrap();

        let skill_md_content = "---\nname: coordination\ndescription: Test coordination skill\n---\n\nuser {{BRANCH_ID}}";
        std::fs::write(skill_dir.join("SKILL.md"), skill_md_content).unwrap();

        // Change to project directory
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&project_dir).unwrap();

        let tmpl = resolve("coordination").unwrap();
        assert_eq!(tmpl.source, Source::AgentsStandard);

        // Delete the skill directory — render must still succeed from in-memory content
        std::fs::remove_dir_all(skill_dir).unwrap();
        let output = render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        assert!(output.contains("feat-x"));

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();
    }

    // 9.15: Unknown placeholder survives in output (warning is emitted to stderr)
    #[test]
    fn unknown_placeholder_survives() {
        let tmpl = SkillTemplate {
            name: "test".into(),
            content: "url={{UNKNOWN_THING}}".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let output = render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        assert!(
            output.contains("{{UNKNOWN_THING}}"),
            "unknown placeholder should survive in output"
        );
    }

    // 9.16: No {{...}} remains after rendering the embedded coordination template
    #[test]
    fn no_unknown_placeholders_after_render() {
        let tmpl = resolve("coordination").unwrap();
        let output = render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        assert!(
            !output.contains("{{"),
            "no double-curly placeholders should remain: {output}"
        );
    }

    // Supervisor skill is reachable as an embedded default
    #[test]
    fn embedded_supervisor_is_reachable() {
        let tmpl = resolve("supervisor").expect("should resolve supervisor");
        assert_eq!(tmpl.source, Source::Embedded);
        assert!(!tmpl.content.is_empty());
    }

    // Supervisor skill contains role definition
    #[test]
    fn supervisor_skill_contains_role_definition() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(tmpl.content.contains("do NOT write code"));
    }

    // Supervisor skill contains broker status endpoint
    #[test]
    fn supervisor_skill_contains_broker_status() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(tmpl.content.contains("{{GIT_PAW_BROKER_URL}}/status"));
    }

    // Supervisor skill contains verified and feedback message types
    #[test]
    fn supervisor_skill_contains_verified_and_feedback() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(tmpl.content.contains("agent.verified"));
        assert!(tmpl.content.contains("agent.feedback"));
    }

    /// Returns the substring containing the supervisor skill's `agent.verified`
    /// curl example body (the JSON payload region), used to scope wire-format
    /// assertions to the verified example without picking up other prose.
    fn verified_curl_example_body(content: &str) -> &str {
        let start = content
            .find("\"type\":\"agent.verified\"")
            .expect("supervisor skill should contain an agent.verified curl example");
        let rest = &content[start..];
        let end = rest
            .find("}}'")
            .expect("agent.verified curl example should terminate with the closing payload `}}'`");
        &rest[..end + 3]
    }

    /// Returns the substring containing the supervisor skill's `agent.feedback`
    /// curl example body (the JSON payload region).
    fn feedback_curl_example_body(content: &str) -> &str {
        let start = content
            .find("\"type\":\"agent.feedback\"")
            .expect("supervisor skill should contain an agent.feedback curl example");
        let rest = &content[start..];
        let end = rest
            .find("}}'")
            .expect("agent.feedback curl example should terminate with the closing payload `}}'`");
        &rest[..end + 3]
    }

    #[test]
    fn supervisor_verified_example_uses_correct_payload_fields() {
        let tmpl = resolve("supervisor").unwrap();
        let example = verified_curl_example_body(&tmpl.content);
        assert!(
            example.contains("verified_by"),
            "agent.verified example must use the `verified_by` payload field: {example}"
        );
        assert!(
            example.contains("message"),
            "agent.verified example must use the `message` payload field: {example}"
        );
        for wrong in ["\"target\"", "\"result\"", "\"notes\""] {
            assert!(
                !example.contains(wrong),
                "agent.verified example must not contain the stale field key {wrong}: {example}"
            );
        }
    }

    #[test]
    fn supervisor_feedback_example_uses_correct_payload_fields() {
        let tmpl = resolve("supervisor").unwrap();
        let example = feedback_curl_example_body(&tmpl.content);
        assert!(
            example.contains("\"from\""),
            "agent.feedback example must use the `from` payload field: {example}"
        );
        assert!(
            example.contains("\"errors\""),
            "agent.feedback example must use the `errors` payload field: {example}"
        );
        assert!(
            example.contains('['),
            "agent.feedback example's errors field must be a JSON array (contains `[`): {example}"
        );
        assert!(
            example.contains(']'),
            "agent.feedback example's errors field must be a JSON array (contains `]`): {example}"
        );
        for wrong in ["\"target\"", "\"message\""] {
            assert!(
                !example.contains(wrong),
                "agent.feedback example must not contain the stale field key {wrong}: {example}"
            );
        }
    }

    #[test]
    fn supervisor_examples_clarify_recipient_vs_sender() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();

        // Verified-section clarification (between the verified heading and the
        // feedback heading).
        let verified_start = tmpl
            .content
            .find("### Publish verification outcome")
            .expect("verified heading should be present");
        let feedback_start = tmpl
            .content
            .find("### Publish feedback to a peer agent")
            .expect("feedback heading should be present");
        let verified_section = tmpl.content[verified_start..feedback_start].to_lowercase();
        assert!(
            verified_section.contains("recipient") && verified_section.contains("sender"),
            "verified section should clarify recipient-vs-sender semantics, got: {verified_section}"
        );

        // Feedback-section clarification (between the feedback heading and the
        // next `### ` heading).
        let after_feedback =
            &tmpl.content[feedback_start + "### Publish feedback to a peer agent".len()..];
        let feedback_end_rel = after_feedback
            .find("\n### ")
            .unwrap_or(after_feedback.len());
        let feedback_section = after_feedback[..feedback_end_rel].to_lowercase();
        assert!(
            feedback_section.contains("recipient") && feedback_section.contains("sender"),
            "feedback section should clarify recipient-vs-sender semantics, got: {feedback_section}"
        );

        // Defensive sanity: the words exist somewhere in the document.
        assert!(lowered.contains("recipient"));
        assert!(lowered.contains("sender"));
    }

    #[test]
    fn supervisor_workflow_prose_drops_legacy_verified_fields() {
        let tmpl = resolve("supervisor").unwrap();
        // Strip whitespace inside the matches so a stray space doesn't hide a
        // regression like `result : "pass"` or `notes : ""`.
        let condensed: String = tmpl
            .content
            .chars()
            .filter(|c| !c.is_whitespace())
            .collect();
        assert!(
            !condensed.contains("result:\"pass\""),
            "workflow prose must not reference `result:\"pass\"` as the verified payload"
        );
        assert!(
            !condensed.contains("notes:\"\""),
            "workflow prose must not reference `notes:\"\"` as the verified payload"
        );
    }

    // Supervisor skill contains tmux commands targeting the session name
    #[test]
    fn supervisor_skill_contains_tmux_commands() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(tmpl.content.contains("tmux capture-pane"));
        assert!(tmpl.content.contains("tmux send-keys"));
        assert!(tmpl.content.contains("paw-{{PROJECT_NAME}}"));
    }

    #[test]
    fn supervisor_skill_contains_spec_audit_procedure() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            tmpl.content.contains("Spec Audit"),
            "supervisor skill should contain Spec Audit section"
        );
        assert!(
            tmpl.content.contains("openspec/changes/"),
            "should reference openspec/changes/ for spec file discovery"
        );
        assert!(
            tmpl.content.contains("grep"),
            "should instruct to grep for matching tests"
        );
    }

    #[test]
    fn supervisor_skill_spec_audit_after_test_before_verified() {
        let tmpl = resolve("supervisor").unwrap();
        let test_pos = tmpl.content.find("Regression check").unwrap_or(0);
        let audit_pos = tmpl.content.find("Spec Audit").unwrap_or(0);
        let verify_pos = tmpl.content.find("Verify or feedback").unwrap_or(0);
        assert!(
            audit_pos > test_pos,
            "spec audit should appear after test/regression check"
        );
        assert!(
            audit_pos < verify_pos,
            "spec audit should appear before verify/feedback"
        );
    }

    // Paste-buffer recovery sub-case under stall detection (prompt-submit-fix).

    #[test]
    fn supervisor_skill_mentions_paste_buffer_recovery() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("paste-buffer") || lowered.contains("paste buffer"),
            "supervisor skill should contain paste-buffer recovery sub-case"
        );
    }

    #[test]
    fn supervisor_skill_mentions_pasted_text_indicator() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            tmpl.content.contains("Pasted text"),
            "supervisor skill should mention the Claude Code 'Pasted text' indicator"
        );
    }

    #[test]
    fn supervisor_skill_paste_buffer_recovery_uses_tmux() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .to_lowercase()
            .find("paste-buffer recovery")
            .or_else(|| tmpl.content.to_lowercase().find("paste buffer recovery"))
            .expect("paste-buffer recovery sub-case heading should be present");
        // Take a window around the heading large enough to cover the
        // recovery example (a couple thousand chars now that the sub-case
        // also references the proactive launch-time sweep).
        let window_end = (start + 2200).min(tmpl.content.len());
        let window = &tmpl.content[start..window_end];
        // The inspect step now goes through `sweep.sh capture <pane>`; the
        // earlier shape `tmux capture-pane …` is still acceptable for
        // historical content. Either form satisfies the inspect contract.
        assert!(
            window.contains(".git-paw/scripts/sweep.sh capture")
                || window.contains("tmux capture-pane"),
            "paste-buffer recovery should reference a pane-capture command (sweep.sh capture or tmux capture-pane)"
        );
        assert!(
            window.contains("tmux send-keys"),
            "paste-buffer recovery should reference tmux send-keys for the Enter recovery"
        );
        assert!(
            window.contains("Enter"),
            "paste-buffer recovery should specify Enter as the recovery keystroke"
        );
    }

    #[test]
    fn supervisor_skill_mentions_launch_time_sweep() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("launch-time pane sweep")
                || lowered.contains("launch time pane sweep")
                || lowered.contains("launch sweep"),
            "supervisor skill should contain a launch-time pane sweep heading"
        );
    }

    #[test]
    fn supervisor_skill_launch_sweep_lists_four_pane_categories() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        let start = lowered
            .find("launch-time pane sweep")
            .or_else(|| lowered.find("launch sweep"))
            .expect("launch-time pane sweep heading should be present");
        let window_end = (start + 2500).min(lowered.len());
        let window = &lowered[start..window_end];
        assert!(
            window.contains("paste-buffer") || window.contains("paste buffer"),
            "launch sweep should enumerate paste-buffer category"
        );
        assert!(
            window.contains("permission prompt"),
            "launch sweep should enumerate permission-prompt category"
        );
        assert!(
            window.contains("working"),
            "launch sweep should enumerate working category"
        );
        assert!(
            window.contains("idle"),
            "launch sweep should enumerate idle category"
        );
    }

    #[test]
    fn supervisor_skill_launch_sweep_references_down_enter_keystroke() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        let start = lowered
            .find("launch-time pane sweep")
            .or_else(|| lowered.find("launch sweep"))
            .expect("launch-time pane sweep heading should be present");
        let window_end = (start + 2500).min(lowered.len());
        let window = &lowered[start..window_end];
        // Safe-command auto-approval uses Down to move to "Yes, don't ask
        // again", then Enter to select it. Both keystrokes must be in the
        // section so the supervisor agent knows the pattern.
        assert!(
            window.contains("down"),
            "launch sweep should reference the Down keystroke for selecting 'don't ask again'"
        );
        assert!(
            window.contains("enter"),
            "launch sweep should reference the Enter keystroke for confirming approval"
        );
        // Confirm the "don't ask again" phrasing is present so future
        // pattern allowlist behavior is documented in the skill.
        assert!(
            window.contains("don't ask again") || window.contains("don't ask"),
            "launch sweep should mention the 'don't ask again' approval option"
        );
    }

    #[test]
    fn supervisor_skill_paste_buffer_recovery_is_safe_by_default() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        let start = lowered
            .find("paste-buffer recovery")
            .or_else(|| lowered.find("paste buffer recovery"))
            .expect("paste-buffer recovery sub-case heading should be present");
        let window_end = (start + 2200).min(lowered.len());
        let window = &lowered[start..window_end];
        let safe_phrasing = window.contains("safe-by-default")
            || window.contains("safe by default")
            || window.contains("no-op")
            || window.contains("no harm");
        assert!(
            safe_phrasing,
            "paste-buffer recovery should explicitly note the Enter is safe-by-default / no-op / no harm"
        );
    }

    // Governance verification sub-step in the supervisor skill (governance-context §5).

    #[test]
    fn supervisor_skill_contains_governance_verification() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            tmpl.content.contains("Governance verification"),
            "supervisor skill should contain 'Governance verification' heading"
        );
    }

    #[test]
    fn supervisor_skill_governance_is_substep_of_spec_audit() {
        let tmpl = resolve("supervisor").unwrap();
        let audit_pos = tmpl
            .content
            .find("### Spec Audit Procedure")
            .expect("Spec Audit Procedure heading must exist");
        let gov_pos = tmpl
            .content
            .find("Governance verification")
            .expect("Governance verification must exist");
        let conflict_pos = tmpl
            .content
            .find("### Conflict detection")
            .unwrap_or(tmpl.content.len());
        assert!(
            gov_pos > audit_pos,
            "Governance verification should appear inside Spec Audit Procedure (after its heading)"
        );
        assert!(
            gov_pos < conflict_pos,
            "Governance verification should appear before the next top-level subsection (Conflict detection), keeping it inside Spec Audit Procedure"
        );
        assert!(
            !tmpl.content.contains("step 7.5"),
            "Governance verification must not be framed as a separate 'step 7.5' flow step"
        );
    }

    #[test]
    fn supervisor_skill_governance_examples_cover_all_five_docs() {
        let tmpl = resolve("supervisor").unwrap();
        let gov_pos = tmpl
            .content
            .find("Governance verification")
            .expect("Governance verification section must exist");
        // Confine the search to the governance subsection (everything between
        // the heading and the next `### ` top-level subsection or EOF).
        let after = &tmpl.content[gov_pos..];
        let end = after.find("\n### ").unwrap_or(after.len());
        let section = &after[..end];
        for needle in &["DoD", "ADR", "Security", "Test strategy", "Constitution"] {
            assert!(
                section.contains(needle),
                "governance section should mention `{needle}` as a per-doc example, got:\n{section}"
            );
        }
    }

    #[test]
    fn supervisor_skill_governance_findings_via_agent_feedback() {
        let tmpl = resolve("supervisor").unwrap();
        let gov_pos = tmpl
            .content
            .find("Governance verification")
            .expect("Governance verification section must exist");
        let after = &tmpl.content[gov_pos..];
        let end = after.find("\n### ").unwrap_or(after.len());
        let section = &after[..end];
        assert!(
            section.contains("agent.feedback"),
            "governance section must state that findings flow through `agent.feedback`"
        );
    }

    #[test]
    fn supervisor_skill_no_governance_gate_tag() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            !tmpl.content.contains("[governance-gate:"),
            "supervisor skill must not contain the dropped `[governance-gate:<doc>]` tag prefix"
        );
    }

    #[test]
    fn supervisor_skill_no_governance_gates_table() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            !tmpl.content.contains("[governance.gates]"),
            "supervisor skill must not reference the dropped `[governance.gates]` table"
        );
    }

    #[test]
    fn supervisor_skill_no_gating_language() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            !lowered.contains("gating"),
            "supervisor skill must not use the language of 'gating'"
        );
        assert!(
            !lowered.contains("blocking on governance failures"),
            "supervisor skill must not use the language of 'blocking on governance failures'"
        );
    }

    #[test]
    fn supervisor_skill_governance_missing_doc_handling() {
        let tmpl = resolve("supervisor").unwrap();
        let gov_pos = tmpl
            .content
            .find("Governance verification")
            .expect("Governance verification section must exist");
        let after = &tmpl.content[gov_pos..];
        let end = after.find("\n### ").unwrap_or(after.len());
        let section = &after[..end];
        let lowered = section.to_lowercase();
        assert!(
            lowered.contains("missing"),
            "governance section should describe missing-doc handling"
        );
        assert!(
            section.contains("agent.feedback"),
            "missing-doc handling should reference `agent.feedback` errors list"
        );
    }

    #[test]
    fn supervisor_skill_governance_missing_doc_is_not_distinct_failure_type() {
        let tmpl = resolve("supervisor").unwrap();
        let gov_pos = tmpl
            .content
            .find("Governance verification")
            .expect("Governance verification section must exist");
        let after = &tmpl.content[gov_pos..];
        let end = after.find("\n### ").unwrap_or(after.len());
        let section = &after[..end];
        let lowered = section.to_lowercase();
        assert!(
            lowered.contains("not a distinct failure")
                || lowered.contains("not a separate failure")
                || lowered.contains("treat it as a finding"),
            "governance section must state that missing files are findings, not a distinct failure type; got:\n{section}"
        );
    }

    #[test]
    fn supervisor_skill_governance_states_activation_condition() {
        let tmpl = resolve("supervisor").unwrap();
        let gov_pos = tmpl
            .content
            .find("Governance verification")
            .expect("Governance verification section must exist");
        let after = &tmpl.content[gov_pos..];
        let end = after.find("\n### ").unwrap_or(after.len());
        let section = &after[..end];
        let lowered = section.to_lowercase();
        assert!(
            lowered.contains("skip"),
            "governance section must instruct the supervisor to skip the sub-step when the boot prompt has no `## Governance documents` section; got:\n{section}"
        );
        assert!(
            section.contains("## Governance documents"),
            "governance section must reference the boot-prompt heading explicitly as its activation condition; got:\n{section}"
        );
    }

    #[test]
    fn supervisor_skill_governance_examples_state_they_are_illustrative() {
        let tmpl = resolve("supervisor").unwrap();
        let gov_pos = tmpl
            .content
            .find("Governance verification")
            .expect("Governance verification section must exist");
        let after = &tmpl.content[gov_pos..];
        let end = after.find("\n### ").unwrap_or(after.len());
        let section = &after[..end];
        let lowered = section.to_lowercase();
        assert!(
            lowered.contains("illustrative") || lowered.contains("not exhaustive"),
            "governance section must state per-doc examples are illustrative / not exhaustive rubrics; got:\n{section}"
        );
    }

    #[test]
    fn supervisor_skill_governance_states_judgment_per_project_conventions() {
        let tmpl = resolve("supervisor").unwrap();
        let gov_pos = tmpl
            .content
            .find("Governance verification")
            .expect("Governance verification section must exist");
        let after = &tmpl.content[gov_pos..];
        let end = after.find("\n### ").unwrap_or(after.len());
        let section = &after[..end];
        let lowered = section.to_lowercase();
        assert!(
            lowered.contains("judgment"),
            "governance section must state the supervisor applies judgment; got:\n{section}"
        );
        assert!(
            lowered.contains("convention") || lowered.contains("project"),
            "governance section must reference the project's conventions / process when describing judgment; got:\n{section}"
        );
    }

    // governance_section_paths renderer (governance-context §1, §3).

    #[test]
    fn governance_section_empty_when_all_paths_none() {
        let out = governance_section_paths(None, None, None, None, None);
        assert!(
            out.is_empty(),
            "governance_section_paths should return empty string when all paths are None, got: {out:?}"
        );
    }

    #[test]
    fn governance_section_one_path_only_dod() {
        let dod = Path::new("docs/dod.md");
        let out = governance_section_paths(None, None, None, Some(dod), None);
        assert!(
            out.contains("## Governance documents"),
            "section should include the canonical heading, got:\n{out}"
        );
        assert!(
            out.contains("- dod: docs/dod.md"),
            "section should include the dod bullet, got:\n{out}"
        );
        for unset in [
            "- adr:",
            "- test_strategy:",
            "- security:",
            "- constitution:",
        ] {
            assert!(
                !out.contains(unset),
                "section should not mention `{unset}` when its path is None, got:\n{out}"
            );
        }
    }

    #[test]
    fn governance_section_lists_all_five_in_canonical_order() {
        let adr = Path::new("docs/adr/");
        let test_strategy = Path::new("docs/test-strategy.md");
        let security = Path::new("docs/security.md");
        let dod = Path::new("docs/dod.md");
        let constitution = Path::new("docs/constitution.md");
        let out = governance_section_paths(
            Some(adr),
            Some(test_strategy),
            Some(security),
            Some(dod),
            Some(constitution),
        );

        let order = [
            "- adr: docs/adr/",
            "- test_strategy: docs/test-strategy.md",
            "- security: docs/security.md",
            "- dod: docs/dod.md",
            "- constitution: docs/constitution.md",
        ];
        let mut last_pos = 0usize;
        for bullet in order {
            let idx = out
                .find(bullet)
                .unwrap_or_else(|| panic!("bullet `{bullet}` not found in:\n{out}"));
            assert!(
                idx >= last_pos,
                "bullets must appear in canonical adr -> test_strategy -> security -> dod -> constitution order; `{bullet}` came before a previous bullet in:\n{out}"
            );
            last_pos = idx;
        }
    }

    #[test]
    fn governance_section_has_no_gates_text() {
        let out = governance_section_paths(
            Some(Path::new("docs/adr/")),
            Some(Path::new("docs/test-strategy.md")),
            Some(Path::new("docs/security.md")),
            Some(Path::new("docs/dod.md")),
            Some(Path::new("docs/constitution.md")),
        );
        let lowered = out.to_lowercase();
        assert!(
            !lowered.contains("gated docs"),
            "section should not contain a 'Gated docs' line, got:\n{out}"
        );
        assert!(
            !lowered.contains("governance gates"),
            "section should not contain a 'Governance gates' sub-section, got:\n{out}"
        );
        assert!(
            !out.contains("[governance.gates]"),
            "section should not reference the dropped [governance.gates] table, got:\n{out}"
        );
        assert!(
            !out.contains("[governance-gate:"),
            "section should not introduce the dropped [governance-gate:<doc>] tag, got:\n{out}"
        );
    }

    #[test]
    fn governance_section_has_preamble_line() {
        let out = governance_section_paths(None, None, None, Some(Path::new("docs/dod.md")), None);
        let preamble = "The supervisor consults these documents during spec audit.";
        assert!(
            out.contains(preamble),
            "section should include the preamble line; got:\n{out}"
        );
        // Preamble must come before bullets and after the heading.
        let heading_pos = out.find("## Governance documents").unwrap();
        let preamble_pos = out.find(preamble).unwrap();
        let bullet_pos = out.find("- dod:").unwrap();
        assert!(
            heading_pos < preamble_pos && preamble_pos < bullet_pos,
            "section layout should be heading -> preamble -> bullets; got:\n{out}"
        );
    }

    // {{PROJECT_NAME}} is substituted by render
    #[test]
    fn project_name_is_substituted() {
        let tmpl = SkillTemplate {
            name: "test".into(),
            content: "session=paw-{{PROJECT_NAME}}".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let output = render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "my-app",
            &GateCommands::default(),
        );
        assert!(output.contains("paw-my-app"));
        assert!(!output.contains("{{PROJECT_NAME}}"));
    }

    // Both BRANCH_ID and PROJECT_NAME substituted in the same template
    #[test]
    fn branch_id_and_project_name_both_substituted() {
        let tmpl = SkillTemplate {
            name: "test".into(),
            content: "agent={{BRANCH_ID}} session=paw-{{PROJECT_NAME}}".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let output = render(
            &tmpl,
            "feat/http-broker",
            "url",
            "git-paw",
            &GateCommands::default(),
        );
        assert!(output.contains("feat-http-broker"));
        assert!(output.contains("paw-git-paw"));
        assert!(!output.contains("{{BRANCH_ID}}"));
        assert!(!output.contains("{{PROJECT_NAME}}"));
    }

    // Standardized skill format is detected and loaded
    #[test]
    #[serial(directory_changes)]
    fn standardized_skill_format_is_detected() {
        let dir = tempfile::tempdir().unwrap();
        let project_dir = dir.path().join("my-project");
        std::fs::create_dir_all(&project_dir).unwrap();

        let skill_dir = project_dir
            .join(".agents")
            .join("skills")
            .join("test-standardized");
        std::fs::create_dir_all(&skill_dir).unwrap();

        let skill_md_content = "---\nname: test-standardized\ndescription: A test standardized skill\n---\n\nThis is the skill content with {{BRANCH_ID}} placeholder.";
        std::fs::write(skill_dir.join("SKILL.md"), skill_md_content).unwrap();

        // Change to project directory
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&project_dir).unwrap();

        let tmpl = resolve("test-standardized").expect("should resolve");
        assert_eq!(tmpl.format, SkillFormat::Standardized);
        assert!(tmpl.content.contains("This is the skill content"));
        assert!(tmpl.content.contains("{{BRANCH_ID}}"));
        assert!(tmpl.metadata.is_some());
        let metadata = tmpl.metadata.as_ref().unwrap();
        assert_eq!(metadata.name, "test-standardized");
        assert_eq!(metadata.description, "A test standardized skill");

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();
    }

    // Standardized skill with resources loads resource paths
    #[test]
    fn standardized_skill_with_resources_loads_paths() {
        let dir = tempfile::tempdir().unwrap();
        let skills_parent_dir = dir.path().join("git-paw").join("agent-skills");
        let specific_skill_dir = skills_parent_dir.join("test-with-resources");
        std::fs::create_dir_all(&specific_skill_dir).unwrap();

        // Create skill directory structure
        std::fs::create_dir_all(specific_skill_dir.join("scripts")).unwrap();
        std::fs::create_dir_all(specific_skill_dir.join("references")).unwrap();
        std::fs::create_dir_all(specific_skill_dir.join("assets")).unwrap();

        let skill_md_content = "---\nname: test-with-resources\ndescription: Skill with resources\n---\n\nMain content here.";
        std::fs::write(specific_skill_dir.join("SKILL.md"), skill_md_content).unwrap();

        let tmpl = resolve_with_config_dir("test-with-resources", Some(dir.path()))
            .expect("should resolve");
        assert_eq!(tmpl.format, SkillFormat::Standardized);
        assert!(tmpl.resource_paths.is_some());
        let resource_paths = tmpl.resource_paths.as_ref().unwrap();
        assert_eq!(resource_paths.len(), 3);
        assert!(resource_paths.iter().any(|p| p.ends_with("scripts")));
        assert!(resource_paths.iter().any(|p| p.ends_with("references")));
        assert!(resource_paths.iter().any(|p| p.ends_with("assets")));
    }

    // Standard location (.agents/skills/) loading
    #[test]
    #[serial(directory_changes)]
    fn standard_location_loading() {
        let temp_dir = tempfile::tempdir().unwrap();
        let project_dir = temp_dir.path().join("my-project");
        std::fs::create_dir_all(&project_dir).unwrap();

        // Create skill in standard location
        let standard_skill_dir = project_dir
            .join(".agents")
            .join("skills")
            .join("test-skill");
        std::fs::create_dir_all(&standard_skill_dir).unwrap();
        let standard_content = "---\nname: test-skill\ndescription: Standard location skill\n---\n\nContent from .agents/skills/";
        std::fs::write(standard_skill_dir.join("SKILL.md"), standard_content).unwrap();

        // Change to project directory so .agents/skills/ can be found
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&project_dir).unwrap();

        let tmpl = resolve("test-skill").expect("should resolve");

        // Should load from standard location
        assert_eq!(tmpl.source, Source::AgentsStandard);
        assert!(tmpl.content.contains("Content from .agents/skills/"));

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();
    }

    // Standardized skill metadata placeholders are substituted
    #[test]
    fn standardized_skill_metadata_placeholders_are_substituted() {
        let metadata = StandardizedSkillMetadata {
            name: "test-skill".to_string(),
            description: "Test description".to_string(),
            license: None,
            compatibility: None,
            metadata: None,
        };

        let tmpl = SkillTemplate {
            name: "test".into(),
            content: "Name: {{SKILL_NAME}}, Desc: {{SKILL_DESCRIPTION}}".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: Some(metadata),
            resource_paths: None,
        };

        let output = render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        assert!(output.contains("Name: test-skill, Desc: Test description"));
        assert!(!output.contains("{{SKILL_NAME}}"));
        assert!(!output.contains("{{SKILL_DESCRIPTION}}"));
    }

    #[test]
    fn test_command_placeholder_substitutes_when_set() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run `{{TEST_COMMAND}}` after each merge.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands {
                test_command: Some("just check"),
                ..Default::default()
            },
        );
        assert_eq!(output, "Run `just check` after each merge.");
        assert!(!output.contains("{{TEST_COMMAND}}"));
    }

    #[test]
    fn test_command_placeholder_falls_back_when_unset() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Baseline: {{TEST_COMMAND}}".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );
        assert_eq!(output, "Baseline: (not configured)");
        assert!(!output.contains("{{TEST_COMMAND}}"));
    }

    #[test]
    fn supervisor_template_no_unsubstituted_placeholders_when_test_command_set() {
        // Regression: rendering the embedded supervisor skill with a configured
        // test_command must NOT leave {{TEST_COMMAND}} in the output. Captured
        // during a live dogfood run that produced the warning
        // "unsubstituted placeholder {{TEST_COMMAND}} in skill 'supervisor'".
        //
        // `{{CHANGE_ID}}` is a per-invocation placeholder (substituted by the
        // supervisor agent, not by render) and is therefore expected to
        // survive a render pass.
        let tmpl = resolve("supervisor").expect("supervisor skill resolves");
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands {
                test_command: Some("just check"),
                ..Default::default()
            },
        );
        assert!(
            !output.contains("{{TEST_COMMAND}}"),
            "supervisor template still contains a literal {{TEST_COMMAND}} after render"
        );
        let remaining: String = output.replace("{{CHANGE_ID}}", "").chars().collect();
        assert!(
            !remaining.contains("{{"),
            "supervisor template has unsubstituted {{...}} placeholder (other than {{CHANGE_ID}}) after render"
        );
    }

    // --- Gate-command placeholder substitution (supervisor-gate-templating-v0-5-x) ---

    /// Helper: render `template` with all gate placeholders set to the same
    /// `Some(value)` or all `None`.
    fn render_with_gates_uniform(template: &str, value: Option<&str>) -> String {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: template.into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            test_command: value,
            lint_command: value,
            build_command: value,
            doc_build_command: value,
            spec_validate_command: value,
            fmt_check_command: value,
            security_audit_command: value,
        };
        render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        )
    }

    #[test]
    fn render_test_command_placeholder_substitutes_from_config() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run {{TEST_COMMAND}}.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            test_command: Some("just check"),
            ..Default::default()
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        assert!(
            output.contains("Run just check."),
            "expected 'Run just check.' in: {output}"
        );
    }

    #[test]
    fn render_test_command_placeholder_none_renders_not_configured() {
        let output = render_with_gates_uniform("Run {{TEST_COMMAND}}.", None);
        assert!(
            output.contains("Run (not configured)."),
            "expected 'Run (not configured).' in: {output}"
        );
    }

    #[test]
    fn render_lint_command_placeholder_substitutes_and_none_fallback() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run {{LINT_COMMAND}}.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            lint_command: Some("cargo clippy -- -D warnings"),
            ..Default::default()
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        assert!(
            output.contains("Run cargo clippy -- -D warnings."),
            "expected substitution in: {output}"
        );

        let none_output = render_with_gates_uniform("Run {{LINT_COMMAND}}.", None);
        assert!(
            none_output.contains("Run (not configured)."),
            "expected '(not configured)' fallback in: {none_output}"
        );
    }

    #[test]
    fn render_build_command_placeholder_substitutes_and_none_fallback() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run {{BUILD_COMMAND}}.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            build_command: Some("cargo build"),
            ..Default::default()
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        assert!(output.contains("Run cargo build."), "got: {output}");

        let none_output = render_with_gates_uniform("Run {{BUILD_COMMAND}}.", None);
        assert!(
            none_output.contains("Run (not configured)."),
            "got: {none_output}"
        );
    }

    #[test]
    fn render_doc_build_command_placeholder_substitutes_and_none_fallback() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run {{DOC_BUILD_COMMAND}}.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            doc_build_command: Some("mdbook build docs/"),
            ..Default::default()
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        assert!(output.contains("Run mdbook build docs/."), "got: {output}");

        let none_output = render_with_gates_uniform("Run {{DOC_BUILD_COMMAND}}.", None);
        assert!(
            none_output.contains("Run (not configured)."),
            "got: {none_output}"
        );
    }

    #[test]
    fn render_spec_validate_command_placeholder_substitutes_and_none_fallback() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run {{SPEC_VALIDATE_COMMAND}}.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            spec_validate_command: Some("openspec validate {{CHANGE_ID}} --strict"),
            ..Default::default()
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        assert!(
            output.contains("Run openspec validate {{CHANGE_ID}} --strict."),
            "got: {output}"
        );

        let none_output = render_with_gates_uniform("Run {{SPEC_VALIDATE_COMMAND}}.", None);
        assert!(
            none_output.contains("Run (not configured)."),
            "got: {none_output}"
        );
    }

    #[test]
    fn render_fmt_check_command_placeholder_substitutes_and_none_fallback() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run {{FMT_CHECK_COMMAND}}.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            fmt_check_command: Some("cargo fmt --check"),
            ..Default::default()
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        assert!(output.contains("Run cargo fmt --check."), "got: {output}");

        let none_output = render_with_gates_uniform("Run {{FMT_CHECK_COMMAND}}.", None);
        assert!(
            none_output.contains("Run (not configured)."),
            "got: {none_output}"
        );
    }

    #[test]
    fn render_security_audit_command_placeholder_substitutes_and_none_fallback() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run {{SECURITY_AUDIT_COMMAND}}.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            security_audit_command: Some("cargo audit"),
            ..Default::default()
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        assert!(output.contains("Run cargo audit."), "got: {output}");

        let none_output = render_with_gates_uniform("Run {{SECURITY_AUDIT_COMMAND}}.", None);
        assert!(
            none_output.contains("Run (not configured)."),
            "got: {none_output}"
        );
    }

    #[test]
    fn supervisor_skill_renders_with_all_six_gate_placeholders_set() {
        // With distinct Some("CMD-N") values, the rendered supervisor skill
        // contains each CMD-N value (proving the gate prose references the
        // placeholders, not hardcoded git-paw commands).
        let tmpl = resolve("supervisor").expect("supervisor skill resolves");
        let gates = GateCommands {
            test_command: Some("CMD-TEST"),
            lint_command: Some("CMD-LINT"),
            build_command: Some("CMD-BUILD"),
            doc_build_command: Some("CMD-DOC"),
            spec_validate_command: Some("CMD-SPEC"),
            fmt_check_command: Some("CMD-FMT"),
            security_audit_command: Some("CMD-SEC"),
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        for needle in [
            "CMD-TEST",
            "CMD-LINT",
            "CMD-BUILD",
            "CMD-DOC",
            "CMD-SPEC",
            "CMD-FMT",
            "CMD-SEC",
        ] {
            assert!(
                output.contains(needle),
                "rendered supervisor skill should contain '{needle}'; not found"
            );
        }
    }

    #[test]
    fn supervisor_skill_renders_not_configured_in_each_gate_when_none() {
        // With all placeholders None, every gate section in the rendered
        // skill must show '(not configured)' so the supervisor agent can
        // recognise the gate as having no tooling-aided phase.
        let tmpl = resolve("supervisor").expect("supervisor skill resolves");
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        );

        // Gate 1 (Testing) section.
        let testing_start = output.find("**Testing**").expect("Testing gate present");
        let testing_end = output[testing_start..]
            .find("**Regression analysis**")
            .map(|p| testing_start + p)
            .expect("Regression follows Testing");
        let testing_section = &output[testing_start..testing_end];
        assert!(
            testing_section.contains("(not configured)"),
            "Testing gate should render '(not configured)' when gate fields are None; got:\n{testing_section}"
        );

        // Gate 3 (Spec audit).
        let spec_start = output.find("**Spec audit**").expect("Spec audit present");
        let spec_end = output[spec_start..]
            .find("**Doc audit**")
            .map(|p| spec_start + p)
            .expect("Doc audit follows Spec audit");
        let spec_section = &output[spec_start..spec_end];
        assert!(
            spec_section.contains("(not configured)"),
            "Spec audit gate should render '(not configured)' when None; got:\n{spec_section}"
        );

        // Gate 4 (Doc audit).
        let doc_start = output.find("**Doc audit**").expect("Doc audit present");
        let doc_end = output[doc_start..]
            .find("**Security audit**")
            .map(|p| doc_start + p)
            .expect("Security audit follows Doc audit");
        let doc_section = &output[doc_start..doc_end];
        assert!(
            doc_section.contains("(not configured)"),
            "Doc audit gate should render '(not configured)' when None; got:\n{doc_section}"
        );

        // Gate 5 (Security audit).
        let security_start = output
            .find("**Security audit**")
            .expect("Security audit present");
        let security_end = output[security_start..]
            .find("**Verify or feedback**")
            .map(|p| security_start + p)
            .expect("Verify-or-feedback follows Security audit");
        let security_section = &output[security_start..security_end];
        assert!(
            security_section.contains("(not configured)"),
            "Security audit gate should render '(not configured)' when None; got:\n{security_section}"
        );
    }

    /// Pre-render audit: the embedded supervisor template must not hardcode
    /// `just check`, `cargo test`, `cargo clippy`, `cargo audit`,
    /// `cargo fmt --check`, `mdbook build`, or `openspec validate` in its
    /// gate prose. Matches inside fenced code blocks demonstrating example
    /// config values (e.g. `# test_command = "just check"`) are tolerated:
    /// the audit windows are the §4-§7 gate-prose paragraphs only.
    #[test]
    fn supervisor_template_gate_prose_has_no_hardcoded_git_paw_commands() {
        let tmpl = resolve("supervisor").expect("supervisor skill resolves");
        let content = &tmpl.content;
        let start = content
            .find("Steps 4-7 below are the **five first-class verification gates**")
            .expect("five-gate intro present");
        let end = content
            .find("### Spec Audit Procedure")
            .expect("Spec Audit Procedure heading present");
        let gate_prose = &content[start..end];
        for needle in [
            "just check",
            "cargo test",
            "cargo clippy",
            "cargo audit",
            "cargo fmt --check",
            "mdbook build",
        ] {
            // The §7 agent.feedback example body intentionally contains the
            // string `cargo test failed: ...` as an illustration of error
            // reporting. The example may be written either with brackets
            // (`[testing] cargo test failed`, the historical wire-format
            // shape) or via the helper invocation
            // (`feedback-gate ... testing "cargo test failed`, the v0.5.0
            // helper-call shape). We allow both.
            if needle == "cargo test"
                && (gate_prose.contains("[testing] cargo test failed")
                    || gate_prose.contains("testing \"cargo test failed"))
            {
                let cleaned = gate_prose.replace("cargo test failed", "<failure>");
                assert!(
                    !cleaned.contains("cargo test"),
                    "gate prose must not contain hardcoded 'cargo test' outside the §7 example"
                );
                continue;
            }
            assert!(
                !gate_prose.contains(needle),
                "gate prose must not contain hardcoded '{needle}'; replace with the matching placeholder"
            );
        }
    }

    #[test]
    fn render_change_id_placeholder_passes_through() {
        let tmpl = SkillTemplate {
            name: "supervisor".into(),
            content: "Run {{SPEC_VALIDATE_COMMAND}}.".into(),
            source: Source::Embedded,
            format: SkillFormat::Standardized,
            metadata: None,
            resource_paths: None,
        };
        let gates = GateCommands {
            spec_validate_command: Some("openspec validate {{CHANGE_ID}} --strict"),
            ..Default::default()
        };
        let output = render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &gates,
        );
        assert!(
            output.contains("Run openspec validate {{CHANGE_ID}} --strict."),
            "outer placeholder substituted but inner {{CHANGE_ID}} preserved; got: {output}"
        );
        assert!(
            output.contains("{{CHANGE_ID}}"),
            "{{CHANGE_ID}} must survive verbatim (not substituted at render time); got: {output}"
        );
    }

    // Invalid standardized skill frontmatter returns validation error
    #[test]
    fn invalid_standardized_skill_frontmatter_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let project_dir = dir.path().join("my-project");
        std::fs::create_dir_all(&project_dir).unwrap();

        let skill_dir = project_dir
            .join(".agents")
            .join("skills")
            .join("invalid-skill");
        std::fs::create_dir_all(&skill_dir).unwrap();

        // Missing required 'description' field
        let skill_md_content = "---\nname: invalid-skill\n---\n\nContent here.";
        std::fs::write(skill_dir.join("SKILL.md"), skill_md_content).unwrap();

        // Change to project directory
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&project_dir).unwrap();

        let result = resolve("invalid-skill");
        assert!(matches!(result, Err(SkillError::ValidationError { .. })));

        // Restore original directory
        std::env::set_current_dir(original_dir).unwrap();
    }

    // 9.17: SkillTemplate is cloneable
    #[test]
    fn skill_template_is_cloneable() {
        let tmpl = resolve("coordination").unwrap();
        let cloned = tmpl.clone();
        assert_eq!(tmpl.name, cloned.name);
        assert_eq!(tmpl.content, cloned.content);
        assert_eq!(tmpl.source, cloned.source);
    }

    // Boot block function tests
    #[test]
    fn boot_block_contains_all_four_essential_events() {
        let block = build_boot_block("feat/errors", "http://localhost:9119");
        assert!(
            block.contains("### 1. REGISTER"),
            "Missing REGISTER section"
        );
        assert!(block.contains("### 2. DONE"), "Missing DONE section");
        assert!(block.contains("### 3. BLOCKED"), "Missing BLOCKED section");
        assert!(
            block.contains("### 4. QUESTION"),
            "Missing QUESTION section"
        );
    }

    #[test]
    fn boot_block_substitutes_branch_id_placeholder() {
        let block = build_boot_block("Feature/HTTP_Broker", "http://localhost:9119");
        assert!(
            block.contains("feature-http_broker"),
            "Branch ID not properly slugified"
        );
        assert!(
            !block.contains("{{BRANCH_ID}}"),
            "BRANCH_ID placeholder not substituted"
        );
    }

    #[test]
    fn boot_block_substitutes_broker_url_placeholder() {
        let block = build_boot_block("feat/x", "http://127.0.0.1:9119");
        assert!(
            block.contains("http://127.0.0.1:9119/publish"),
            "Broker URL not substituted"
        );
        assert!(
            !block.contains("{{GIT_PAW_BROKER_URL}}"),
            "GIT_PAW_BROKER_URL placeholder not substituted"
        );
    }

    #[test]
    fn boot_block_contains_paste_handling_instructions() {
        let block = build_boot_block("feat/x", "http://localhost:9119");
        assert!(
            block.contains("PASTE HANDLING"),
            "Missing paste handling section"
        );
        assert!(
            block.contains("additional Enter key"),
            "Missing Enter key instruction"
        );
        assert!(
            block.contains("[Pasted text #N]"),
            "Missing paste text reference"
        );
    }

    #[test]
    fn boot_block_question_section_emphasizes_waiting() {
        let block = build_boot_block("feat/x", "http://localhost:9119");
        assert!(
            block.contains("DO NOT CONTINUE UNTIL YOU RECEIVE AN ANSWER!"),
            "Missing wait emphasis"
        );
        assert!(
            block.contains("WAIT for the answer before continuing"),
            "Missing wait instruction"
        );
    }

    #[test]
    fn boot_block_is_deterministic() {
        let a = build_boot_block("feat/x", "http://localhost:9119");
        let b = build_boot_block("feat/x", "http://localhost:9119");
        assert_eq!(a, b, "Boot block generation should be deterministic");
    }

    #[test]
    fn boot_block_handles_complex_branch_names() {
        let block = build_boot_block("fix/topological-cycle-fallback", "http://localhost:9119");
        assert!(
            block.contains("fix-topological-cycle-fallback"),
            "Complex branch name not properly slugified"
        );
    }

    #[test]
    fn boot_block_contains_pre_expanded_curl_commands() {
        let block = build_boot_block("feat/test", "http://127.0.0.1:9119");

        // Check that all curl commands have the actual URL substituted
        assert!(
            block.contains("curl -s -X POST http://127.0.0.1:9119/publish"),
            "Curl commands not pre-expanded"
        );

        // Check that all curl commands have the actual branch ID substituted
        assert!(
            block.contains("\"agent_id\":\"feat-test\""),
            "Agent ID not substituted in curl commands"
        );
    }

    fn done_section_body(block: &str) -> String {
        let start = block
            .find("### 2. DONE")
            .expect("rendered boot block should contain the DONE section heading");
        let end = block
            .find("### 3. BLOCKED")
            .expect("rendered boot block should contain the BLOCKED section heading");
        block[start..end].to_string()
    }

    #[test]
    fn boot_block_done_section_leads_with_commit_instruction() {
        let block = build_boot_block("feat/test", "http://127.0.0.1:9119");
        let done_body = done_section_body(&block);

        let commit_idx = done_body
            .find("commit your work")
            .or_else(|| done_body.find("git commit"))
            .expect("DONE section should lead with a commit-first instruction");

        let manual_done_idx = done_body
            .find("\"status\":\"done\"")
            .expect("DONE section should still contain the manual done curl as a fallback");

        assert!(
            commit_idx < manual_done_idx,
            "commit-first instruction (byte {commit_idx}) must appear before the manual done curl (byte {manual_done_idx})"
        );
    }

    #[test]
    fn boot_block_done_section_names_committed_status_published_by_hook() {
        let block = build_boot_block("feat/test", "http://127.0.0.1:9119");
        let done_body = done_section_body(&block);

        assert!(
            done_body.contains("status: \"committed\"")
                || done_body.contains("status:\"committed\""),
            "DONE section should name the `status: \"committed\"` event published by the hook"
        );
        assert!(
            done_body.contains("post-commit hook"),
            "DONE section should mention the post-commit hook that publishes on the agent's behalf"
        );
    }

    #[test]
    fn boot_block_done_section_scopes_manual_done_to_code_less_tasks() {
        let block = build_boot_block("feat/test", "http://127.0.0.1:9119");
        let done_body = done_section_body(&block);

        let hits = ["docs-only", "planning", "exploration"]
            .iter()
            .filter(|needle| done_body.contains(*needle))
            .count();
        assert!(
            hits >= 2,
            "DONE section should enumerate at least two code-less task examples \
             (docs-only / planning / exploration); only {hits} present"
        );
    }

    #[test]
    fn boot_block_done_section_warns_against_manual_done_with_uncommitted_changes() {
        let block = build_boot_block("feat/test", "http://127.0.0.1:9119");
        let done_body = done_section_body(&block);

        assert!(
            done_body.contains("uncommitted"),
            "DONE section should warn about uncommitted changes"
        );
        assert!(
            done_body.contains("manual `done`") || done_body.contains("manual done"),
            "DONE section warning should reference manual `done`"
        );
        assert!(
            done_body.contains("**WARNING") || done_body.contains("**DO NOT"),
            "DONE section warning should be emphasised with bold markers (**...**)"
        );
    }

    #[test]
    fn boot_block_done_section_retains_manual_done_curl() {
        let block = build_boot_block("feat/test", "http://127.0.0.1:9119");
        let done_body = done_section_body(&block);

        assert!(
            done_body.contains("curl -s -X POST http://127.0.0.1:9119/publish"),
            "DONE section should retain the pre-expanded broker curl"
        );
        assert!(
            done_body.contains("\"type\":\"agent.artifact\""),
            "DONE section curl should publish an agent.artifact event"
        );
        assert!(
            done_body.contains("\"status\":\"done\""),
            "DONE section curl should still publish status: done as the manual fallback"
        );
        assert!(
            done_body.contains("\"exports\":[]"),
            "DONE section curl should retain the exports field"
        );
        assert!(
            done_body.contains("\"modified_files\":[]"),
            "DONE section curl should retain the modified_files field"
        );
    }

    // -----------------------------------------------------------------
    // conflict-detection skill content (v0.5.0)
    // -----------------------------------------------------------------

    #[test]
    fn supervisor_skill_contains_conflict_detector_tag() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            tmpl.content.contains("[conflict-detector]"),
            "supervisor skill should reference the [conflict-detector] tag"
        );
    }

    #[test]
    fn supervisor_skill_documents_broker_side_detection() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("auto-detect") || lowered.contains("auto-emit"),
            "skill should mention auto-detection/auto-emission by the broker"
        );
        assert!(
            lowered.contains("forward conflict"),
            "skill should mention forward conflict"
        );
        assert!(
            lowered.contains("in-flight conflict"),
            "skill should mention in-flight conflict"
        );
        assert!(
            lowered.contains("ownership violation"),
            "skill should mention ownership violation"
        );
    }

    #[test]
    fn supervisor_skill_removes_v04_manual_conflict_detection() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            !tmpl
                .content
                .contains("Compare the `modified_files` arrays from every `agent.artifact` event"),
            "supervisor skill should no longer contain the v0.4 manual conflict-comparison instructions"
        );
    }

    #[test]
    fn supervisor_skill_mentions_agent_intent() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(tmpl.content.contains("agent.intent"));
        assert!(
            tmpl.content.contains("Watch peer intents")
                || tmpl
                    .content
                    .contains("Watch peer intents and broker-side conflict detection"),
            "skill should contain a 'Watch peer intents' heading"
        );
    }

    #[test]
    fn supervisor_skill_focuses_on_question_escalations() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        // The supervisor agent's role on detector output is to react to
        // agent.question escalations and follow up on repeat offenders.
        assert!(
            lowered.contains("agent.question")
                && (lowered.contains("escalation") || lowered.contains("escalat")),
            "skill should direct the supervisor agent at agent.question escalations"
        );
        assert!(
            lowered.contains("do not") && lowered.contains("manually"),
            "skill should tell the supervisor not to duplicate by manual comparison"
        );
    }

    // --- Spec Kit consolidated worktree section (`spec-kit-format` change) ---

    #[test]
    fn embedded_coordination_mentions_spec_kit_consolidated_worktrees() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("Spec Kit")
                && (tmpl.content.contains("consolidated") || tmpl.content.contains("phase/")),
            "coordination skill should mention Spec Kit consolidated worktrees"
        );
    }

    #[test]
    fn embedded_coordination_instructs_sequential_work_and_writeback() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("sequential") || tmpl.content.contains("Sequential"),
            "should instruct sequential execution"
        );
        assert!(
            tmpl.content.contains("`- [x]`") || tmpl.content.contains("- [x]"),
            "should mention - [x] writeback"
        );
        assert!(
            tmpl.content.contains("tasks.md"),
            "should reference tasks.md as writeback target"
        );
    }

    #[test]
    fn embedded_coordination_states_agent_done_timing_for_consolidated() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("agent.done"),
            "should mention agent.done"
        );
        let lower = tmpl.content.to_lowercase();
        assert!(
            lower.contains("every task")
                || lower.contains("all listed tasks")
                || lower.contains("all tasks"),
            "should tie agent.done to completion of all listed tasks"
        );
    }

    #[test]
    fn embedded_coordination_clarifies_p_worktrees_follow_standard_pattern() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("[P]") || tmpl.content.contains("task/"),
            "should distinguish [P] / task/ worktrees from consolidated ones"
        );
        assert!(
            tmpl.content.contains("standard"),
            "should reference the standard before/while-editing pattern"
        );
    }

    // -----------------------------------------------------------------------
    // supervisor-as-pane (v0.5.0) — interactive user input + merge orchestration
    // -----------------------------------------------------------------------

    /// section heading.
    #[test]
    fn supervisor_skill_has_user_input_section() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            tmpl.content.contains("When the user types in your pane"),
            "supervisor skill should include the 'When the user types in your pane' section"
        );
    }

    /// 8.2 — user-input section maps directives to `agent.feedback`.
    #[test]
    fn supervisor_skill_user_input_uses_agent_feedback_for_directives() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("When the user types in your pane")
            .expect("user-input section heading present");
        let window = &tmpl.content[start..];
        assert!(
            window.contains("agent.feedback"),
            "user-input directives section should reference agent.feedback"
        );
    }

    /// 8.3 — user-input section maps judgment-call asks to `agent.question`.
    #[test]
    fn supervisor_skill_user_input_uses_agent_question_for_judgment_calls() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("When the user types in your pane")
            .expect("user-input section heading present");
        let window = &tmpl.content[start..];
        assert!(
            window.contains("agent.question"),
            "user-input judgment-call section should reference agent.question"
        );
    }

    /// 8.4 — user-input section states the autonomous loop continues.
    #[test]
    fn supervisor_skill_user_input_states_loop_continues() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("When the user types in your pane")
            .expect("user-input section heading present");
        let window = &tmpl.content[start..];
        assert!(
            window.to_lowercase().contains("autonomous"),
            "user-input section should state the autonomous loop continues alongside user input"
        );
    }

    /// 8.5 — supervisor skill contains the "Merge orchestration" section.
    #[test]
    fn supervisor_skill_has_merge_orchestration_section() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            tmpl.content.contains("Merge orchestration"),
            "supervisor skill should include the 'Merge orchestration' section"
        );
    }

    /// 8.6 — merge orchestration uses `git merge --ff-only`.
    #[test]
    fn supervisor_skill_merge_uses_ff_only() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("Merge orchestration")
            .expect("merge orchestration section present");
        let window = &tmpl.content[start..];
        assert!(
            window.contains("git merge --ff-only"),
            "merge orchestration should specify git merge --ff-only"
        );
    }

    /// revert.
    #[test]
    fn supervisor_skill_merge_reverts_via_reset_hard() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("Merge orchestration")
            .expect("merge orchestration section present");
        let window = &tmpl.content[start..];
        assert!(
            window.contains("git reset --hard"),
            "merge orchestration should describe regression revert via git reset --hard"
        );
    }

    /// `agent.question`.
    #[test]
    fn supervisor_skill_merge_cycle_uses_agent_question() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("Merge orchestration")
            .expect("merge orchestration section present");
        let window = &tmpl.content[start..];
        assert!(
            window.contains("agent.question") && window.to_lowercase().contains("cycle"),
            "merge orchestration cycle handling should publish agent.question"
        );
    }

    /// 8.9 — merge orchestration ends with a final `agent.status` summary.
    #[test]
    fn supervisor_skill_merge_publishes_final_status_summary() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("Merge orchestration")
            .expect("merge orchestration section present");
        let window = &tmpl.content[start..];
        assert!(
            window.contains("agent.status") && window.to_lowercase().contains("summary"),
            "merge orchestration should end with a final agent.status summary"
        );
    }

    // === coordination-skill-followups: drift 34, 37, 54, 55, 56, 57 ===

    /// drift 54 — coordination skill names both `agent_id` and `slugify_branch` in a
    /// references/terminology section.
    #[test]
    fn coordination_skill_documents_slugify_terminology() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("agent_id"),
            "coordination skill should mention the agent_id identifier form"
        );
        assert!(
            tmpl.content.contains("slugify_branch"),
            "coordination skill should name slugify_branch as the canonical conversion"
        );
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("references & terminology")
                || lowered.contains("references and terminology")
                || lowered.contains("terminology"),
            "coordination skill should contain a references/terminology heading"
        );
    }

    /// drift 57 — coordination skill documents stash-hygiene rules.
    #[test]
    fn coordination_skill_documents_stash_hygiene() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("git stash list"),
            "stash-hygiene section should reference `git stash list`"
        );
        assert!(
            tmpl.content.contains("git stash show -p"),
            "stash-hygiene section should reference `git stash show -p`"
        );
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("stash hygiene") || lowered.contains("stash safety"),
            "coordination skill should contain a stash-hygiene heading"
        );
        assert!(
            lowered.contains("pop only") || lowered.contains("only pop"),
            "coordination skill should instruct agents to pop only their own stashes"
        );
    }

    /// drift 55 — supervisor skill documents publishing agent.intent for main-side
    /// work with `agent_id` = "supervisor".
    #[test]
    fn supervisor_skill_documents_main_side_intent() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("supervisor publishes agent.intent")
                || lowered.contains("publish intent")
                || lowered.contains("main-side work"),
            "supervisor skill should contain a heading naming supervisor-side intent publishing"
        );
        let start = tmpl
            .content
            .find("Supervisor publishes agent.intent")
            .expect("supervisor-publishes-intent heading present");
        let window = &tmpl.content[start..];
        assert!(
            window.contains("agent.intent"),
            "section should mention agent.intent"
        );
        assert!(
            window.contains("\"supervisor\""),
            "section should show agent_id = \"supervisor\" in the example"
        );
        assert!(
            window.contains("\"files\"")
                && window.contains("\"summary\"")
                && window.contains("\"valid_for_seconds\""),
            "section should include a curl example with files, summary, valid_for_seconds"
        );
    }

    /// drift 34 — supervisor skill instructs `tmux send-keys` alongside
    /// `agent.feedback` answers, with the "agents do not poll" rationale.
    #[test]
    fn supervisor_skill_documents_tmux_send_keys_alongside_feedback() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("Send the answer to the agent pane too")
            .expect("drift-34 subsection should be present");
        let next_heading = tmpl.content[start + 1..]
            .find("\n### ")
            .map_or(tmpl.content.len(), |off| start + 1 + off);
        let section = &tmpl.content[start..next_heading];
        assert!(
            section.contains("tmux send-keys"),
            "section should contain `tmux send-keys`"
        );
        assert!(
            section.contains("agent.feedback"),
            "section should reference agent.feedback in the same section"
        );
        let lowered_section = section.to_lowercase();
        assert!(
            lowered_section.contains("do not poll") || lowered_section.contains("don't poll"),
            "section should state the rationale (agents do not poll their inbox)"
        );
    }

    /// drift 37 — coordination skill documents the working-heartbeat cadence and
    /// the filesystem-watcher rationale.
    #[test]
    fn coordination_skill_documents_working_heartbeat() {
        let tmpl = resolve("coordination").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("working heartbeat") || lowered.contains("heartbeat"),
            "coordination skill should contain a working-heartbeat heading"
        );
        assert!(
            tmpl.content.contains("every 5 tool uses"),
            "coordination skill should state the cadence as 'every 5 tool uses'"
        );
        assert!(
            tmpl.content.contains("agent.status"),
            "heartbeat reuses the agent.status shape — substring should be present"
        );
        let start = tmpl
            .content
            .find("Working heartbeat")
            .expect("Working heartbeat heading present");
        let next_heading = tmpl.content[start + 1..]
            .find("\n### ")
            .map_or(tmpl.content.len(), |off| start + 1 + off);
        let section = &tmpl.content[start..next_heading].to_lowercase();
        assert!(
            section.contains("filesystem watcher") || section.contains("watcher"),
            "heartbeat section should explain why the filesystem watcher is insufficient"
        );
    }

    /// drift 56 — supervisor skill documents the accept-edits `modified_files` audit
    /// step with explicit non-silent-approval guidance.
    #[test]
    fn supervisor_skill_documents_accept_edits_audit() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("accept-edits commits") || lowered.contains("accept edits"),
            "supervisor skill should contain an accept-edits audit heading"
        );
        assert!(
            tmpl.content.contains("modified_files"),
            "audit section should reference the modified_files payload field"
        );
        let start = tmpl
            .content
            .find("Verify accept-edits commits before merge")
            .expect("accept-edits audit heading present");
        let next_heading = tmpl.content[start + 1..]
            .find("\n### ")
            .map_or(tmpl.content.len(), |off| start + 1 + off);
        let section_lower = tmpl.content[start..next_heading].to_lowercase();
        assert!(
            section_lower.contains("out-of-scope"),
            "audit section should call out 'out-of-scope' edits"
        );
        assert!(
            section_lower.contains("shall not be silently")
                || section_lower.contains("not be silently auto-approved")
                || section_lower.contains("silently auto-approved"),
            "audit section should forbid silent auto-approval"
        );
    }

    /// drift 54 (optional 3.5) — coordination skill describes the slugify rule's
    /// effect: lowercase, non-allowed-char replacement, and `agent` fallback.
    #[test]
    fn coordination_skill_describes_slugify_rule() {
        let tmpl = resolve("coordination").unwrap();
        let start = tmpl
            .content
            .find("slugify_branch")
            .expect("slugify_branch should be named in the references section");
        let next_heading = tmpl.content[start + 1..]
            .find("\n### ")
            .map_or(tmpl.content.len(), |off| start + 1 + off);
        let section_lower = tmpl.content[start..next_heading].to_lowercase();
        assert!(
            section_lower.contains("lowercase"),
            "slugify rule should mention lowercase step"
        );
        assert!(
            tmpl.content[start..next_heading].contains("[a-z0-9_]"),
            "slugify rule should describe the allowed char class"
        );
        assert!(
            (section_lower.contains("fallback") || section_lower.contains("fall back"))
                && section_lower.contains("agent"),
            "slugify rule should describe the empty-fallback to `agent`"
        );
    }

    // --- test-coverage-v0-5-0 -------------------------------------------------
    //
    // The following tests close per-scenario coverage gaps from the v0.5.0
    // archived spec set. See `openspec/changes/test-coverage-v0-5-0/tasks.md`.

    // Renders the supervisor skill with a representative set of substitutions.
    // Tests assert against the rendered output so any post-render
    // transformation regressions are caught.
    fn rendered_supervisor() -> String {
        let tmpl = resolve("supervisor").expect("supervisor skill resolves");
        render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        )
    }

    fn rendered_coordination() -> String {
        let tmpl = resolve("coordination").expect("coordination skill resolves");
        render(
            &tmpl,
            "feat/x",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands::default(),
        )
    }

    // Maps to scenario `Supervisor skill — lenient indicator framing` from
    // prompt-submit-fix. (task 3.3)
    #[test]
    fn supervisor_skill_paste_buffer_framing_is_lenient() {
        let content = rendered_supervisor();
        let lowered = content.to_lowercase();
        assert!(
            lowered.contains("even if"),
            "supervisor skill should frame recovery as attempted even when indicator absent; got:\n{content}"
        );
        assert!(
            lowered.contains("judgment"),
            "supervisor skill should describe applying judgment; got:\n{content}"
        );
        assert!(
            lowered.contains("long buffered text"),
            "supervisor skill should mention the long-buffered-text heuristic; got:\n{content}"
        );
    }

    // Maps to scenario `Coordination skill rejects pairwise over-coordination
    // patterns` from forward-coordination. (task 4.1)
    #[test]
    fn coordination_skill_rejects_pairwise_overcoordination() {
        let content = rendered_coordination();
        assert!(
            content.contains("pairwise"),
            "coordination skill should name `pairwise` under a MUST-NOT clause; got:\n{content}"
        );
        let lowered = content.to_lowercase();
        assert!(
            lowered.contains("explicit go-ahead"),
            "coordination skill should reject waiting for an explicit go-ahead; got:\n{content}"
        );
        assert!(
            lowered.contains("broker silence") || lowered.contains("block on broker silence"),
            "coordination skill should reject blocking on broker silence; got:\n{content}"
        );
    }

    // Maps to scenario `Verification/feedback wording separability` from
    // forward-coordination. (task 4.3)
    //
    // The two message types must be separately reachable — i.e. each lives in
    // its own bullet or heading. We assert their distinct anchor lines:
    // `- **agent.verified**` and `- **agent.feedback**`.
    #[test]
    fn coordination_skill_verified_and_feedback_substrings_independent() {
        let content = rendered_coordination();
        let verified_anchor = "- **`agent.verified`**";
        let feedback_anchor = "- **`agent.feedback`**";
        assert!(
            content.contains(verified_anchor),
            "coordination skill should anchor `agent.verified` in its own bullet; got:\n{content}"
        );
        assert!(
            content.contains(feedback_anchor),
            "coordination skill should anchor `agent.feedback` in its own bullet; got:\n{content}"
        );
        // The two anchors must not be on the same line.
        let v = content.find(verified_anchor).unwrap();
        let f = content.find(feedback_anchor).unwrap();
        let between = if v < f {
            &content[v..f]
        } else {
            &content[f..v]
        };
        assert!(
            between.contains('\n'),
            "the verified and feedback bullets must be on separate lines; got slice:\n{between}"
        );
    }

    // Maps to scenario `Supervisor skill specifies the ordering` from
    // governance-context. (task 10.1)
    //
    // Ordering invariant: Spec Audit Procedure < Governance verification <
    // the publish step that emits `agent.verified`.
    #[test]
    fn supervisor_skill_governance_after_spec_audit_before_verified() {
        let content = rendered_supervisor();
        let spec_audit = content
            .find("Spec Audit Procedure")
            .expect("Spec Audit Procedure heading present in supervisor skill");
        let governance = content
            .find("Governance verification")
            .expect("Governance verification heading present in supervisor skill");
        // The closest publish step emitting `agent.verified` after the
        // governance heading is the next occurrence of `agent.verified`.
        let verified_after = content[governance..]
            .find("agent.verified")
            .map(|o| governance + o)
            .expect("agent.verified mention after Governance verification");

        assert!(
            spec_audit < governance,
            "Spec Audit Procedure should appear before Governance verification \
             (spec_audit={spec_audit}, governance={governance})"
        );
        assert!(
            governance < verified_after,
            "Governance verification should appear before the next agent.verified \
             publish step (governance={governance}, verified_after={verified_after})"
        );
    }

    // Maps to scenario `Coordination skill states agent.done timing for
    // consolidated worktrees` from spec-kit-format. (task 11.6)
    #[test]
    fn coordination_skill_consolidated_agent_done_timing() {
        let content = rendered_coordination();
        let start = content
            .find("consolidated worktree")
            .or_else(|| content.find("Consolidated worktree"))
            .expect("coordination skill should have a consolidated-worktree section");
        let section = &content[start..];
        let lowered = section.to_lowercase();
        assert!(
            lowered.contains("agent.done") || lowered.contains("agent.artifact"),
            "consolidated-worktree section should describe agent.done timing; got:\n{section}"
        );
        assert!(
            section.contains("- [x]"),
            "consolidated-worktree section should require every task to show - [x]; got:\n{section}"
        );
        assert!(
            lowered.contains("every task") || lowered.contains("every"),
            "consolidated-worktree section should make the rule cover every task; got:\n{section}"
        );
    }

    /// drift 55 (optional 3.6) — supervisor-publishes-intent section cross-references
    /// the agent-side `Before you start editing` flow in `coordination.md`.
    #[test]
    fn supervisor_skill_cross_references_agent_intent_flow() {
        let tmpl = resolve("supervisor").unwrap();
        let start = tmpl
            .content
            .find("Supervisor publishes agent.intent")
            .expect("supervisor-publishes-intent heading present");
        let next_heading = tmpl.content[start + 1..]
            .find("\n### ")
            .map_or(tmpl.content.len(), |off| start + 1 + off);
        let section = &tmpl.content[start..next_heading];
        assert!(
            section.contains("Before you start editing"),
            "supervisor-publishes-intent section should cross-reference the agent-side \
             `Before you start editing` heading"
        );
        assert!(
            section.contains("coordination.md"),
            "cross-reference should name the coordination skill file"
        );
    }

    // ---------------------------------------------------------------------------
    // supervisor-as-pane-followups: skill-content tests
    // (tasks 8.3, 8.4, 8a.4-8a.7, 8b.7-8b.12)
    // ---------------------------------------------------------------------------

    fn render_supervisor() -> String {
        let tmpl = resolve("supervisor").expect("resolve supervisor template");
        render(
            &tmpl,
            "supervisor",
            "http://127.0.0.1:9119",
            "git-paw",
            &GateCommands {
                test_command: Some("just check"),
                ..Default::default()
            },
        )
    }

    /// 8.3 — resolved supervisor skill contains a curl publishing an
    /// `agent.status` for `agent_id = "supervisor"` AND including a `cli`
    /// field in the payload JSON.
    #[test]
    fn supervisor_skill_self_register_curl_includes_cli_field() {
        let rendered = render_supervisor();
        let start = rendered
            .find("Bootstrap")
            .expect("Bootstrap section heading present");
        let next = rendered[start..]
            .find("### Poll session status and messages")
            .map_or(rendered.len(), |p| start + p);
        let section = &rendered[start..next];
        assert!(
            section.contains("agent.status"),
            "bootstrap section must publish agent.status; got:\n{section}"
        );
        assert!(
            section.contains("\"agent_id\":\"supervisor\""),
            "bootstrap curl must use agent_id=\"supervisor\"; got:\n{section}"
        );
        assert!(
            section.contains("\"cli\""),
            "bootstrap payload must include a cli field; got:\n{section}"
        );
    }

    /// 8.4 — bootstrap section names this as the FIRST action after
    /// reading the skill / AGENTS.md, not a "you may" suggestion.
    #[test]
    fn supervisor_skill_self_register_is_first_action() {
        let rendered = render_supervisor();
        let pos_bootstrap = rendered
            .find("Bootstrap")
            .expect("Bootstrap heading present");
        let section_end = rendered[pos_bootstrap..]
            .find("### Poll session status and messages")
            .map_or(rendered.len(), |p| pos_bootstrap + p);
        let section = &rendered[pos_bootstrap..section_end];
        let lower = section.to_lowercase();
        assert!(
            lower.contains("first action") || lower.contains("very first"),
            "bootstrap section must state this is the agent's first action; got:\n{section}"
        );
    }

    /// 8a.4 — Watch section explicitly mentions per-iteration sweeping.
    #[test]
    fn supervisor_skill_watch_mentions_per_iteration_sweep() {
        let rendered = render_supervisor();
        let start = rendered
            .find("**Watch**")
            .expect("Watch step heading present");
        let end = rendered[start..]
            .find("Stall detection")
            .map_or(rendered.len(), |p| start + p);
        let section = &rendered[start..end];
        let lower = section.to_lowercase();
        assert!(
            lower.contains("every iteration")
                || lower.contains("every monitoring")
                || lower.contains("each monitoring")
                || lower.contains("each iteration"),
            "Watch section must mention per-iteration sweeping; got:\n{section}"
        );
    }

    /// 8a.5 — Rules section bullet mentions absorbing routine approvals
    /// AND at least three routine command families.
    #[test]
    fn supervisor_skill_rules_bullet_mentions_routine_absorption() {
        let rendered = render_supervisor();
        let start = rendered.find("### Rules").expect("Rules section present");
        let end = rendered[start..]
            .find("### Auto-approve permission prompts")
            .map_or(rendered.len(), |p| start + p);
        let section = &rendered[start..end];
        let lower = section.to_lowercase();
        assert!(
            lower.contains("absorb routine approval") || lower.contains("rubber-stamp"),
            "Rules must include the routine-approval absorption framing; got:\n{section}"
        );
        let mut family_hits = 0;
        for family in ["cargo", "git commit", "mdbook", "git stash", "git restore"] {
            if section.contains(family) {
                family_hits += 1;
            }
        }
        assert!(
            family_hits >= 3,
            "Rules bullet must enumerate at least 3 routine families; only {family_hits} found in:\n{section}",
        );
    }

    /// 8a.6 — Rules bullet also enumerates at least two non-routine
    /// escalation cases.
    #[test]
    fn supervisor_skill_rules_bullet_enumerates_escalation_cases() {
        let rendered = render_supervisor();
        let start = rendered.find("### Rules").expect("Rules section present");
        let end = rendered[start..]
            .find("### Auto-approve permission prompts")
            .map_or(rendered.len(), |p| start + p);
        let section = &rendered[start..end];
        let lower = section.to_lowercase();
        let mut hits = 0;
        for case in [
            "cross-agent conflict",
            "destructive",
            "scope",
            "spec decisions",
            "novel",
        ] {
            if lower.contains(case) {
                hits += 1;
            }
        }
        assert!(
            hits >= 2,
            "Rules bullet must enumerate at least 2 escalation cases; only {hits} found in:\n{section}",
        );
    }

    /// 8a.7 — Watch section contains the phrase "every iteration" or
    /// "every monitoring" (verbatim).
    #[test]
    fn supervisor_skill_contains_every_iteration_phrase() {
        let rendered = render_supervisor();
        let lower = rendered.to_lowercase();
        assert!(
            lower.contains("every iteration") || lower.contains("every monitoring"),
            "skill must contain 'every iteration' or 'every monitoring' phrasing somewhere",
        );
    }

    /// 8b.7 — supervisor skill contains the five gate names in order.
    #[test]
    fn supervisor_skill_enumerates_five_gates_in_order() {
        let rendered = render_supervisor();
        let pos = |needle: &str| {
            rendered
                .find(needle)
                .unwrap_or_else(|| panic!("gate '{needle}' not found in supervisor skill"))
        };
        let pos_testing = pos("**Testing**");
        let pos_regression = pos("**Regression analysis**");
        let pos_spec = pos("**Spec audit**");
        let pos_doc = pos("**Doc audit**");
        let pos_security = pos("**Security audit**");
        assert!(
            pos_testing < pos_regression
                && pos_regression < pos_spec
                && pos_spec < pos_doc
                && pos_doc < pos_security,
            "five gates must appear in order Testing < Regression < Spec < Doc < Security; \
             got positions Testing={pos_testing} Regression={pos_regression} \
             Spec={pos_spec} Doc={pos_doc} Security={pos_security}",
        );
    }

    /// 8b.8 — §7 Verify-or-feedback's `agent.verified` example body
    /// mentions all five gate names.
    #[test]
    fn supervisor_skill_verified_message_enumerates_five_gates() {
        let rendered = render_supervisor();
        // Anchor on §7 specifically — the supervisor skill has an earlier
        // `agent.verified` example near the top of the file that pre-dates
        // the five-gate restructure.
        let verify_start = rendered
            .find("**Verify or feedback**")
            .expect("Verify or feedback step present");
        let window = &rendered[verify_start..];
        let lower = window.to_lowercase();
        for needle in [
            "testing",
            "regression",
            "spec audit",
            "doc audit",
            "security audit",
        ] {
            assert!(
                lower.contains(needle),
                "§7 Verify-or-feedback must mention '{needle}'; got window:\n{window}",
            );
        }
    }

    /// 8b.9 — §7's `agent.feedback` examples mention the gate-name
    /// convention with at least three of the five gates shown. The
    /// supervisor skill now wraps feedback through
    /// `.git-paw/scripts/sweep.sh feedback-gate <agent> <gate> <msg>`,
    /// so a gate name passed as the second argument satisfies the
    /// convention equivalently to a bracketed `[gate]` prefix.
    #[test]
    fn supervisor_skill_feedback_example_uses_gate_name_prefixes() {
        let rendered = render_supervisor();
        let verify_start = rendered
            .find("**Verify or feedback**")
            .expect("Verify or feedback step present");
        // Cap the window at the next top-level section so we don't bleed
        // into "Spec Audit Procedure".
        let end = rendered[verify_start..]
            .find("\n### ")
            .map_or(rendered.len(), |p| verify_start + p);
        let window = &rendered[verify_start..end];
        let mut hits = 0;
        for (bracketed, helper_arg) in [
            ("[testing]", " testing "),
            ("[regression]", " regression "),
            ("[spec audit]", " \"spec audit\" "),
            ("[doc audit]", " \"doc audit\" "),
            ("[security audit]", " \"security audit\" "),
        ] {
            if window.contains(bracketed)
                || window.contains(&format!("feedback-gate __FILL_IN_AGENT_ID__{helper_arg}"))
            {
                hits += 1;
            }
        }
        assert!(
            hits >= 3,
            "§7 agent.feedback example must show at least 3 gates (bracketed or helper-arg); \
             only {hits} found in:\n{window}",
        );
    }

    /// 8b.10 — Doc audit gate enumerates at least 4 of 5 doc surfaces.
    #[test]
    fn supervisor_skill_doc_audit_enumerates_surfaces() {
        let rendered = render_supervisor();
        let start = rendered
            .find("**Doc audit**")
            .expect("Doc audit gate present");
        let end = rendered[start..]
            .find("**Security audit**")
            .map(|p| start + p)
            .expect("Security audit follows Doc audit");
        let section = &rendered[start..end];
        let mut hits = 0;
        for surface in ["docs/src/", "README.md", "AGENTS.md", "--help", "rustdoc"] {
            if section.contains(surface) {
                hits += 1;
            }
        }
        assert!(
            hits >= 4,
            "Doc audit must enumerate at least 4 of 5 doc surfaces; only {hits} found in:\n{section}",
        );
    }

    /// 8b.11 — Security audit gate enumerates at least 4 of 6 OWASP
    /// categories AND mentions the `unwrap()`/`expect()` rule.
    #[test]
    fn supervisor_skill_security_audit_enumerates_owasp_categories() {
        let rendered = render_supervisor();
        let start = rendered
            .find("**Security audit**")
            .expect("Security audit gate present");
        let end = rendered[start..]
            .find("**Verify or feedback**")
            .map_or(rendered.len(), |p| start + p);
        let section = &rendered[start..end];
        let lower = section.to_lowercase();
        let mut hits = 0;
        for cat in [
            "command injection",
            "xss",
            "sql injection",
            "path traversal",
            "unvalidated external input",
            "secret leakage",
        ] {
            if lower.contains(cat) {
                hits += 1;
            }
        }
        assert!(
            hits >= 4,
            "Security audit must enumerate at least 4 of 6 OWASP categories; only {hits} found in:\n{section}",
        );
        assert!(
            section.contains("unwrap()") || section.contains("expect()"),
            "Security audit must mention the unwrap()/expect() rule; got:\n{section}",
        );
    }

    /// 8b.12 — Governance verification sub-step is preserved (`DoD`,
    /// ADRs, `security.md`, `test-strategy.md`, `constitution.md` still present).
    #[test]
    fn supervisor_skill_governance_verification_substep_preserved() {
        let rendered = render_supervisor();
        let start = rendered
            .find("Governance verification")
            .expect("Governance verification sub-step still present");
        let end = (start + 2000).min(rendered.len());
        let section = &rendered[start..end];
        for needle in [
            "DoD",
            "ADR",
            "security.md",
            "test-strategy.md",
            "constitution.md",
        ] {
            assert!(
                section.contains(needle),
                "governance sub-step must still reference '{needle}'; got:\n{section}",
            );
        }
    }

    // ---------------------------------------------------------------------------
    // coordination-skill-followups-2: skill-content tests
    // (tasks 1.3, 2.3, 2.4, 3.3)
    // ---------------------------------------------------------------------------

    /// 1.3 — coordination skill teaches a per-group commit cadence with
    /// conventional-commit examples.
    #[test]
    fn coordination_skill_documents_commit_cadence() {
        let tmpl = resolve("coordination").unwrap();
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("commit cadence") || lowered.contains("per-group commit cadence"),
            "coordination skill should have a heading naming the commit-cadence concept; \
             got:\n{}",
            tmpl.content
        );
        assert!(
            lowered.contains("group") || lowered.contains("section"),
            "commit-cadence section should mention the GROUP/section grain"
        );
        let has_conventional_prefix = ["feat(", "fix(", "docs(", "test(", "chore("]
            .iter()
            .any(|p| tmpl.content.contains(p));
        assert!(
            has_conventional_prefix,
            "commit-cadence section should show at least one conventional-commit prefix example"
        );
    }

    /// 2.3 — coordination skill explicitly forbids the coding agent from
    /// invoking `/opsx:verify` and `/opsx:archive`.
    #[test]
    fn coordination_skill_forbids_opsx_verify_and_archive() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("/opsx:verify"),
            "coordination skill should name `/opsx:verify` literally"
        );
        assert!(
            tmpl.content.contains("/opsx:archive"),
            "coordination skill should name `/opsx:archive` literally"
        );
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("off-limits")
                || lowered.contains("do not invoke")
                || lowered.contains("shall not")
                || lowered.contains("supervisor's job"),
            "coordination skill should state both are not the coding agent's responsibility"
        );
    }

    /// 2.4 — coordination skill names `agent.artifact` as the terminal action
    /// with status "done" or "committed".
    #[test]
    fn coordination_skill_names_terminal_action() {
        let tmpl = resolve("coordination").unwrap();
        assert!(
            tmpl.content.contains("agent.artifact"),
            "coordination skill should name `agent.artifact` as the terminal publish"
        );
        assert!(
            tmpl.content.contains("\"done\"") || tmpl.content.contains("\"committed\""),
            "coordination skill should reference status: \"done\" or \"committed\""
        );
    }

    /// 3.3 — supervisor skill teaches `pane_current_path` as the canonical
    /// pane→agent resolution mechanism.
    #[test]
    fn supervisor_skill_documents_pane_current_path_resolution() {
        let tmpl = resolve("supervisor").unwrap();
        assert!(
            tmpl.content.contains("tmux display-message"),
            "supervisor skill should show the tmux display-message command"
        );
        assert!(
            tmpl.content.contains("pane_current_path"),
            "supervisor skill should name pane_current_path literally"
        );
        let lowered = tmpl.content.to_lowercase();
        assert!(
            lowered.contains("not alphabetical")
                || lowered.contains("not sorted alphabetically")
                || lowered.contains("are not alphabetical"),
            "supervisor skill should warn against alphabetical pane-index assumptions"
        );
        assert!(
            lowered.contains("cli-argument order")
                || lowered.contains("cli argument order")
                || lowered.contains("argument order"),
            "supervisor skill should warn against CLI-argument-order pane-index assumptions"
        );
    }

    // prompt-submit-fix coverage: ensure the supervisor skill's launch-time
    // pane sweep section continues to teach the three timing/escalation/
    // cross-reference contracts that the prompt-submit-fix change locked in.

    #[test]
    fn supervisor_skill_documents_proactive_launch_sweep() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        let start = lowered
            .find("launch-time pane sweep")
            .or_else(|| lowered.find("launch sweep"))
            .expect("launch-time pane sweep heading should be present");
        let window_end = (start + 2500).min(lowered.len());
        let window = &lowered[start..window_end];
        assert!(
            window.contains("immediately after attaching")
                || window.contains("before the poll thread")
                || window.contains("first-few-seconds")
                || window.contains("first few seconds"),
            "launch sweep should link the sweep to the first-few-seconds-after-attach window",
        );
    }

    #[test]
    fn supervisor_skill_launch_sweep_escalates_unknown_via_agent_question() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        let start = lowered
            .find("launch-time pane sweep")
            .or_else(|| lowered.find("launch sweep"))
            .expect("launch-time pane sweep heading should be present");
        let window_end = (start + 2500).min(lowered.len());
        let window = &lowered[start..window_end];
        assert!(
            window.contains("unknown") || window.contains("wider scope"),
            "launch sweep should classify a third category for unknown/wider-scope prompts",
        );
        assert!(
            window.contains("agent.question"),
            "launch sweep should instruct agent.question escalation for unknown prompts",
        );
        assert!(
            window.contains("escalate"),
            "launch sweep should use the word 'escalate' alongside the agent.question instruction",
        );
    }

    #[test]
    fn supervisor_skill_launch_sweep_complements_auto_approve_thread() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        let start = lowered
            .find("launch-time pane sweep")
            .or_else(|| lowered.find("launch sweep"))
            .expect("launch-time pane sweep heading should be present");
        let window_end = (start + 2500).min(lowered.len());
        let window = &lowered[start..window_end];
        assert!(
            window.contains("complements"),
            "launch sweep should describe itself as complementing the auto-approve thread",
        );
        assert!(
            window.contains("does not replace")
                || window.contains("not replace")
                || window.contains("does **not** replace"),
            "launch sweep should explicitly say it does NOT replace the auto-approve thread",
        );
        assert!(
            window.contains("[supervisor.auto_approve]") || window.contains("auto_approve"),
            "launch sweep should cross-reference the [supervisor.auto_approve] poll thread",
        );
    }

    // coordination-skill-followups: when the supervisor sends an
    // `agent.feedback` answer to a peer's `agent.question`, it must
    // dual-write via `tmux send-keys` AND cross-reference the
    // paste-buffer recovery sub-case for long answers. The test below
    // asserts that cross-reference is present in the send-keys section.
    // v0-5-0-audit-cleanup task 8.1.

    #[test]
    fn supervisor_skill_paste_buffer_cross_ref_in_send_keys_section() {
        let tmpl = resolve("supervisor").unwrap();
        let lowered = tmpl.content.to_lowercase();
        // Anchor on the "send the answer to the agent pane too" heading
        // — that's the section drift-34 owns. Fall back to a substring
        // unique to the section if the heading wording shifts.
        let start = lowered
            .find("send the answer to the agent pane")
            .or_else(|| lowered.find("agents do not poll their inbox"))
            .expect("send-keys-alongside-agent.feedback section should be present");
        let window_end = (start + 2200).min(lowered.len());
        let window = &lowered[start..window_end];

        assert!(
            window.contains("paste-buffer")
                || window.contains("paste buffer")
                || window.contains("follow-up enter")
                || window.contains("follow-up `enter`"),
            "send-keys-alongside-feedback section must cross-reference paste-buffer recovery / follow-up Enter for long answers",
        );
    }

    // coordination-skill-followups-2: the `pane_current_path` resolution
    // section must contain a warning against using `git paw status`
    // output order as a pane→agent mapping source. The dashboard and
    // status output are alphabetically sorted by the broker and have no
    // relationship to the launcher's pane assignment.
    // v0-5-0-audit-cleanup task 8.2.

    #[test]
    fn supervisor_skill_warns_against_git_paw_status_ordering() {
        let tmpl = resolve("supervisor").unwrap();
        // Case-sensitive search first for the literal `git paw status`
        // substring, then case-insensitive for the surrounding warning.
        assert!(
            tmpl.content.contains("git paw status"),
            "supervisor skill should reference `git paw status` by name when warning against using its ordering as a mapping source",
        );

        let lowered = tmpl.content.to_lowercase();
        let start = lowered
            .find("pane_current_path")
            .expect("pane_current_path resolution section should be present");
        let window_end = (start + 2500).min(lowered.len());
        let window = &lowered[start..window_end];

        assert!(
            window.contains("git paw status"),
            "the warning against `git paw status` ordering must appear within the pane_current_path resolution section",
        );
        assert!(
            window.contains("shall not be inferred")
                || window.contains("must not")
                || window.contains("not be inferred")
                || window.contains("not used as a mapping")
                || window.contains("no relationship"),
            "section must forbid using `git paw status` order as a mapping source",
        );
    }
}