ralph-core 2.9.2

Core orchestration loop, configuration, and state management for Ralph Orchestrator
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
//! Hatless Ralph - the constant coordinator.
//!
//! Ralph is always present, cannot be configured away, and acts as a universal fallback.

use crate::config::CoreConfig;
use crate::hat_registry::HatRegistry;
use ralph_proto::{HatId, Topic};
use std::collections::HashMap;
use std::path::Path;

/// Hatless Ralph - the constant coordinator.
pub struct HatlessRalph {
    completion_promise: String,
    core: CoreConfig,
    hat_topology: Option<HatTopology>,
    /// Event to publish after coordination to start the hat workflow.
    starting_event: Option<String>,
    /// Whether memories mode is enabled.
    /// When enabled, adds tasks CLI instructions alongside scratchpad.
    memories_enabled: bool,
    /// The user's original objective, stored at initialization.
    /// Injected into every prompt so hats always see the goal.
    objective: Option<String>,
    /// Pre-built skill index section for prompt injection.
    /// Set by EventLoop after SkillRegistry is initialized.
    skill_index: String,
    /// Collected robot guidance messages for injection into prompts.
    /// Set by EventLoop before build_prompt(), cleared after injection.
    robot_guidance: Vec<String>,
}

/// Hat topology for multi-hat mode prompt generation.
pub struct HatTopology {
    hats: Vec<HatInfo>,
}

/// Information about a hat that receives an event.
#[derive(Debug, Clone)]
pub struct EventReceiver {
    pub name: String,
    pub description: String,
    /// Hat ID for looking up config (e.g., concurrency settings).
    pub hat_id: HatId,
    /// Maximum concurrent wave instances for this hat (1 = sequential).
    pub concurrency: u32,
}

/// Information about a hat for prompt generation.
pub struct HatInfo {
    pub name: String,
    pub description: String,
    pub subscribes_to: Vec<String>,
    pub publishes: Vec<String>,
    pub instructions: String,
    /// Maps each published event to the hats that receive it.
    pub event_receivers: HashMap<String, Vec<EventReceiver>>,
    /// Tools the hat is not allowed to use (prompt-level enforcement).
    pub disallowed_tools: Vec<String>,
}

impl HatInfo {
    /// Generates an Event Publishing Guide section showing what happens when this hat publishes events.
    ///
    /// Returns `None` if the hat doesn't publish any events.
    pub fn event_publishing_guide(&self) -> Option<String> {
        if self.publishes.is_empty() {
            return None;
        }

        let mut guide = String::from(
            "### Event Publishing Guide\n\n\
             You MUST publish exactly ONE event when your work is complete.\n\
             You MUST use `ralph emit \"<topic>\" \"<brief summary>\"` to publish it.\n\
             Plain-language summaries do NOT publish events.\n\
             Publishing hands off to the next hat and starts a fresh iteration with clear context.\n\n\
             When you publish:\n",
        );

        for pub_event in &self.publishes {
            let receivers = self.event_receivers.get(pub_event);
            let receiver_text = match receivers {
                Some(r) if !r.is_empty() => r
                    .iter()
                    .map(|recv| {
                        if recv.description.is_empty() {
                            recv.name.clone()
                        } else {
                            format!("{} ({})", recv.name, recv.description)
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", "),
                _ => "Ralph (coordinates next steps)".to_string(),
            };
            guide.push_str(&format!(
                "- `{}` → Received by: {}\n",
                pub_event, receiver_text
            ));
        }

        Some(guide)
    }

    /// Generates a Wave Dispatch section when downstream hats support parallel execution.
    ///
    /// Shows a table of wave-capable topics and usage instructions for `ralph wave emit`.
    /// Returns empty string if no downstream hats have `concurrency > 1`.
    pub fn wave_dispatch_section(&self) -> String {
        // Collect wave-capable downstream topics
        let mut wave_topics: Vec<(&str, &str, u32)> = Vec::new();
        for pub_event in &self.publishes {
            if let Some(receivers) = self.event_receivers.get(pub_event) {
                for recv in receivers {
                    if recv.concurrency > 1 {
                        wave_topics.push((pub_event.as_str(), &recv.name, recv.concurrency));
                    }
                }
            }
        }

        if wave_topics.is_empty() {
            return String::new();
        }

        let mut section = String::from("### Wave Dispatch (Parallel Execution)\n\n");
        section.push_str(
            "Some downstream hats support parallel execution via waves. \
             Use `ralph wave emit` to dispatch multiple items for concurrent processing.\n\n",
        );

        section.push_str("| Topic | Activates | Max Concurrent |\n");
        section.push_str("|-------|-----------|----------------|\n");
        for (topic, hat_name, concurrency) in &wave_topics {
            section.push_str(&format!(
                "| `{}` | {} | {} |\n",
                topic, hat_name, concurrency
            ));
        }
        section.push('\n');

        // Usage example with the first wave topic
        if let Some((topic, _, _)) = wave_topics.first() {
            section.push_str("**Usage:**\n```bash\n");
            section.push_str(&format!(
                "ralph wave emit {} --payloads \"item1\" \"item2\" \"item3\"\n",
                topic
            ));
            section.push_str("```\n\n");
        }

        section
    }
}

impl HatTopology {
    /// Creates topology from registry.
    pub fn from_registry(registry: &HatRegistry) -> Self {
        let hats = registry
            .all()
            .map(|hat| {
                // Compute who receives each event this hat publishes
                let event_receivers: HashMap<String, Vec<EventReceiver>> = hat
                    .publishes
                    .iter()
                    .map(|pub_topic| {
                        let receivers: Vec<EventReceiver> = registry
                            .subscribers(pub_topic)
                            .into_iter()
                            .map(|h| {
                                let concurrency = registry
                                    .get_config(&h.id)
                                    .map(|c| c.concurrency)
                                    .unwrap_or(1);
                                EventReceiver {
                                    name: h.name.clone(),
                                    description: h.description.clone(),
                                    hat_id: h.id.clone(),
                                    concurrency,
                                }
                            })
                            .collect();
                        (pub_topic.as_str().to_string(), receivers)
                    })
                    .collect();

                let disallowed_tools = registry
                    .get_config(&hat.id)
                    .map(|c| c.disallowed_tools.clone())
                    .unwrap_or_default();

                HatInfo {
                    name: hat.name.clone(),
                    description: hat.description.clone(),
                    subscribes_to: hat
                        .subscriptions
                        .iter()
                        .map(|t| t.as_str().to_string())
                        .collect(),
                    publishes: hat
                        .publishes
                        .iter()
                        .map(|t| t.as_str().to_string())
                        .collect(),
                    instructions: hat.instructions.clone(),
                    event_receivers,
                    disallowed_tools,
                }
            })
            .collect();

        Self { hats }
    }
}

impl HatlessRalph {
    /// Creates a new HatlessRalph.
    ///
    /// # Arguments
    /// * `completion_promise` - Event topic that signals loop completion
    /// * `core` - Core configuration (scratchpad, specs_dir, guardrails)
    /// * `registry` - Hat registry for topology generation
    /// * `starting_event` - Optional event to publish after coordination to start hat workflow
    pub fn new(
        completion_promise: impl Into<String>,
        core: CoreConfig,
        registry: &HatRegistry,
        starting_event: Option<String>,
    ) -> Self {
        let hat_topology = if registry.is_empty() {
            None
        } else {
            Some(HatTopology::from_registry(registry))
        };

        Self {
            completion_promise: completion_promise.into(),
            core,
            hat_topology,
            starting_event,
            memories_enabled: false, // Default: scratchpad-only mode
            objective: None,
            skill_index: String::new(),
            robot_guidance: Vec::new(),
        }
    }

    /// Sets whether memories mode is enabled.
    ///
    /// When enabled, adds tasks CLI instructions alongside scratchpad.
    /// Scratchpad is always included regardless of this setting.
    pub fn with_memories_enabled(mut self, enabled: bool) -> Self {
        self.memories_enabled = enabled;
        self
    }

    /// Sets the pre-built skill index for prompt injection.
    ///
    /// The skill index is a compact table of available skills that appears
    /// between GUARDRAILS and OBJECTIVE in the prompt.
    pub fn with_skill_index(mut self, index: String) -> Self {
        self.skill_index = index;
        self
    }

    /// Stores the user's original objective so it persists across all iterations.
    ///
    /// Called once during initialization. The objective is injected into every
    /// prompt regardless of which hat is active, ensuring intermediate hats
    /// (test_writer, implementer, refactorer) always see the goal.
    pub fn set_objective(&mut self, objective: String) {
        self.objective = Some(objective);
    }

    /// Sets robot guidance messages collected from `human.guidance` events.
    ///
    /// Called by `EventLoop::build_prompt()` before `HatlessRalph::build_prompt()`.
    /// Multiple guidance messages are squashed into a numbered list and injected
    /// as a `## ROBOT GUIDANCE` section in the prompt.
    pub fn set_robot_guidance(&mut self, guidance: Vec<String>) {
        self.robot_guidance = guidance;
    }

    /// Clears stored robot guidance after it has been injected into a prompt.
    ///
    /// Called by `EventLoop::build_prompt()` after `HatlessRalph::build_prompt()`.
    pub fn clear_robot_guidance(&mut self) {
        self.robot_guidance.clear();
    }

    /// Collects robot guidance and returns the formatted prompt section.
    ///
    /// Squashes multiple guidance messages into a numbered list format.
    /// Returns an empty string if no guidance is pending.
    fn collect_robot_guidance(&self) -> String {
        if self.robot_guidance.is_empty() {
            return String::new();
        }

        let mut section = String::from("## ROBOT GUIDANCE\n\n");

        if self.robot_guidance.len() == 1 {
            section.push_str(&self.robot_guidance[0]);
        } else {
            for (i, guidance) in self.robot_guidance.iter().enumerate() {
                section.push_str(&format!("{}. {}\n", i + 1, guidance));
            }
        }

        section.push_str("\n\n");

        section
    }

    /// Builds Ralph's prompt with filtered instructions for only active hats.
    ///
    /// This method reduces token usage by including instructions only for hats
    /// that are currently triggered by pending events, while still showing the
    /// full hat topology table for context.
    ///
    /// For solo mode (no hats), pass an empty slice: `&[]`
    pub fn build_prompt(&self, context: &str, active_hats: &[&ralph_proto::Hat]) -> String {
        let mut prompt = self.core_prompt();

        // Inject skill index between GUARDRAILS and OBJECTIVE
        if !self.skill_index.is_empty() {
            prompt.push_str(&self.skill_index);
            prompt.push('\n');
        }

        // Add prominent OBJECTIVE section first (stored at initialization, persists across all iterations)
        if let Some(ref obj) = self.objective {
            prompt.push_str(&self.objective_section(obj));
        }

        // Inject robot guidance (collected from human.guidance events, cleared after injection)
        let guidance = self.collect_robot_guidance();
        if !guidance.is_empty() {
            prompt.push_str(&guidance);
        }

        // Include pending events BEFORE workflow so Ralph sees the task first
        if !context.trim().is_empty() {
            prompt.push_str("## PENDING EVENTS\n\n");
            prompt.push_str("You MUST handle these events in this iteration:\n\n");
            prompt.push_str(context);
            prompt.push_str("\n\n");
        }

        // Check if any active hat has custom instructions
        // If so, skip the generic workflow - the hat's instructions ARE the workflow
        let has_custom_workflow = active_hats
            .iter()
            .any(|h| !h.instructions.trim().is_empty());

        if !has_custom_workflow {
            prompt.push_str(&self.workflow_section());
        }

        if let Some(topology) = &self.hat_topology {
            prompt.push_str(&self.hats_section(topology, active_hats));
        }

        prompt.push_str(&self.event_writing_section());

        // Only show completion instructions when Ralph is coordinating (no active hat).
        // Hats should publish events and stop — only Ralph decides when the loop is done.
        if active_hats.is_empty() {
            prompt.push_str(&self.done_section(self.objective.as_deref()));
        }

        prompt
    }

    /// Generates the OBJECTIVE section - the primary goal Ralph must achieve.
    fn objective_section(&self, objective: &str) -> String {
        format!(
            r"## OBJECTIVE

**This is your primary goal. All work must advance this objective.**

> {objective}

You MUST keep this objective in mind throughout the iteration.
You MUST NOT get distracted by workflow mechanics — they serve this goal.

",
            objective = objective
        )
    }

    /// Always returns true - Ralph handles all events as fallback.
    pub fn should_handle(&self, _topic: &Topic) -> bool {
        true
    }

    /// Checks if this is a fresh start (starting_event set, no scratchpad).
    ///
    /// Used to enable fast path delegation that skips the PLAN step
    /// when immediate delegation to specialized hats is appropriate.
    fn is_fresh_start(&self) -> bool {
        // Fast path only applies when starting_event is configured
        if self.starting_event.is_none() {
            return false;
        }

        // Check if scratchpad exists
        let path = Path::new(&self.core.scratchpad);
        !path.exists()
    }

    fn core_prompt(&self) -> String {
        // Adapt guardrails based on whether scratchpad or memories mode is active
        let guardrails = self
            .core
            .guardrails
            .iter()
            .enumerate()
            .map(|(i, g)| {
                // Replace scratchpad reference with memories reference when memories are enabled
                let guardrail = if self.memories_enabled && g.contains("scratchpad is memory") {
                    g.replace(
                        "scratchpad is memory",
                        "save learnings to memories for next time",
                    )
                } else {
                    g.clone()
                };
                format!("{}. {guardrail}", 999 + i)
            })
            .collect::<Vec<_>>()
            .join("\n");

        let mut prompt = if self.memories_enabled {
            r"
### 0a. ORIENTATION
You are Ralph. You are running in a loop. You have fresh context each iteration.
You MUST complete only one atomic task for the overall objective. Leave work for future iterations.

**First thing every iteration:**
1. Review your `<scratchpad>` (auto-injected above) for context on your thinking
2. Review your `<ready-tasks>` (auto-injected above) to see what work exists
3. If tasks exist, pick one. If not, create them from your plan.
"
        } else {
            r"
### 0a. ORIENTATION
You are Ralph. You are running in a loop. You have fresh context each iteration.
You MUST complete only one atomic task for the overall objective. Leave work for future iterations.
"
        }
        .to_string();

        // SCRATCHPAD section - ALWAYS present
        prompt.push_str(&format!(
            r"### 0b. SCRATCHPAD
`{scratchpad}` is your thinking journal for THIS objective.
Its content is auto-injected in `<scratchpad>` tags at the top of your context each iteration.

**Always append** new entries to the end of the file (most recent = bottom).

**Use for:**
- Current understanding and reasoning
- Analysis notes and decisions
- Plan narrative (the 'why' behind your approach)

**Do NOT use for:**
- Tracking what tasks exist or their status (use `ralph tools task`)
- Checklists or todo lists (use `ralph tools task ensure` when a stable key exists, otherwise `ralph tools task add`)

",
            scratchpad = self.core.scratchpad,
        ));

        // TASKS section removed — now injected via skills auto-injection pipeline
        // (see EventLoop::inject_memories_and_tools_skill)
        // TASK BREAKDOWN guidance moved into ralph-tools.md

        // Add state management guidance (tasks/memories descriptions now live in their respective skills)
        prompt.push_str(&format!(
            "### STATE MANAGEMENT\n\n\
**Scratchpad** (`{scratchpad}`) — Your thinking:\n\
- Current understanding and reasoning\n\
- Analysis notes, decisions, plan narrative\n\
- NOT for checklists or status tracking\n\
\n\
**Context Files** (`.ralph/agent/*.md`) — Research artifacts:\n\
- Analysis and temporary notes\n\
- Read when relevant\n\
\n\
**Tool reliability rule:** Assume the workflow commands are available when the loop is already running and use the task-specific command you actually need.\n\
The loop sets `$RALPH_BIN` to the current Ralph executable. Prefer `$RALPH_BIN emit ...` and `$RALPH_BIN tools ...` when you need a direct command form.\n\
Do not spend turns on shell or tool-availability diagnosis unless the task is explicitly about the runtime environment.\n\
Do NOT infer failure from empty or terse stdout alone. Verify the intended side effect in the task/event state or in the files and artifacts the command should have changed.\n\
Keep temporary artifacts where later steps can still inspect them, such as a repo-local `logs/` directory or `/var/tmp` when needed.\n\
\n",
            scratchpad = self.core.scratchpad,
        ));

        // List available context files in .ralph/agent/
        if let Ok(entries) = std::fs::read_dir(".ralph/agent") {
            let md_files: Vec<String> = entries
                .filter_map(|e| e.ok())
                .filter_map(|e| {
                    let path = e.path();
                    let fname = path.file_name().and_then(|s| s.to_str());
                    if path.extension().and_then(|s| s.to_str()) == Some("md")
                        && fname != Some("memories.md")
                        && fname != Some("scratchpad.md")
                    {
                        path.file_name()
                            .and_then(|s| s.to_str())
                            .map(|s| s.to_string())
                    } else {
                        None
                    }
                })
                .collect();

            if !md_files.is_empty() {
                prompt.push_str("### AVAILABLE CONTEXT FILES\n\n");
                prompt.push_str(
                    "Context files in `.ralph/agent/` (read if relevant to current work):\n",
                );
                for file in md_files {
                    prompt.push_str(&format!("- `.ralph/agent/{}`\n", file));
                }
                prompt.push('\n');
            }
        }

        prompt.push_str(&format!(
            r"### GUARDRAILS
{guardrails}

",
            guardrails = guardrails,
        ));

        prompt
    }

    fn workflow_section(&self) -> String {
        // Different workflow for solo mode vs multi-hat mode
        if self.hat_topology.is_some() {
            // Check for fast path: starting_event set AND no scratchpad
            if self.is_fresh_start() {
                // Fast path: immediate delegation without planning
                return format!(
                    r#"## WORKFLOW

**FAST PATH**: You MUST publish `{}` immediately to start the hat workflow.
You MUST use `ralph emit "{}" "<brief handoff>"` and stop immediately.
You MUST NOT plan or analyze — delegate now.

"#,
                    self.starting_event.as_ref().unwrap(),
                    self.starting_event.as_ref().unwrap()
                );
            }

            // Multi-hat mode: Ralph coordinates and delegates
            if self.memories_enabled {
                // Memories mode: reference both scratchpad AND tasks CLI
                format!(
                    r"## WORKFLOW

### 1. PLAN
You MUST update `{scratchpad}` with your understanding and plan.
You MUST check `<ready-tasks>` first.
You MUST represent work items with runtime tasks using `ralph tools task ensure` when you can derive a stable key, otherwise `ralph tools task add`.
You SHOULD search memories with `ralph tools memory search` before acting in unfamiliar areas.
If confidence is 80 or below on a consequential decision, you MUST document it in `.ralph/agent/decisions.md`.

### 2. DELEGATE
You MUST emit exactly ONE next event via `ralph emit` to hand off to specialized hats.
Plain-language summaries do NOT hand off work.
You MUST NOT do implementation work — delegation is your only job.

",
                    scratchpad = self.core.scratchpad
                )
            } else {
                // Scratchpad-only mode (legacy)
                format!(
                    r"## WORKFLOW

### 1. PLAN
You MUST update `{scratchpad}` with prioritized tasks to complete the objective end-to-end.

### 2. DELEGATE
You MUST emit exactly ONE next event via `ralph emit` to hand off to specialized hats.
Plain-language summaries do NOT hand off work.
You MUST NOT do implementation work — delegation is your only job.

",
                    scratchpad = self.core.scratchpad
                )
            }
        } else {
            // Solo mode: Ralph does everything
            if self.memories_enabled {
                // Memories mode: reference both scratchpad AND tasks CLI
                format!(
                    r"## WORKFLOW

### 1. Study the prompt.
You MUST study, explore, and research what needs to be done.

### 2. PLAN
You MUST update `{scratchpad}` with your understanding and plan.
You MUST check `<ready-tasks>` first.
You MUST represent work items with runtime tasks using `ralph tools task ensure` when you can derive a stable key, otherwise `ralph tools task add`.
You SHOULD search memories with `ralph tools memory search` before acting in unfamiliar areas.
If confidence is 80 or below on a consequential decision, you MUST document it in `.ralph/agent/decisions.md`.

### 3. IMPLEMENT
You MUST pick exactly ONE task from `<ready-tasks>` to implement.
You MUST mark it in progress with `ralph tools task start <id>` before implementation.

### 4. VERIFY & COMMIT
You MUST run tests and verify the implementation works.
If the target is runnable or user-facing, you MUST exercise it with the strongest available harness (Playwright, tmux, real CLI/API) before committing.
You SHOULD try at least one realistic failure-path or adversarial input during verification.
If this turn is likely to take more than a few minutes, you SHOULD send `ralph tools interact progress`.
You MUST commit after verification passes - one commit per task.
You SHOULD run `git diff --cached` to review staged changes before committing.
You MUST close the task with `ralph tools task close <id>` AFTER commit.
You SHOULD save learnings to memories with `ralph tools memory add`.
If a command fails, a dependency is missing, or work becomes blocked and you cannot resolve it in this iteration, you MUST record a `fix` memory and `ralph tools task fail <id>` or `ralph tools task reopen <id>` before stopping.
You MUST update scratchpad with what you learned (tasks track what remains).

### 5. EXIT
You MUST exit after completing ONE task.

",
                    scratchpad = self.core.scratchpad
                )
            } else {
                // Scratchpad-only mode (legacy)
                format!(
                    r"## WORKFLOW

### 1. Study the prompt.
You MUST study, explore, and research what needs to be done.
You MAY use parallel subagents (up to 10) for searches.

### 2. PLAN
You MUST update `{scratchpad}` with prioritized tasks to complete the objective end-to-end.

### 3. IMPLEMENT
You MUST pick exactly ONE task to implement.
You MUST NOT use more than 1 subagent for build/tests.

### 4. COMMIT
If the target is runnable or user-facing, you MUST exercise it with the strongest available harness (Playwright, tmux, real CLI/API) before committing.
You SHOULD try at least one realistic failure-path or adversarial input during verification.
You MUST commit after completing each atomic unit of work.
You MUST capture the why, not just the what.
You SHOULD run `git diff` before committing to review changes.
You MUST mark the task `[x]` in scratchpad when complete.

### 5. REPEAT
You MUST continue until all tasks are `[x]` or `[~]`.

",
                    scratchpad = self.core.scratchpad
                )
            }
        }
    }

    fn hats_section(&self, topology: &HatTopology, active_hats: &[&ralph_proto::Hat]) -> String {
        let mut section = String::new();

        // When a specific hat is active, skip the topology overview (table + Mermaid)
        // The hat just needs its instructions and publishing guide
        if active_hats.is_empty() {
            // Ralph is coordinating - show full topology for delegation decisions
            section.push_str("## HATS\n\nDelegate via events.\n\n");

            // Include starting_event instruction if configured
            if let Some(ref starting_event) = self.starting_event {
                section.push_str(&format!(
                    "**After coordination, publish `{}` to start the workflow.**\n\n",
                    starting_event
                ));
            }

            // Derive Ralph's triggers and publishes from topology
            // Ralph triggers on: task.start + all hats' publishes (results Ralph handles)
            // Ralph publishes: all hats' subscribes_to (events Ralph can emit to delegate)
            let mut ralph_triggers: Vec<&str> = vec!["task.start"];
            let mut ralph_publishes: Vec<&str> = Vec::new();

            for hat in &topology.hats {
                for pub_event in &hat.publishes {
                    if !ralph_triggers.contains(&pub_event.as_str()) {
                        ralph_triggers.push(pub_event.as_str());
                    }
                }
                for sub_event in &hat.subscribes_to {
                    if !ralph_publishes.contains(&sub_event.as_str()) {
                        ralph_publishes.push(sub_event.as_str());
                    }
                }
            }

            // Build hat table with Description column
            section.push_str("| Hat | Triggers On | Publishes | Description |\n");
            section.push_str("|-----|-------------|----------|-------------|\n");

            // Add Ralph coordinator row first
            section.push_str(&format!(
                "| Ralph | {} | {} | Coordinates workflow, delegates to specialized hats |\n",
                ralph_triggers.join(", "),
                ralph_publishes.join(", ")
            ));

            // Add all other hats
            for hat in &topology.hats {
                let subscribes = hat.subscribes_to.join(", ");
                let publishes = hat.publishes.join(", ");
                section.push_str(&format!(
                    "| {} | {} | {} | {} |\n",
                    hat.name, subscribes, publishes, hat.description
                ));
            }

            section.push('\n');

            // Generate Mermaid topology diagram
            section.push_str(&self.generate_mermaid_diagram(topology, &ralph_publishes));
            section.push('\n');

            // Add explicit constraint listing valid events Ralph can publish
            if !ralph_publishes.is_empty() {
                section.push_str(&format!(
                    "**CONSTRAINT:** You MUST only publish events from this list: `{}`\n\
                     Publishing other events will have no effect - no hat will receive them.\n\n",
                    ralph_publishes.join("`, `")
                ));
            }

            // Validate topology and log warnings for unreachable hats
            self.validate_topology_reachability(topology);
        } else {
            // Specific hat(s) active - minimal section with just instructions + guide
            section.push_str("## ACTIVE HAT\n\n");

            for active_hat in active_hats {
                // Find matching HatInfo from topology to access event_receivers
                let hat_info = topology.hats.iter().find(|h| h.name == active_hat.name);

                if !active_hat.instructions.trim().is_empty() {
                    section.push_str(&format!("### {} Instructions\n\n", active_hat.name));
                    section.push_str(&active_hat.instructions);
                    if !active_hat.instructions.ends_with('\n') {
                        section.push('\n');
                    }
                    section.push('\n');
                }

                // Add Event Publishing Guide after instructions (if hat publishes events)
                if let Some(guide) = hat_info.and_then(|info| info.event_publishing_guide()) {
                    section.push_str(&guide);
                    section.push('\n');
                }

                // Add Wave Dispatch section when downstream hats support concurrency > 1
                if let Some(info) = hat_info {
                    let wave_dispatch = info.wave_dispatch_section();
                    if !wave_dispatch.is_empty() {
                        section.push_str(&wave_dispatch);
                    }
                }

                // Add Tool Restrictions section (prompt-level enforcement)
                if let Some(info) = hat_info
                    && !info.disallowed_tools.is_empty()
                {
                    section.push_str("### TOOL RESTRICTIONS\n\n");
                    section.push_str("You MUST NOT use these tools in this hat:\n");
                    for tool in &info.disallowed_tools {
                        section.push_str(&format!("- **{}** — blocked for this hat\n", tool));
                    }
                    section.push_str(
                        "\nUsing a restricted tool is a scope violation. \
                         File modifications are audited after each iteration.\n\n",
                    );
                }
            }
        }

        section
    }

    /// Generates a Mermaid flowchart showing event flow between hats.
    fn generate_mermaid_diagram(&self, topology: &HatTopology, ralph_publishes: &[&str]) -> String {
        // Pre-compute sanitized Mermaid node IDs (strip emojis/special chars)
        let node_ids: std::collections::HashMap<&str, String> = topology
            .hats
            .iter()
            .map(|h| {
                let id = h
                    .name
                    .chars()
                    .filter(|c| c.is_alphanumeric())
                    .collect::<String>();
                (h.name.as_str(), id)
            })
            .collect();

        let mut diagram = String::from("```mermaid\nflowchart LR\n");

        // Entry point: task.start -> Ralph
        diagram.push_str("    task.start((task.start)) --> Ralph\n");

        // Ralph -> hats (via ralph_publishes which are hat triggers)
        for hat in &topology.hats {
            let node_id = &node_ids[hat.name.as_str()];
            for trigger in &hat.subscribes_to {
                if ralph_publishes.contains(&trigger.as_str()) {
                    if node_id == &hat.name {
                        diagram.push_str(&format!("    Ralph -->|{}| {}\n", trigger, hat.name));
                    } else {
                        diagram.push_str(&format!(
                            "    Ralph -->|{}| {}[{}]\n",
                            trigger, node_id, hat.name
                        ));
                    }
                }
            }
        }

        // Hats -> Ralph (via hat publishes)
        for hat in &topology.hats {
            let node_id = &node_ids[hat.name.as_str()];
            for pub_event in &hat.publishes {
                diagram.push_str(&format!("    {} -->|{}| Ralph\n", node_id, pub_event));
            }
        }

        // Hat -> Hat connections (when one hat publishes what another triggers on)
        for source_hat in &topology.hats {
            let source_id = &node_ids[source_hat.name.as_str()];
            for pub_event in &source_hat.publishes {
                for target_hat in &topology.hats {
                    if target_hat.name != source_hat.name
                        && target_hat.subscribes_to.contains(pub_event)
                    {
                        let target_id = &node_ids[target_hat.name.as_str()];
                        diagram.push_str(&format!(
                            "    {} -->|{}| {}\n",
                            source_id, pub_event, target_id
                        ));
                    }
                }
            }
        }

        diagram.push_str("```\n");
        diagram
    }

    /// Validates that all hats are reachable from task.start.
    /// Logs warnings for unreachable hats but doesn't fail.
    fn validate_topology_reachability(&self, topology: &HatTopology) {
        use std::collections::HashSet;
        use tracing::warn;

        // Collect all events that are published (reachable)
        let mut reachable_events: HashSet<&str> = HashSet::new();
        reachable_events.insert("task.start");

        // Ralph publishes all hat triggers, so add those
        for hat in &topology.hats {
            for trigger in &hat.subscribes_to {
                reachable_events.insert(trigger.as_str());
            }
        }

        // Now add all events published by hats (they become reachable after hat runs)
        for hat in &topology.hats {
            for pub_event in &hat.publishes {
                reachable_events.insert(pub_event.as_str());
            }
        }

        // Check each hat's triggers - warn if none of them are reachable
        for hat in &topology.hats {
            let hat_reachable = hat
                .subscribes_to
                .iter()
                .any(|t| reachable_events.contains(t.as_str()));
            if !hat_reachable {
                warn!(
                    hat = %hat.name,
                    triggers = ?hat.subscribes_to,
                    "Hat has triggers that are never published - it may be unreachable"
                );
            }
        }
    }

    fn event_writing_section(&self) -> String {
        // Always use scratchpad for detailed output (scratchpad is always present)
        let detailed_output_hint = format!(
            "You SHOULD write detailed output to `{}` and emit only a brief event.",
            self.core.scratchpad
        );

        format!(
            r#"## EVENT WRITING

Events are routing signals, not data transport. You SHOULD keep payloads brief.

You MUST use `ralph emit` to write events (handles JSON escaping correctly):
```bash
ralph emit "build.done" "tests: pass, lint: pass, typecheck: pass, audit: pass, coverage: pass"
ralph emit "review.done" --json '{{"status": "approved", "issues": 0}}'
```

You MUST NOT use echo/cat to write events because shell escaping breaks JSON.

{detailed_output_hint}

**Constraints:**
- You MUST stop working after publishing an event because a new iteration will start with fresh context
- You MUST NOT continue with additional work after publishing because the next iteration handles it with the appropriate hat persona
"#,
            detailed_output_hint = detailed_output_hint
        )
    }

    fn done_section(&self, objective: Option<&str>) -> String {
        let mut section = if self.hat_topology.is_some() {
            format!(
                r"## DONE

You MUST emit the completion event `{}` via `ralph emit` when the objective is complete and all tasks are done.
Stdout text does NOT end the loop in coordinated mode.
",
                self.completion_promise
            )
        } else {
            format!(
                r"## DONE

You MUST output the literal completion promise `{}` as the final non-empty line when the objective is complete and all tasks are done.
You MUST NOT substitute a prose summary for `{}`.
You MUST NOT print any text after `{}`.
",
                self.completion_promise, self.completion_promise, self.completion_promise
            )
        };

        // Add task verification when memories/tasks mode is enabled
        if self.memories_enabled {
            section.push_str(
                r"
**Before declaring completion:**
1. Run `ralph tools task list` to check for any remaining non-terminal tasks
2. If any tasks are still open or in progress, close, fail, or reopen them first
3. Only declare completion when YOUR tasks for this objective are all terminal

Tasks from other parallel loops are filtered out automatically. You only need to verify tasks YOU created for THIS objective are complete.

You MUST NOT declare completion while tasks remain open.
",
            );
        }

        // Reinforce the objective at the end to bookend the prompt
        if let Some(obj) = objective {
            section.push_str(&format!(
                r"
**Remember your objective:**
> {}

You MUST NOT declare completion until this objective is fully satisfied.
",
                obj
            ));
        }

        section
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::RalphConfig;

    #[test]
    fn test_prompt_without_hats() {
        let config = RalphConfig::default();
        let registry = HatRegistry::new(); // Empty registry
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        // Identity with RFC2119 style
        assert!(prompt.contains(
            "You are Ralph. You are running in a loop. You have fresh context each iteration."
        ));

        // Numbered orientation phases (RFC2119)
        assert!(prompt.contains("### 0a. ORIENTATION"));
        assert!(prompt.contains("MUST complete only one atomic task"));

        // Scratchpad section with auto-inject and append instructions
        assert!(prompt.contains("### 0b. SCRATCHPAD"));
        assert!(prompt.contains("auto-injected"));
        assert!(prompt.contains("**Always append**"));

        // Workflow with numbered steps (solo mode) using RFC2119
        assert!(prompt.contains("## WORKFLOW"));
        assert!(prompt.contains("### 1. Study the prompt"));
        assert!(prompt.contains("You MAY use parallel subagents (up to 10)"));
        assert!(prompt.contains("### 2. PLAN"));
        assert!(prompt.contains("### 3. IMPLEMENT"));
        assert!(prompt.contains("You MUST NOT use more than 1 subagent for build/tests"));
        assert!(prompt.contains("### 4. COMMIT"));
        assert!(prompt.contains("You MUST capture the why"));
        assert!(prompt.contains("### 5. REPEAT"));

        // Should NOT have hats section when no hats
        assert!(!prompt.contains("## HATS"));

        // Event writing and completion using RFC2119
        assert!(prompt.contains("## EVENT WRITING"));
        assert!(prompt.contains("You MUST use `ralph emit`"));
        assert!(prompt.contains("You MUST NOT use echo/cat"));
        assert!(prompt.contains("LOOP_COMPLETE"));
    }

    #[test]
    fn test_prompt_with_hats() {
        // Test multi-hat mode WITHOUT starting_event (no fast path)
        let yaml = r#"
hats:
  planner:
    name: "Planner"
    triggers: ["planning.start", "build.done", "build.blocked"]
    publishes: ["build.task"]
  builder:
    name: "Builder"
    triggers: ["build.task"]
    publishes: ["build.done", "build.blocked"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        // Note: No starting_event - tests normal multi-hat workflow (not fast path)
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        // Identity with RFC2119 style
        assert!(prompt.contains(
            "You are Ralph. You are running in a loop. You have fresh context each iteration."
        ));

        // Orientation phases
        assert!(prompt.contains("### 0a. ORIENTATION"));
        assert!(prompt.contains("### 0b. SCRATCHPAD"));

        // Multi-hat workflow: PLAN + DELEGATE, not IMPLEMENT (RFC2119)
        assert!(prompt.contains("## WORKFLOW"));
        assert!(prompt.contains("### 1. PLAN"));
        assert!(
            prompt.contains("### 2. DELEGATE"),
            "Multi-hat mode should have DELEGATE step"
        );
        assert!(
            !prompt.contains("### 3. IMPLEMENT"),
            "Multi-hat mode should NOT tell Ralph to implement"
        );
        assert!(
            prompt.contains("You MUST stop working after publishing"),
            "Should explicitly tell Ralph to stop after publishing event"
        );

        // Hats section when hats are defined
        assert!(prompt.contains("## HATS"));
        assert!(prompt.contains("Delegate via events"));
        assert!(prompt.contains("| Hat | Triggers On | Publishes |"));

        // Event writing and completion
        assert!(prompt.contains("## EVENT WRITING"));
        assert!(prompt.contains("LOOP_COMPLETE"));
    }

    #[test]
    fn test_should_handle_always_true() {
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        assert!(ralph.should_handle(&Topic::new("any.topic")));
        assert!(ralph.should_handle(&Topic::new("build.task")));
        assert!(ralph.should_handle(&Topic::new("unknown.event")));
    }

    #[test]
    fn test_rfc2119_patterns_present() {
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        // Key RFC2119 language patterns
        assert!(
            prompt.contains("You MUST study"),
            "Should use RFC2119 MUST with 'study' verb"
        );
        assert!(
            prompt.contains("You MUST complete only one atomic task"),
            "Should have RFC2119 MUST complete atomic task constraint"
        );
        assert!(
            prompt.contains("You MAY use parallel subagents"),
            "Should mention parallel subagents with MAY"
        );
        assert!(
            prompt.contains("You MUST NOT use more than 1 subagent"),
            "Should limit to 1 subagent for builds with MUST NOT"
        );
        assert!(
            prompt.contains("You MUST capture the why"),
            "Should emphasize 'why' in commits with MUST"
        );

        // Numbered guardrails (999+)
        assert!(
            prompt.contains("### GUARDRAILS"),
            "Should have guardrails section"
        );
        assert!(
            prompt.contains("999."),
            "Guardrails should use high numbers"
        );
    }

    #[test]
    fn test_scratchpad_format_documented() {
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        // Auto-injection and append instructions are documented
        assert!(prompt.contains("auto-injected"));
        assert!(prompt.contains("**Always append**"));
    }

    #[test]
    fn test_starting_event_in_prompt() {
        // When starting_event is configured, prompt should include delegation instruction
        let yaml = r#"
hats:
  tdd_writer:
    name: "TDD Writer"
    triggers: ["tdd.start"]
    publishes: ["test.written"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new(
            "LOOP_COMPLETE",
            config.core.clone(),
            &registry,
            Some("tdd.start".to_string()),
        );

        let prompt = ralph.build_prompt("", &[]);

        // Should include delegation instruction
        assert!(
            prompt.contains("After coordination, publish `tdd.start` to start the workflow"),
            "Prompt should include starting_event delegation instruction"
        );
    }

    #[test]
    fn test_no_starting_event_instruction_when_none() {
        // When starting_event is None, no delegation instruction should appear
        let yaml = r#"
hats:
  some_hat:
    name: "Some Hat"
    triggers: ["some.event"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        // Should NOT include delegation instruction
        assert!(
            !prompt.contains("After coordination, publish"),
            "Prompt should NOT include starting_event delegation when None"
        );
    }

    #[test]
    fn test_hat_instructions_propagated_to_prompt() {
        // When a hat has instructions defined in config,
        // those instructions should appear in the generated prompt
        let yaml = r#"
hats:
  tdd_writer:
    name: "TDD Writer"
    triggers: ["tdd.start"]
    publishes: ["test.written"]
    instructions: |
      You are a Test-Driven Development specialist.
      Always write failing tests before implementation.
      Focus on edge cases and error handling.
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new(
            "LOOP_COMPLETE",
            config.core.clone(),
            &registry,
            Some("tdd.start".to_string()),
        );

        // Get the tdd_writer hat as active to see its instructions
        let tdd_writer = registry
            .get(&ralph_proto::HatId::new("tdd_writer"))
            .unwrap();
        let prompt = ralph.build_prompt("", &[tdd_writer]);

        // Instructions should appear in the prompt
        assert!(
            prompt.contains("### TDD Writer Instructions"),
            "Prompt should include hat instructions section header"
        );
        assert!(
            prompt.contains("Test-Driven Development specialist"),
            "Prompt should include actual instructions content"
        );
        assert!(
            prompt.contains("Always write failing tests"),
            "Prompt should include full instructions"
        );
    }

    #[test]
    fn test_empty_instructions_not_rendered() {
        // When a hat has empty/no instructions, no instructions section should appear
        let yaml = r#"
hats:
  builder:
    name: "Builder"
    triggers: ["build.task"]
    publishes: ["build.done"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        // No instructions section should appear for hats without instructions
        assert!(
            !prompt.contains("### Builder Instructions"),
            "Prompt should NOT include instructions section for hat with empty instructions"
        );
    }

    #[test]
    fn test_multiple_hats_with_instructions() {
        // When multiple hats have instructions, each should have its own section
        let yaml = r#"
hats:
  planner:
    name: "Planner"
    triggers: ["planning.start"]
    publishes: ["build.task"]
    instructions: "Plan carefully before implementation."
  builder:
    name: "Builder"
    triggers: ["build.task"]
    publishes: ["build.done"]
    instructions: "Focus on clean, testable code."
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        // Get both hats as active to see their instructions
        let planner = registry.get(&ralph_proto::HatId::new("planner")).unwrap();
        let builder = registry.get(&ralph_proto::HatId::new("builder")).unwrap();
        let prompt = ralph.build_prompt("", &[planner, builder]);

        // Both hats' instructions should appear
        assert!(
            prompt.contains("### Planner Instructions"),
            "Prompt should include Planner instructions section"
        );
        assert!(
            prompt.contains("Plan carefully before implementation"),
            "Prompt should include Planner instructions content"
        );
        assert!(
            prompt.contains("### Builder Instructions"),
            "Prompt should include Builder instructions section"
        );
        assert!(
            prompt.contains("Focus on clean, testable code"),
            "Prompt should include Builder instructions content"
        );
    }

    #[test]
    fn test_fast_path_with_starting_event() {
        // When starting_event is configured AND scratchpad doesn't exist,
        // should use fast path (skip PLAN step)
        let yaml = r#"
core:
  scratchpad: "/nonexistent/path/scratchpad.md"
hats:
  tdd_writer:
    name: "TDD Writer"
    triggers: ["tdd.start"]
    publishes: ["test.written"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new(
            "LOOP_COMPLETE",
            config.core.clone(),
            &registry,
            Some("tdd.start".to_string()),
        );

        let prompt = ralph.build_prompt("", &[]);

        // Should use fast path - immediate delegation with RFC2119
        assert!(
            prompt.contains("FAST PATH"),
            "Prompt should indicate fast path when starting_event set and no scratchpad"
        );
        assert!(
            prompt.contains("You MUST publish `tdd.start` immediately"),
            "Prompt should instruct immediate event publishing with MUST"
        );
        assert!(
            prompt.contains("ralph emit \"tdd.start\""),
            "Fast path should require explicit event emission"
        );
        assert!(
            !prompt.contains("### 1. PLAN"),
            "Fast path should skip PLAN step"
        );
    }

    #[test]
    fn test_events_context_included_in_prompt() {
        // Given a non-empty events context
        // When build_prompt(context) is called
        // Then the prompt contains ## PENDING EVENTS section with the context
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let events_context = r"[task.start] User's task: Review this code for security vulnerabilities
[build.done] Build completed successfully";

        let prompt = ralph.build_prompt(events_context, &[]);

        assert!(
            prompt.contains("## PENDING EVENTS"),
            "Prompt should contain PENDING EVENTS section"
        );
        assert!(
            prompt.contains("Review this code for security vulnerabilities"),
            "Prompt should contain the user's task"
        );
        assert!(
            prompt.contains("Build completed successfully"),
            "Prompt should contain all events from context"
        );
    }

    #[test]
    fn test_empty_context_no_pending_events_section() {
        // Given an empty events context
        // When build_prompt("") is called
        // Then no PENDING EVENTS section appears
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        assert!(
            !prompt.contains("## PENDING EVENTS"),
            "Empty context should not produce PENDING EVENTS section"
        );
    }

    #[test]
    fn test_whitespace_only_context_no_pending_events_section() {
        // Given a whitespace-only events context
        // When build_prompt is called
        // Then no PENDING EVENTS section appears
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("   \n\t  ", &[]);

        assert!(
            !prompt.contains("## PENDING EVENTS"),
            "Whitespace-only context should not produce PENDING EVENTS section"
        );
    }

    #[test]
    fn test_events_section_before_workflow() {
        // Given events context with a task
        // When prompt is built
        // Then ## PENDING EVENTS appears BEFORE ## WORKFLOW
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let events_context = "[task.start] Implement feature X";
        let prompt = ralph.build_prompt(events_context, &[]);

        let events_pos = prompt
            .find("## PENDING EVENTS")
            .expect("Should have PENDING EVENTS");
        let workflow_pos = prompt.find("## WORKFLOW").expect("Should have WORKFLOW");

        assert!(
            events_pos < workflow_pos,
            "PENDING EVENTS ({}) should come before WORKFLOW ({})",
            events_pos,
            workflow_pos
        );
    }

    // === Phase 3: Filtered Hat Instructions Tests ===

    #[test]
    fn test_only_active_hat_instructions_included() {
        // Scenario 4 from plan.md: Only active hat instructions included in prompt
        let yaml = r#"
hats:
  security_reviewer:
    name: "Security Reviewer"
    triggers: ["review.security"]
    instructions: "Review code for security vulnerabilities."
  architecture_reviewer:
    name: "Architecture Reviewer"
    triggers: ["review.architecture"]
    instructions: "Review system design and architecture."
  correctness_reviewer:
    name: "Correctness Reviewer"
    triggers: ["review.correctness"]
    instructions: "Review logic and correctness."
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        // Get active hats - only security_reviewer is active
        let security_hat = registry
            .get(&ralph_proto::HatId::new("security_reviewer"))
            .unwrap();
        let active_hats = vec![security_hat];

        let prompt = ralph.build_prompt("Event: review.security - Check auth", &active_hats);

        // Should contain ONLY security_reviewer instructions
        assert!(
            prompt.contains("### Security Reviewer Instructions"),
            "Should include Security Reviewer instructions section"
        );
        assert!(
            prompt.contains("Review code for security vulnerabilities"),
            "Should include Security Reviewer instructions content"
        );

        // Should NOT contain other hats' instructions
        assert!(
            !prompt.contains("### Architecture Reviewer Instructions"),
            "Should NOT include Architecture Reviewer instructions"
        );
        assert!(
            !prompt.contains("Review system design and architecture"),
            "Should NOT include Architecture Reviewer instructions content"
        );
        assert!(
            !prompt.contains("### Correctness Reviewer Instructions"),
            "Should NOT include Correctness Reviewer instructions"
        );
    }

    #[test]
    fn test_multiple_active_hats_all_included() {
        // Scenario 6 from plan.md: Multiple active hats includes all instructions
        let yaml = r#"
hats:
  security_reviewer:
    name: "Security Reviewer"
    triggers: ["review.security"]
    instructions: "Review code for security vulnerabilities."
  architecture_reviewer:
    name: "Architecture Reviewer"
    triggers: ["review.architecture"]
    instructions: "Review system design and architecture."
  correctness_reviewer:
    name: "Correctness Reviewer"
    triggers: ["review.correctness"]
    instructions: "Review logic and correctness."
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        // Get active hats - both security_reviewer and architecture_reviewer are active
        let security_hat = registry
            .get(&ralph_proto::HatId::new("security_reviewer"))
            .unwrap();
        let arch_hat = registry
            .get(&ralph_proto::HatId::new("architecture_reviewer"))
            .unwrap();
        let active_hats = vec![security_hat, arch_hat];

        let prompt = ralph.build_prompt("Events", &active_hats);

        // Should contain BOTH active hats' instructions
        assert!(
            prompt.contains("### Security Reviewer Instructions"),
            "Should include Security Reviewer instructions"
        );
        assert!(
            prompt.contains("Review code for security vulnerabilities"),
            "Should include Security Reviewer content"
        );
        assert!(
            prompt.contains("### Architecture Reviewer Instructions"),
            "Should include Architecture Reviewer instructions"
        );
        assert!(
            prompt.contains("Review system design and architecture"),
            "Should include Architecture Reviewer content"
        );

        // Should NOT contain inactive hat's instructions
        assert!(
            !prompt.contains("### Correctness Reviewer Instructions"),
            "Should NOT include Correctness Reviewer instructions"
        );
    }

    #[test]
    fn test_no_active_hats_no_instructions() {
        // No active hats = no instructions section (but topology table still present)
        let yaml = r#"
hats:
  security_reviewer:
    name: "Security Reviewer"
    triggers: ["review.security"]
    instructions: "Review code for security vulnerabilities."
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        // No active hats
        let active_hats: Vec<&ralph_proto::Hat> = vec![];

        let prompt = ralph.build_prompt("Events", &active_hats);

        // Should NOT contain any instructions
        assert!(
            !prompt.contains("### Security Reviewer Instructions"),
            "Should NOT include instructions when no active hats"
        );
        assert!(
            !prompt.contains("Review code for security vulnerabilities"),
            "Should NOT include instructions content when no active hats"
        );

        // But topology table should still be present
        assert!(prompt.contains("## HATS"), "Should still have HATS section");
        assert!(
            prompt.contains("| Hat | Triggers On | Publishes |"),
            "Should still have topology table"
        );
    }

    #[test]
    fn test_topology_table_only_when_ralph_coordinating() {
        // Topology table + Mermaid shown only when Ralph is coordinating (no active hats)
        // When a hat is active, skip the table to reduce token usage
        let yaml = r#"
hats:
  security_reviewer:
    name: "Security Reviewer"
    triggers: ["review.security"]
    instructions: "Security instructions."
  architecture_reviewer:
    name: "Architecture Reviewer"
    triggers: ["review.architecture"]
    instructions: "Architecture instructions."
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        // Test 1: No active hats (Ralph coordinating) - should show table + Mermaid
        let prompt_coordinating = ralph.build_prompt("Events", &[]);

        assert!(
            prompt_coordinating.contains("## HATS"),
            "Should have HATS section when coordinating"
        );
        assert!(
            prompt_coordinating.contains("| Hat | Triggers On | Publishes |"),
            "Should have topology table when coordinating"
        );
        assert!(
            prompt_coordinating.contains("```mermaid"),
            "Should have Mermaid diagram when coordinating"
        );

        // Test 2: Active hat - should NOT show table/Mermaid, just instructions
        let security_hat = registry
            .get(&ralph_proto::HatId::new("security_reviewer"))
            .unwrap();
        let prompt_active = ralph.build_prompt("Events", &[security_hat]);

        assert!(
            prompt_active.contains("## ACTIVE HAT"),
            "Should have ACTIVE HAT section when hat is active"
        );
        assert!(
            !prompt_active.contains("| Hat | Triggers On | Publishes |"),
            "Should NOT have topology table when hat is active"
        );
        assert!(
            !prompt_active.contains("```mermaid"),
            "Should NOT have Mermaid diagram when hat is active"
        );
        assert!(
            prompt_active.contains("### Security Reviewer Instructions"),
            "Should still have the active hat's instructions"
        );
    }

    // === Memories/Scratchpad Exclusivity Tests ===

    #[test]
    fn test_scratchpad_always_included() {
        // Scratchpad section should always be included (regardless of memories mode)
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        assert!(
            prompt.contains("### 0b. SCRATCHPAD"),
            "Scratchpad section should be included"
        );
        assert!(
            prompt.contains("`.ralph/agent/scratchpad.md`"),
            "Scratchpad path should be referenced"
        );
        assert!(
            prompt.contains("auto-injected"),
            "Auto-injection should be documented"
        );
    }

    #[test]
    fn test_scratchpad_included_with_memories_enabled() {
        // When memories are enabled, scratchpad should STILL be included (not excluded)
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None)
            .with_memories_enabled(true);

        let prompt = ralph.build_prompt("", &[]);

        // Scratchpad should still be present
        assert!(
            prompt.contains("### 0b. SCRATCHPAD"),
            "Scratchpad section should be included even with memories enabled"
        );
        assert!(
            prompt.contains("**Always append**"),
            "Append instruction should be documented"
        );

        // Tasks section is now injected via the skills pipeline (not in core_prompt)
        assert!(
            !prompt.contains("### 0c. TASKS"),
            "Tasks section should NOT be in core_prompt — injected via skills pipeline"
        );
    }

    #[test]
    fn test_no_tasks_section_in_core_prompt() {
        // Tasks section is now in the skills pipeline, not core_prompt
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        // core_prompt no longer contains the tasks section (injected via skills)
        assert!(
            !prompt.contains("### 0c. TASKS"),
            "Tasks section should NOT be in core_prompt — injected via skills pipeline"
        );
    }

    #[test]
    fn test_workflow_references_both_scratchpad_and_tasks_with_memories() {
        // When memories enabled, workflow should reference BOTH scratchpad AND tasks CLI
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None)
            .with_memories_enabled(true);

        let prompt = ralph.build_prompt("", &[]);

        // Workflow should mention scratchpad
        assert!(
            prompt.contains("update scratchpad"),
            "Workflow should reference scratchpad when memories enabled"
        );
        // Workflow should also mention tasks CLI
        assert!(
            prompt.contains("ralph tools task"),
            "Workflow should reference tasks CLI when memories enabled"
        );
    }

    #[test]
    fn test_multi_hat_mode_workflow_with_memories_enabled() {
        // Multi-hat mode should reference scratchpad AND tasks CLI when memories enabled
        let yaml = r#"
hats:
  builder:
    name: "Builder"
    triggers: ["build.task"]
    publishes: ["build.done"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None)
            .with_memories_enabled(true);

        let prompt = ralph.build_prompt("", &[]);

        // Multi-hat workflow should mention scratchpad
        assert!(
            prompt.contains("scratchpad"),
            "Multi-hat workflow should reference scratchpad when memories enabled"
        );
        // And tasks CLI
        assert!(
            prompt.contains("ralph tools task ensure"),
            "Multi-hat workflow should reference tasks CLI when memories enabled"
        );
    }

    #[test]
    fn test_guardrails_adapt_to_memories_mode() {
        // When memories enabled, guardrails should encourage saving to memories
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None)
            .with_memories_enabled(true);

        let prompt = ralph.build_prompt("", &[]);

        // With memories enabled + include_scratchpad still true (default),
        // the guardrail transformation doesn't apply
        // Just verify the prompt generates correctly
        assert!(
            prompt.contains("### GUARDRAILS"),
            "Guardrails section should be present"
        );
    }

    #[test]
    fn test_guardrails_present_without_memories() {
        // Without memories, guardrails should still be present
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        // memories_enabled defaults to false

        let prompt = ralph.build_prompt("", &[]);

        assert!(
            prompt.contains("### GUARDRAILS"),
            "Guardrails section should be present"
        );
    }

    // === Task Completion Verification Tests ===

    #[test]
    fn test_task_closure_verification_in_done_section() {
        // When memories/tasks mode is enabled, the DONE section should include
        // task verification requirements
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None)
            .with_memories_enabled(true);

        let prompt = ralph.build_prompt("", &[]);

        // The tasks CLI instructions are now injected via the skills pipeline,
        // but the DONE section still requires task verification before completion
        assert!(
            prompt.contains("ralph tools task list"),
            "Should reference task list command in DONE section"
        );
        assert!(
            prompt.contains("MUST NOT declare completion while tasks remain open"),
            "Should require tasks closed before completion"
        );
    }

    #[test]
    fn test_workflow_verify_and_commit_step() {
        // Solo mode with memories should have VERIFY & COMMIT step
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None)
            .with_memories_enabled(true);

        let prompt = ralph.build_prompt("", &[]);

        // Should have VERIFY & COMMIT step
        assert!(
            prompt.contains("### 4. VERIFY & COMMIT"),
            "Should have VERIFY & COMMIT step in workflow"
        );
        assert!(
            prompt.contains("run tests and verify"),
            "Should require verification"
        );
        assert!(
            prompt.contains("ralph tools task start"),
            "Should reference task start command"
        );
        assert!(
            prompt.contains("ralph tools task close"),
            "Should reference task close command"
        );
    }

    #[test]
    fn test_scratchpad_mode_still_has_commit_step() {
        // Scratchpad-only mode (no memories) should have COMMIT step
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        // memories_enabled defaults to false

        let prompt = ralph.build_prompt("", &[]);

        // Scratchpad mode uses different format - COMMIT step without task CLI
        assert!(
            prompt.contains("### 4. COMMIT"),
            "Should have COMMIT step in workflow"
        );
        assert!(
            prompt.contains("mark the task `[x]`"),
            "Should mark task in scratchpad"
        );
        // Scratchpad mode doesn't have the TASKS section
        assert!(
            !prompt.contains("### 0c. TASKS"),
            "Scratchpad mode should not have TASKS section"
        );
    }

    // === Objective Section Tests ===

    #[test]
    fn test_objective_section_present_with_set_objective() {
        // When objective is set via set_objective(), OBJECTIVE section should appear
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Implement user authentication with JWT tokens".to_string());

        let prompt = ralph.build_prompt("", &[]);

        assert!(
            prompt.contains("## OBJECTIVE"),
            "Should have OBJECTIVE section when objective is set"
        );
        assert!(
            prompt.contains("Implement user authentication with JWT tokens"),
            "OBJECTIVE should contain the original user prompt"
        );
        assert!(
            prompt.contains("This is your primary goal"),
            "OBJECTIVE should emphasize this is the primary goal"
        );
    }

    #[test]
    fn test_objective_reinforced_in_done_section() {
        // The objective should be restated in the DONE section (bookend pattern)
        // when Ralph is coordinating (no active hats)
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Fix the login bug in auth module".to_string());

        let prompt = ralph.build_prompt("", &[]);

        // Check DONE section contains objective reinforcement
        let done_pos = prompt.find("## DONE").expect("Should have DONE section");
        let after_done = &prompt[done_pos..];

        assert!(
            after_done.contains("Remember your objective"),
            "DONE section should remind about objective"
        );
        assert!(
            after_done.contains("Fix the login bug in auth module"),
            "DONE section should restate the objective"
        );
    }

    #[test]
    fn test_objective_appears_before_pending_events() {
        // OBJECTIVE should appear BEFORE PENDING EVENTS for prominence
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Build feature X".to_string());

        let context = "Event: task.start - Build feature X";
        let prompt = ralph.build_prompt(context, &[]);

        let objective_pos = prompt.find("## OBJECTIVE").expect("Should have OBJECTIVE");
        let events_pos = prompt
            .find("## PENDING EVENTS")
            .expect("Should have PENDING EVENTS");

        assert!(
            objective_pos < events_pos,
            "OBJECTIVE ({}) should appear before PENDING EVENTS ({})",
            objective_pos,
            events_pos
        );
    }

    #[test]
    fn test_no_objective_when_not_set() {
        // When no objective has been set, no OBJECTIVE section should appear
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let context = "Event: build.done - Build completed successfully";
        let prompt = ralph.build_prompt(context, &[]);

        assert!(
            !prompt.contains("## OBJECTIVE"),
            "Should NOT have OBJECTIVE section when objective not set"
        );
    }

    #[test]
    fn test_objective_set_correctly() {
        // Test that set_objective stores the objective and it appears in prompt
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Review this PR for security issues".to_string());

        let prompt = ralph.build_prompt("", &[]);

        assert!(
            prompt.contains("Review this PR for security issues"),
            "Should show the stored objective"
        );
    }

    #[test]
    fn test_objective_with_events_context() {
        // Objective should appear even when context has other events (not task.start)
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Implement feature Y".to_string());

        let context =
            "Event: build.done - Previous build succeeded\nEvent: test.passed - All tests green";
        let prompt = ralph.build_prompt(context, &[]);

        assert!(
            prompt.contains("## OBJECTIVE"),
            "Should have OBJECTIVE section"
        );
        assert!(
            prompt.contains("Implement feature Y"),
            "OBJECTIVE should contain the stored objective"
        );
    }

    #[test]
    fn test_done_section_without_objective() {
        // When no objective, DONE section should still work but without reinforcement
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("", &[]);

        assert!(prompt.contains("## DONE"), "Should have DONE section");
        assert!(
            prompt.contains("LOOP_COMPLETE"),
            "DONE should mention completion event"
        );
        assert!(
            prompt.contains("final non-empty line"),
            "Solo DONE section should require literal terminal output"
        );
        assert!(
            !prompt.contains("Remember your objective"),
            "Should NOT have objective reinforcement without objective"
        );
    }

    #[test]
    fn test_objective_persists_across_iterations() {
        // Objective is present in prompt even when context has no task.start event
        // (simulating iteration 2+ where the start event has been consumed)
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Build a REST API with authentication".to_string());

        // Simulate iteration 2: only non-start events present
        let context = "Event: build.done - Build completed";
        let prompt = ralph.build_prompt(context, &[]);

        assert!(
            prompt.contains("## OBJECTIVE"),
            "OBJECTIVE should persist even without task.start in context"
        );
        assert!(
            prompt.contains("Build a REST API with authentication"),
            "Stored objective should appear in later iterations"
        );
    }

    #[test]
    fn test_done_section_suppressed_when_hat_active() {
        // When active_hats is non-empty, prompt does NOT contain ## DONE
        let yaml = r#"
hats:
  builder:
    name: "Builder"
    triggers: ["build.task"]
    publishes: ["build.done"]
    instructions: "Build the code."
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Implement feature X".to_string());

        let builder = registry.get(&ralph_proto::HatId::new("builder")).unwrap();
        let prompt = ralph.build_prompt("Event: build.task - Do the build", &[builder]);

        assert!(
            !prompt.contains("## DONE"),
            "DONE section should be suppressed when a hat is active"
        );
        assert!(
            !prompt.contains("LOOP_COMPLETE"),
            "Completion promise should NOT appear when a hat is active"
        );
        // But objective should still be visible
        assert!(
            prompt.contains("## OBJECTIVE"),
            "OBJECTIVE should still appear even when hat is active"
        );
        assert!(
            prompt.contains("Implement feature X"),
            "Objective content should be visible to active hat"
        );
    }

    #[test]
    fn test_done_section_present_when_coordinating() {
        // When active_hats is empty, prompt contains ## DONE with objective reinforcement
        let yaml = r#"
hats:
  builder:
    name: "Builder"
    triggers: ["build.task"]
    publishes: ["build.done"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Complete the TDD cycle".to_string());

        // No active hats - Ralph is coordinating
        let prompt = ralph.build_prompt("Event: build.done - Build finished", &[]);

        assert!(
            prompt.contains("## DONE"),
            "DONE section should appear when Ralph is coordinating"
        );
        assert!(
            prompt.contains("LOOP_COMPLETE"),
            "Completion promise should appear when coordinating"
        );
        assert!(
            prompt.contains("via `ralph emit`"),
            "Coordinating DONE section should require explicit event emission"
        );
    }

    #[test]
    fn test_objective_in_done_section_when_coordinating() {
        // DONE section includes "Remember your objective" when Ralph is coordinating
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Deploy the application".to_string());

        let prompt = ralph.build_prompt("", &[]);

        let done_pos = prompt.find("## DONE").expect("Should have DONE section");
        let after_done = &prompt[done_pos..];

        assert!(
            after_done.contains("Remember your objective"),
            "DONE section should remind about objective when coordinating"
        );
        assert!(
            after_done.contains("Deploy the application"),
            "DONE section should contain the objective text"
        );
    }

    // === Event Publishing Guide Tests ===

    #[test]
    fn test_event_publishing_guide_with_receivers() {
        // When a hat publishes events and other hats receive them,
        // the guide should show who receives each event
        let yaml = r#"
hats:
  builder:
    name: "Builder"
    description: "Builds and tests code"
    triggers: ["build.task"]
    publishes: ["build.done", "build.blocked"]
  confessor:
    name: "Confessor"
    description: "Produces a ConfessionReport; rewarded for honesty"
    triggers: ["build.done"]
    publishes: ["confession.done"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        // Get the builder hat as active
        let builder = registry.get(&ralph_proto::HatId::new("builder")).unwrap();
        let prompt = ralph.build_prompt("[build.task] Build the feature", &[builder]);

        // Should include Event Publishing Guide
        assert!(
            prompt.contains("### Event Publishing Guide"),
            "Should include Event Publishing Guide section"
        );
        assert!(
            prompt.contains("When you publish:"),
            "Guide should explain what happens when publishing"
        );
        assert!(
            prompt.contains("You MUST use `ralph emit"),
            "Guide should require explicit event emission"
        );
        // build.done has a receiver (Confessor)
        assert!(
            prompt.contains("`build.done` → Received by: Confessor"),
            "Should show Confessor receives build.done"
        );
        assert!(
            prompt.contains("Produces a ConfessionReport; rewarded for honesty"),
            "Should include receiver's description"
        );
        // build.blocked has no receiver, so falls back to Ralph
        assert!(
            prompt.contains("`build.blocked` → Received by: Ralph (coordinates next steps)"),
            "Should show Ralph receives orphan events"
        );
    }

    #[test]
    fn test_event_publishing_guide_no_publishes() {
        // When a hat doesn't publish any events, no guide should appear
        let yaml = r#"
hats:
  observer:
    name: "Observer"
    description: "Only observes"
    triggers: ["events.*"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let observer = registry.get(&ralph_proto::HatId::new("observer")).unwrap();
        let prompt = ralph.build_prompt("[events.start] Start", &[observer]);

        // Should NOT include Event Publishing Guide
        assert!(
            !prompt.contains("### Event Publishing Guide"),
            "Should NOT include Event Publishing Guide when hat has no publishes"
        );
    }

    #[test]
    fn test_event_publishing_guide_all_orphan_events() {
        // When all published events have no receivers, all should show Ralph
        let yaml = r#"
hats:
  solo:
    name: "Solo"
    triggers: ["solo.start"]
    publishes: ["solo.done", "solo.failed"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let solo = registry.get(&ralph_proto::HatId::new("solo")).unwrap();
        let prompt = ralph.build_prompt("[solo.start] Go", &[solo]);

        assert!(
            prompt.contains("### Event Publishing Guide"),
            "Should include guide even for orphan events"
        );
        assert!(
            prompt.contains("`solo.done` → Received by: Ralph (coordinates next steps)"),
            "Orphan solo.done should go to Ralph"
        );
        assert!(
            prompt.contains("`solo.failed` → Received by: Ralph (coordinates next steps)"),
            "Orphan solo.failed should go to Ralph"
        );
    }

    #[test]
    fn test_event_publishing_guide_multiple_receivers() {
        // When an event has multiple receivers, all should be listed
        let yaml = r#"
hats:
  broadcaster:
    name: "Broadcaster"
    triggers: ["broadcast.start"]
    publishes: ["signal.sent"]
  listener1:
    name: "Listener1"
    description: "First listener"
    triggers: ["signal.sent"]
  listener2:
    name: "Listener2"
    description: "Second listener"
    triggers: ["signal.sent"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let broadcaster = registry
            .get(&ralph_proto::HatId::new("broadcaster"))
            .unwrap();
        let prompt = ralph.build_prompt("[broadcast.start] Go", &[broadcaster]);

        assert!(
            prompt.contains("### Event Publishing Guide"),
            "Should include guide"
        );
        // Both listeners should be mentioned (order may vary due to HashMap iteration)
        assert!(
            prompt.contains("Listener1 (First listener)"),
            "Should list Listener1 as receiver"
        );
        assert!(
            prompt.contains("Listener2 (Second listener)"),
            "Should list Listener2 as receiver"
        );
    }

    #[test]
    fn test_event_publishing_guide_includes_self() {
        // If a hat subscribes to its own event (self-loop), it should be listed as receiver
        let yaml = r#"
hats:
  looper:
    name: "Looper"
    triggers: ["loop.continue", "loop.start"]
    publishes: ["loop.continue"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let looper = registry.get(&ralph_proto::HatId::new("looper")).unwrap();
        let prompt = ralph.build_prompt("[loop.start] Start", &[looper]);

        assert!(
            prompt.contains("### Event Publishing Guide"),
            "Should include guide"
        );
        // Self-loop: looper publishes loop.continue and triggers on it
        assert!(
            prompt.contains("`loop.continue` → Received by: Looper"),
            "Self-loop event should show the hat itself as receiver"
        );
    }

    #[test]
    fn test_event_publishing_guide_self_loop_shows_self_as_receiver() {
        // When a hat publishes an event that it also triggers on (self-loop),
        // the guide should show the hat itself as the receiver, not "Ralph"
        let yaml = r#"
hats:
  processor:
    name: "Processor"
    description: "Processes work with retry"
    triggers: ["start", "process.retry"]
    publishes: ["process.done", "process.retry"]
  validator:
    name: "Validator"
    triggers: ["process.done"]
    publishes: ["validate.pass"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let processor = registry.get(&ralph_proto::HatId::new("processor")).unwrap();
        let prompt = ralph.build_prompt("[start] Go", &[processor]);

        // process.retry routes back to Processor itself — should say so
        assert!(
            prompt.contains("`process.retry` → Received by: Processor"),
            "Self-loop event should show the hat itself as receiver, not Ralph. Got:\n{}",
            prompt
                .lines()
                .filter(|l| l.contains("process.retry"))
                .collect::<Vec<_>>()
                .join("\n")
        );
        // process.done routes to Validator — should still work
        assert!(
            prompt.contains("`process.done` → Received by: Validator"),
            "Non-self event should still show correct receiver"
        );
    }

    #[test]
    fn test_event_publishing_guide_receiver_without_description() {
        // When a receiver has no description, just show the name
        let yaml = r#"
hats:
  sender:
    name: "Sender"
    triggers: ["send.start"]
    publishes: ["message.sent"]
  receiver:
    name: "NoDescReceiver"
    triggers: ["message.sent"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let sender = registry.get(&ralph_proto::HatId::new("sender")).unwrap();
        let prompt = ralph.build_prompt("[send.start] Go", &[sender]);

        assert!(
            prompt.contains("`message.sent` → Received by: NoDescReceiver"),
            "Should show receiver name without parentheses when no description"
        );
        // Should NOT have empty parentheses
        assert!(
            !prompt.contains("NoDescReceiver ()"),
            "Should NOT have empty parentheses for receiver without description"
        );
    }

    // === Event Publishing Constraint Tests ===

    #[test]
    fn test_constraint_lists_valid_events_when_coordinating() {
        // When Ralph is coordinating (no active hats), the prompt should include
        // a CONSTRAINT listing valid events to publish
        let yaml = r#"
hats:
  test_writer:
    name: "Test Writer"
    triggers: ["tdd.start"]
    publishes: ["test.written"]
  implementer:
    name: "Implementer"
    triggers: ["test.written"]
    publishes: ["test.passing"]
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        // No active hats - Ralph is coordinating
        let prompt = ralph.build_prompt("[task.start] Do TDD for feature X", &[]);

        // Should contain CONSTRAINT with valid events
        assert!(
            prompt.contains("**CONSTRAINT:**"),
            "Prompt should include CONSTRAINT when coordinating"
        );
        assert!(
            prompt.contains("tdd.start"),
            "CONSTRAINT should list tdd.start as valid event"
        );
        assert!(
            prompt.contains("test.written"),
            "CONSTRAINT should list test.written as valid event"
        );
        assert!(
            prompt.contains("Publishing other events will have no effect"),
            "CONSTRAINT should warn about invalid events"
        );
    }

    #[test]
    fn test_no_constraint_when_hat_is_active() {
        // When a hat is active, the CONSTRAINT should NOT appear
        // (the active hat has its own Event Publishing Guide)
        let yaml = r#"
hats:
  builder:
    name: "Builder"
    triggers: ["build.task"]
    publishes: ["build.done"]
    instructions: "Build the code."
"#;
        let config: RalphConfig = serde_yaml::from_str(yaml).unwrap();
        let registry = HatRegistry::from_config(&config);
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        // Builder hat is active
        let builder = registry.get(&ralph_proto::HatId::new("builder")).unwrap();
        let prompt = ralph.build_prompt("[build.task] Build feature X", &[builder]);

        // Should NOT contain the coordinating CONSTRAINT
        assert!(
            !prompt.contains("**CONSTRAINT:** You MUST only publish events from this list"),
            "Active hat should NOT have coordinating CONSTRAINT"
        );

        // Should have Event Publishing Guide instead
        assert!(
            prompt.contains("### Event Publishing Guide"),
            "Active hat should have Event Publishing Guide"
        );
    }

    #[test]
    fn test_no_constraint_when_no_hats() {
        // When there are no hats (solo mode), no CONSTRAINT should appear
        let config = RalphConfig::default();
        let registry = HatRegistry::new(); // Empty registry
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("[task.start] Do something", &[]);

        // Should NOT contain CONSTRAINT (no hats to coordinate)
        assert!(
            !prompt.contains("**CONSTRAINT:**"),
            "Solo mode should NOT have CONSTRAINT"
        );
    }

    // === Human Guidance Injection Tests ===

    #[test]
    fn test_single_guidance_injection() {
        // Single human.guidance message should be injected as-is (no numbered list)
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_robot_guidance(vec!["Focus on error handling first".to_string()]);

        let prompt = ralph.build_prompt("", &[]);

        assert!(
            prompt.contains("## ROBOT GUIDANCE"),
            "Should include ROBOT GUIDANCE section"
        );
        assert!(
            prompt.contains("Focus on error handling first"),
            "Should contain the guidance message"
        );
        // Single message should NOT be numbered
        assert!(
            !prompt.contains("1. Focus on error handling first"),
            "Single guidance should not be numbered"
        );
    }

    #[test]
    fn test_multiple_guidance_squashing() {
        // Multiple human.guidance messages should be squashed into a numbered list
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_robot_guidance(vec![
            "Focus on error handling".to_string(),
            "Use the existing retry pattern".to_string(),
            "Check edge cases for empty input".to_string(),
        ]);

        let prompt = ralph.build_prompt("", &[]);

        assert!(
            prompt.contains("## ROBOT GUIDANCE"),
            "Should include ROBOT GUIDANCE section"
        );
        assert!(
            prompt.contains("1. Focus on error handling"),
            "First guidance should be numbered 1"
        );
        assert!(
            prompt.contains("2. Use the existing retry pattern"),
            "Second guidance should be numbered 2"
        );
        assert!(
            prompt.contains("3. Check edge cases for empty input"),
            "Third guidance should be numbered 3"
        );
    }

    #[test]
    fn test_guidance_appears_in_prompt_before_events() {
        // ROBOT GUIDANCE should appear after OBJECTIVE but before PENDING EVENTS
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_objective("Build feature X".to_string());
        ralph.set_robot_guidance(vec!["Use the new API".to_string()]);

        let prompt = ralph.build_prompt("Event: build.task - Do the work", &[]);

        let objective_pos = prompt.find("## OBJECTIVE").expect("Should have OBJECTIVE");
        let guidance_pos = prompt
            .find("## ROBOT GUIDANCE")
            .expect("Should have ROBOT GUIDANCE");
        let events_pos = prompt
            .find("## PENDING EVENTS")
            .expect("Should have PENDING EVENTS");

        assert!(
            objective_pos < guidance_pos,
            "OBJECTIVE ({}) should come before ROBOT GUIDANCE ({})",
            objective_pos,
            guidance_pos
        );
        assert!(
            guidance_pos < events_pos,
            "ROBOT GUIDANCE ({}) should come before PENDING EVENTS ({})",
            guidance_pos,
            events_pos
        );
    }

    #[test]
    fn test_guidance_cleared_after_injection() {
        // After build_prompt consumes guidance, clear_robot_guidance should leave it empty
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let mut ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);
        ralph.set_robot_guidance(vec!["First guidance".to_string()]);

        // First prompt should include guidance
        let prompt1 = ralph.build_prompt("", &[]);
        assert!(
            prompt1.contains("## ROBOT GUIDANCE"),
            "First prompt should have guidance"
        );

        // Clear guidance (as EventLoop would)
        ralph.clear_robot_guidance();

        // Second prompt should NOT include guidance
        let prompt2 = ralph.build_prompt("", &[]);
        assert!(
            !prompt2.contains("## ROBOT GUIDANCE"),
            "After clearing, prompt should not have guidance"
        );
    }

    #[test]
    fn test_no_injection_when_no_guidance() {
        // When no guidance events, prompt should not have ROBOT GUIDANCE section
        let config = RalphConfig::default();
        let registry = HatRegistry::new();
        let ralph = HatlessRalph::new("LOOP_COMPLETE", config.core.clone(), &registry, None);

        let prompt = ralph.build_prompt("Event: build.task - Do the work", &[]);

        assert!(
            !prompt.contains("## ROBOT GUIDANCE"),
            "Should NOT include ROBOT GUIDANCE when no guidance set"
        );
    }
}