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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
# Reachy Tales Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Reboot the AI_game story project as a Reachy Mini JS app with a clean two-package layout β€” `story-engine` library + HF Space β€” shipping the translated `story_pirates` end-to-end in English with embodied audio narration.

**Architecture:** Pure TypeScript `story-engine` library (no DOM / robot / LLM deps) lives at `packages/story-engine/`. JS HF Space app at repo root copies plumbing from `tfrere/reachy-mini-minimal-js-conversation-app` and wires the engine into OpenAI Realtime via a new `src/story-bridge.ts` module. State-in-instructions pattern with regenerated tool defs per transition. Voice swap on character change via OpenAI Realtime session restart with a gpt-4o-mini-generated context summary.

**Tech Stack:** TypeScript, npm workspaces, Vite 5, Vitest, OpenAI Realtime API + chat-completions, Reachy Mini JS SDK (jsDelivr CDN), Docker + nginx, Hugging Face Spaces (static-Docker).

**Source spec:** [`docs/superpowers/specs/2026-04-29-reachy-tales-design.md`](../specs/2026-04-29-reachy-tales-design.md) (in this `AI_game/` directory).

**Reference materials to fetch as needed:**
- Reachy Mini JS SDK: `https://github.com/pollen-robotics/reachy_mini` (branch `feat/ehance-js-lib`), file `js/reachy-mini.js`.
- Reference JS conversation app: `https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app` (raw files at `https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app/raw/main/<path>`).
- Original story content: `/Users/nicolasrabault/Projects/AI_game/Stories/story_pirates/` and `/Users/nicolasrabault/Projects/AI_game/Stories/narrator/`.

**Repo location target:** `/Users/nicolasrabault/Projects/reachy-tales/` (create at start of plan).

---

## Phase 1 β€” Repo bootstrap

### Task 1: Create the repo and workspace skeleton

**Files:**
- Create: `/Users/nicolasrabault/Projects/reachy-tales/.gitignore`
- Create: `/Users/nicolasrabault/Projects/reachy-tales/package.json`
- Create: `/Users/nicolasrabault/Projects/reachy-tales/tsconfig.base.json`
- Create: `/Users/nicolasrabault/Projects/reachy-tales/README.md`

- [ ] **Step 1: Create directory and init git**

```bash
mkdir -p /Users/nicolasrabault/Projects/reachy-tales
cd /Users/nicolasrabault/Projects/reachy-tales
git init
```

- [ ] **Step 2: Write `.gitignore`**

```
node_modules/
dist/
*.log
.DS_Store
.env
.env.local
.vite/
coverage/
```

- [ ] **Step 3: Write root `package.json`**

```json
{
  "name": "reachy-tales",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "dev": "vite",
    "build": "tsc -p tsconfig.app.json --noEmit && vite build",
    "preview": "vite preview",
    "test": "npm run test --workspaces --if-present"
  },
  "devDependencies": {
    "typescript": "^5.6.3",
    "vite": "^5.4.10"
  }
}
```

- [ ] **Step 4: Write `tsconfig.base.json`**

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true
  }
}
```

- [ ] **Step 5: Write a minimal root `README.md`** (HF Space frontmatter comes later when we deploy)

```markdown
# Reachy Tales

Voice-driven story adventures, narrated by your Reachy Mini.

See [design spec](docs/superpowers/specs/2026-04-29-reachy-tales-design.md).
```

- [ ] **Step 6: Initial commit**

```bash
git add .gitignore package.json tsconfig.base.json README.md
git commit -m "chore: bootstrap reachy-tales workspace"
```

---

### Task 2: Scaffold the `story-engine` package

**Files:**
- Create: `packages/story-engine/package.json`
- Create: `packages/story-engine/tsconfig.json`
- Create: `packages/story-engine/vitest.config.ts`
- Create: `packages/story-engine/src/index.ts`

- [ ] **Step 1: Create the package directory tree**

```bash
mkdir -p packages/story-engine/src packages/story-engine/tests
```

- [ ] **Step 2: Write `packages/story-engine/package.json`**

```json
{
  "name": "story-engine",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "main": "./src/index.ts",
  "exports": {
    ".": "./src/index.ts"
  },
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest"
  },
  "devDependencies": {
    "vitest": "^2.1.0"
  }
}
```

- [ ] **Step 3: Write `packages/story-engine/tsconfig.json`**

```json
{
  "extends": "../../tsconfig.base.json",
  "include": ["src/**/*", "tests/**/*"]
}
```

- [ ] **Step 4: Write `packages/story-engine/vitest.config.ts`**

```typescript
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    include: ["tests/**/*.test.ts"],
    environment: "node",
  },
});
```

- [ ] **Step 5: Write a placeholder `packages/story-engine/src/index.ts`** (kept minimal so npm install + initial test works)

```typescript
export const ENGINE_VERSION = "0.1.0";
```

- [ ] **Step 6: Install workspace deps**

```bash
cd /Users/nicolasrabault/Projects/reachy-tales
npm install
```

Expected: `node_modules/` created, `package-lock.json` written, `story-engine` symlinked from `node_modules/story-engine`.

- [ ] **Step 7: Verify Vitest runs (with no tests)**

```bash
npm test --workspace story-engine
```

Expected: "No test files found" β€” exits 0 with `--passWithNoTests`? If exits non-zero, add `--passWithNoTests` to the script. Update `package.json` test script if needed:

```json
    "test": "vitest run --passWithNoTests"
```

- [ ] **Step 8: Commit**

```bash
git add package-lock.json packages/
git commit -m "chore: scaffold story-engine package"
```

---

## Phase 2 β€” Engine library

### Task 3: Engine types

**Files:**
- Create: `packages/story-engine/src/types.ts`

- [ ] **Step 1: Write `types.ts`** β€” the full data model. No tests yet (types only); they become testable when we use them in the loader.

```typescript
// ─── Loaded data (immutable after load) ──────────────────────────────────

export interface Narrator {
  id: "narrator";              // sentinel id for the global narrator
  name: string;
  description: string;
  introduction: string;
  background: string;
  goal: string;
  voice: string;               // OpenAI Realtime voice preset name
  voiceTone: string;
}

export interface Character {
  id: string;                  // derived from filename stem (e.g. "sparrow")
  name: string;
  description: string;
  introduction: string;
  background: string;
  goal: string;
  voice: string;               // OpenAI Realtime voice preset name
  voiceTone: string;
}

export interface SceneAction {
  id: string;
  description: string;
  effects: string;             // narrative description, no flag effects
}

export interface Scene {
  id: string;                  // derived from filename stem
  name: string;
  description: string;
  actions: SceneAction[];      // atmospheric actions
  charactersPresent: string[]; // character ids
}

export interface StorylineActionEffects {
  setFlags?: Record<string, boolean>;
}

export interface StorylineAction {
  id: string;
  description: string;
  next?: string;               // next storyline node id
  effects?: StorylineActionEffects;
}

export type StorylineType = "dialogue" | "narration" | "character_interaction";

export interface StorylineNode {
  id: string;
  scene: string;               // scene id
  type: StorylineType;
  speaker: string;             // character id, "narrator", or empty string
  text: string;
  actions: StorylineAction[];
}

export interface FlagCondition {
  type: "requires_flag";
  flag: string;
  conditionFailed: string;     // explanation if blocked
}

export interface MapEdge {
  from: string;                // scene id
  to: string;                  // scene id
  description: string;
  conditions?: FlagCondition[];
}

export interface Story {
  id: string;
  title: string;
  description: string;
  languages: string[];
  entryPoint: string;          // path relative to story root, e.g. "storylines/chapter1/meet_sparrow.json"
  narrator: Character | Narrator;  // story-specific or global
  characters: Record<string, Character>;
  scenes: Record<string, Scene>;
  storylines: Record<string, StorylineNode>;
  map: MapEdge[];
  flags: string[];             // declared flag names (flat array)
}

export interface LoadedContent {
  narrator: Narrator;          // global menu narrator
  stories: Record<string, Story>;
}

// ─── Mutable state ────────────────────────────────────────────────────────

export type AppMode = "menu" | "story";

export interface GameState {
  mode: AppMode;
  storyId?: string;
  currentSceneId?: string;
  currentNodeId?: string;
  currentSpeaker?: string;     // character id, or "narrator"
  flags: Record<string, boolean>;
  discoveredScenes: string[];
  metCharacters: string[];
  recentTransitions: TransitionEvent[];  // bounded log for summary builder
}

// ─── Transition events ────────────────────────────────────────────────────

export type TransitionEvent =
  | { type: "speakerChanged"; from?: string; to: string;
      newCharacter: Character | Narrator }
  | { type: "sceneChanged"; from?: string; to: string }
  | { type: "storyEntered"; storyId: string }
  | { type: "storyExited" }
  | { type: "flagSet"; name: string; value: boolean }
  | { type: "blocked"; reason: string };

export interface TransitionResult {
  state: Readonly<GameState>;
  events: TransitionEvent[];
}

// ─── Tool definitions for OpenAI Realtime ─────────────────────────────────

export interface ToolDef {
  name: string;
  description: string;
  parameters: {
    type: "object";
    properties: Record<string, unknown>;
    required: string[];
  };
}
```

- [ ] **Step 2: Verify it type-checks**

```bash
cd /Users/nicolasrabault/Projects/reachy-tales/packages/story-engine
npx tsc --noEmit
```

Expected: no errors.

- [ ] **Step 3: Commit**

```bash
git add packages/story-engine/src/types.ts
git commit -m "feat(engine): define core types for story data and game state"
```

---

### Task 4: Engine loader β€” narrator only (test-first)

**Files:**
- Create: `packages/story-engine/src/loader.ts`
- Create: `packages/story-engine/tests/loader.test.ts`
- Create: `packages/story-engine/tests/fixtures/narrator/narrator.json`

The loader will eventually load from a Vite-bundled `content/` directory via dynamic JSON imports, but for testability we make it accept arbitrary JSON objects. We'll test against fixture JSON written here, then use the same loader in the app with bundled content.

- [ ] **Step 1: Write test fixture** β€” a minimal narrator JSON

`packages/story-engine/tests/fixtures/narrator/narrator.json`:

```json
{
  "name": "The Narrator",
  "description": "A cheerful storyteller",
  "introduction": "Welcome adventurer!",
  "background": "An entity who guides players through stories.",
  "goal": "Help the player pick a story.",
  "voice": "cedar",
  "voice_tone": "Warm, enthusiastic, brief."
}
```

- [ ] **Step 2: Write the failing test**

`packages/story-engine/tests/loader.test.ts`:

```typescript
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { loadNarrator } from "../src/loader.js";

const narratorJson = JSON.parse(
  readFileSync(resolve(__dirname, "fixtures/narrator/narrator.json"), "utf-8"),
);

describe("loadNarrator", () => {
  it("normalizes a narrator JSON into the Narrator type", () => {
    const narrator = loadNarrator(narratorJson);
    expect(narrator.id).toBe("narrator");
    expect(narrator.name).toBe("The Narrator");
    expect(narrator.voice).toBe("cedar");
    expect(narrator.voiceTone).toBe("Warm, enthusiastic, brief.");
  });
});
```

- [ ] **Step 3: Run the test to confirm it fails**

```bash
cd /Users/nicolasrabault/Projects/reachy-tales
npm test --workspace story-engine
```

Expected: FAIL β€” `loadNarrator` not exported.

- [ ] **Step 4: Implement `loader.ts`** with just `loadNarrator`

`packages/story-engine/src/loader.ts`:

```typescript
import type { Narrator } from "./types.js";

interface RawNarrator {
  name: string;
  description: string;
  introduction: string;
  background: string;
  goal: string;
  voice: string;
  voice_tone: string;
  // legacy fields ignored: picture, tools, etc.
}

export function loadNarrator(raw: unknown): Narrator {
  const r = raw as RawNarrator;
  if (!r || typeof r !== "object") {
    throw new Error("Narrator JSON must be an object");
  }
  for (const field of ["name", "description", "introduction", "background", "goal", "voice", "voice_tone"] as const) {
    if (typeof r[field] !== "string" || !r[field]) {
      throw new Error(`Narrator missing required string field: ${field}`);
    }
  }
  return {
    id: "narrator",
    name: r.name,
    description: r.description,
    introduction: r.introduction,
    background: r.background,
    goal: r.goal,
    voice: r.voice,
    voiceTone: r.voice_tone,
  };
}
```

- [ ] **Step 5: Run the test, confirm it passes**

```bash
npm test --workspace story-engine
```

Expected: PASS.

- [ ] **Step 6: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): loader for narrator JSON"
```

---

### Task 5: Engine loader β€” character + scene + storyline node

**Files:**
- Modify: `packages/story-engine/src/loader.ts`
- Modify: `packages/story-engine/tests/loader.test.ts`
- Create: `packages/story-engine/tests/fixtures/story_test/characters/sparrow.json`
- Create: `packages/story-engine/tests/fixtures/story_test/scenes/tavern.json`
- Create: `packages/story-engine/tests/fixtures/story_test/storylines/chapter1/meet_sparrow.json`

- [ ] **Step 1: Write fixtures**

`packages/story-engine/tests/fixtures/story_test/characters/sparrow.json`:

```json
{
  "name": "Sparrow",
  "description": "A ruthless pirate captain.",
  "introduction": "Captain Sparrow at your service.",
  "background": "Notorious pirate of the seven seas.",
  "goal": "Amass wealth through piracy.",
  "voice": "ash",
  "voice_tone": "Deep, raspy, threatening but conversational."
}
```

`packages/story-engine/tests/fixtures/story_test/scenes/tavern.json`:

```json
{
  "name": "The Rusty Anchor Tavern",
  "description": "A dimly lit tavern, thick with pipe smoke.",
  "actions": [
    {
      "id": "examine_memorabilia",
      "description": "examine the nautical memorabilia",
      "effects": "the user examines old maps and rusted cutlasses on the walls."
    }
  ],
  "characters_present": ["Sparrow"],
  "picture": "tavern.png"
}
```

`packages/story-engine/tests/fixtures/story_test/storylines/chapter1/meet_sparrow.json`:

```json
{
  "id": "meet_sparrow",
  "scene": "tavern",
  "type": "dialogue",
  "speaker": "Sparrow",
  "text": "Captain Sparrow at your service. Friend or foe?",
  "actions": [
    {
      "id": "greet_respectfully",
      "next": "friendly_response",
      "effects": { "set_flags": { "trust_sparrow": true } },
      "description": "Show respect to the captain"
    },
    {
      "id": "mock_sparrow",
      "next": "hostile_response",
      "effects": { "set_flags": { "trust_sparrow": false } },
      "description": "Mock the so-called captain"
    }
  ]
}
```

- [ ] **Step 2: Add failing tests for each loader**

Append to `packages/story-engine/tests/loader.test.ts`:

```typescript
import { loadCharacter, loadScene, loadStorylineNode } from "../src/loader.js";

const sparrowJson = JSON.parse(readFileSync(resolve(__dirname, "fixtures/story_test/characters/sparrow.json"), "utf-8"));
const tavernJson = JSON.parse(readFileSync(resolve(__dirname, "fixtures/story_test/scenes/tavern.json"), "utf-8"));
const meetSparrowJson = JSON.parse(readFileSync(resolve(__dirname, "fixtures/story_test/storylines/chapter1/meet_sparrow.json"), "utf-8"));

describe("loadCharacter", () => {
  it("normalizes a character JSON, deriving id from filename", () => {
    const c = loadCharacter("sparrow", sparrowJson);
    expect(c.id).toBe("sparrow");
    expect(c.name).toBe("Sparrow");
    expect(c.voice).toBe("ash");
    expect(c.voiceTone).toBe("Deep, raspy, threatening but conversational.");
  });
});

describe("loadScene", () => {
  it("normalizes a scene JSON, deriving id from filename", () => {
    const s = loadScene("tavern", tavernJson);
    expect(s.id).toBe("tavern");
    expect(s.name).toBe("The Rusty Anchor Tavern");
    expect(s.actions).toHaveLength(1);
    expect(s.actions[0]!.id).toBe("examine_memorabilia");
    expect(s.charactersPresent).toEqual(["Sparrow"]);
  });
});

describe("loadStorylineNode", () => {
  it("normalizes a storyline node, mapping set_flags β†’ setFlags", () => {
    const n = loadStorylineNode(meetSparrowJson);
    expect(n.id).toBe("meet_sparrow");
    expect(n.speaker).toBe("Sparrow");
    expect(n.actions).toHaveLength(2);
    expect(n.actions[0]!.id).toBe("greet_respectfully");
    expect(n.actions[0]!.next).toBe("friendly_response");
    expect(n.actions[0]!.effects?.setFlags).toEqual({ trust_sparrow: true });
  });
});
```

- [ ] **Step 3: Run tests to confirm they fail**

```bash
npm test --workspace story-engine
```

Expected: FAIL β€” functions not exported.

- [ ] **Step 4: Implement the three loaders** β€” append to `packages/story-engine/src/loader.ts`:

```typescript
import type { Character, Scene, SceneAction, StorylineAction, StorylineNode, StorylineType } from "./types.js";

interface RawCharacter {
  name: string;
  description: string;
  introduction: string;
  background: string;
  goal: string;
  voice: string;
  voice_tone: string;
}

export function loadCharacter(id: string, raw: unknown): Character {
  const r = raw as RawCharacter;
  if (!r || typeof r !== "object") throw new Error(`Character ${id}: not an object`);
  for (const field of ["name", "description", "introduction", "background", "goal", "voice", "voice_tone"] as const) {
    if (typeof r[field] !== "string" || !r[field]) {
      throw new Error(`Character ${id} missing required string field: ${field}`);
    }
  }
  return {
    id,
    name: r.name,
    description: r.description,
    introduction: r.introduction,
    background: r.background,
    goal: r.goal,
    voice: r.voice,
    voiceTone: r.voice_tone,
  };
}

interface RawSceneAction {
  id: string;
  description: string;
  effects: string;
}
interface RawScene {
  name: string;
  description: string;
  actions: RawSceneAction[];
  characters_present: string[];
}

export function loadScene(id: string, raw: unknown): Scene {
  const r = raw as RawScene;
  if (!r || typeof r !== "object") throw new Error(`Scene ${id}: not an object`);
  if (typeof r.name !== "string" || typeof r.description !== "string") {
    throw new Error(`Scene ${id} missing name/description`);
  }
  if (!Array.isArray(r.actions)) throw new Error(`Scene ${id}: actions must be an array`);
  if (!Array.isArray(r.characters_present)) throw new Error(`Scene ${id}: characters_present must be an array`);
  const actions: SceneAction[] = r.actions.map((a, i) => {
    if (typeof a.id !== "string" || typeof a.description !== "string" || typeof a.effects !== "string") {
      throw new Error(`Scene ${id} action[${i}]: missing id/description/effects`);
    }
    return { id: a.id, description: a.description, effects: a.effects };
  });
  return {
    id,
    name: r.name,
    description: r.description,
    actions,
    charactersPresent: r.characters_present,
  };
}

interface RawStorylineAction {
  id: string;
  description: string;
  next?: string;
  effects?: { set_flags?: Record<string, boolean> };
}
interface RawStorylineNode {
  id: string;
  scene: string;
  type: string;
  speaker: string;
  text: string;
  actions: RawStorylineAction[];
}

export function loadStorylineNode(raw: unknown): StorylineNode {
  const r = raw as RawStorylineNode;
  if (!r || typeof r !== "object") throw new Error("Storyline node: not an object");
  for (const field of ["id", "scene", "type", "speaker", "text"] as const) {
    if (typeof r[field] !== "string") throw new Error(`Storyline ${r.id ?? "?"} missing field: ${field}`);
  }
  if (!["dialogue", "narration", "character_interaction"].includes(r.type)) {
    throw new Error(`Storyline ${r.id}: unknown type "${r.type}"`);
  }
  if (!Array.isArray(r.actions)) throw new Error(`Storyline ${r.id}: actions must be an array`);
  const actions: StorylineAction[] = r.actions.map((a, i) => {
    if (typeof a.id !== "string" || typeof a.description !== "string") {
      throw new Error(`Storyline ${r.id} action[${i}]: missing id/description`);
    }
    return {
      id: a.id,
      description: a.description,
      next: a.next,
      effects: a.effects?.set_flags ? { setFlags: a.effects.set_flags } : undefined,
    };
  });
  return {
    id: r.id,
    scene: r.scene,
    type: r.type as StorylineType,
    speaker: r.speaker,
    text: r.text,
    actions,
  };
}
```

- [ ] **Step 5: Run tests, confirm they pass**

```bash
npm test --workspace story-engine
```

Expected: PASS (4 tests total now).

- [ ] **Step 6: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): loaders for character, scene, storyline node"
```

---

### Task 6: Engine loader β€” map edges, flags, story manifest, full story

**Files:**
- Modify: `packages/story-engine/src/loader.ts`
- Modify: `packages/story-engine/tests/loader.test.ts`
- Create: `packages/story-engine/tests/fixtures/story_test/manifest.json`
- Create: `packages/story-engine/tests/fixtures/story_test/map.json`
- Create: `packages/story-engine/tests/fixtures/story_test/flags.json`
- Create: `packages/story-engine/tests/fixtures/story_test/storylines/chapter1/friendly_response.json`
- Create: `packages/story-engine/tests/fixtures/story_test/storylines/chapter1/hostile_response.json`
- Create: `packages/story-engine/tests/fixtures/story_test/scenes/harbor.json`

- [ ] **Step 1: Write manifest, map, flags fixtures**

`packages/story-engine/tests/fixtures/story_test/manifest.json`:

```json
{
  "id": "story_test",
  "title": "Test Story",
  "description": "A short test story.",
  "languages": ["en"],
  "entry_point": "storylines/chapter1/meet_sparrow.json",
  "narrator": {
    "name": "Test Narrator",
    "description": "story-specific narrator",
    "introduction": "Ahoy!",
    "background": "Pirate storyteller.",
    "goal": "Tell the pirate tale.",
    "voice": "ballad",
    "voice_tone": "Salty and brief."
  }
}
```

`packages/story-engine/tests/fixtures/story_test/map.json`:

```json
[
  {
    "from": "tavern",
    "to": "harbor",
    "description": "Head to the harbor"
  },
  {
    "from": "harbor",
    "to": "tavern",
    "description": "Return to the tavern"
  },
  {
    "from": "tavern",
    "to": "docks",
    "description": "Sneak to the docks",
    "conditions": [
      {
        "type": "requires_flag",
        "flag": "trust_sparrow",
        "condition_failed": "You don't trust him enough to follow yet."
      }
    ]
  }
]
```

`packages/story-engine/tests/fixtures/story_test/flags.json`:

```json
["trust_sparrow", "found_treasure"]
```

`packages/story-engine/tests/fixtures/story_test/storylines/chapter1/friendly_response.json`:

```json
{
  "id": "friendly_response",
  "scene": "tavern",
  "type": "dialogue",
  "speaker": "Sparrow",
  "text": "Aye, that's the spirit!",
  "actions": []
}
```

`packages/story-engine/tests/fixtures/story_test/storylines/chapter1/hostile_response.json`:

```json
{
  "id": "hostile_response",
  "scene": "tavern",
  "type": "dialogue",
  "speaker": "Sparrow",
  "text": "Bold of you, scallywag!",
  "actions": []
}
```

`packages/story-engine/tests/fixtures/story_test/scenes/harbor.json`:

```json
{
  "name": "Port Royal Harbor",
  "description": "A bustling harbor smelling of salt and tar.",
  "actions": [],
  "characters_present": []
}
```

- [ ] **Step 2: Write failing tests for `loadStory` and `loadMapEdges`** β€” append:

```typescript
import { loadStory, loadMapEdges, loadFlags } from "../src/loader.js";
import { readdirSync } from "node:fs";

const STORY_FIXTURE_DIR = resolve(__dirname, "fixtures/story_test");

function readJsonFile(path: string): unknown {
  return JSON.parse(readFileSync(path, "utf-8"));
}

function readJsonDir(dir: string): Record<string, unknown> {
  const result: Record<string, unknown> = {};
  for (const file of readdirSync(dir)) {
    if (!file.endsWith(".json")) continue;
    const id = file.replace(/\.json$/, "");
    result[id] = readJsonFile(resolve(dir, file));
  }
  return result;
}

describe("loadFlags", () => {
  it("loads a flat array of flag names", () => {
    const flags = loadFlags(readJsonFile(resolve(STORY_FIXTURE_DIR, "flags.json")));
    expect(flags).toEqual(["trust_sparrow", "found_treasure"]);
  });
});

describe("loadMapEdges", () => {
  it("normalizes map edges, mapping condition_failed β†’ conditionFailed", () => {
    const edges = loadMapEdges(readJsonFile(resolve(STORY_FIXTURE_DIR, "map.json")));
    expect(edges).toHaveLength(3);
    expect(edges[2]!.conditions).toEqual([
      { type: "requires_flag", flag: "trust_sparrow", conditionFailed: "You don't trust him enough to follow yet." },
    ]);
  });
});

describe("loadStory", () => {
  it("loads a complete story from raw inputs", () => {
    const story = loadStory({
      manifest: readJsonFile(resolve(STORY_FIXTURE_DIR, "manifest.json")),
      map: readJsonFile(resolve(STORY_FIXTURE_DIR, "map.json")),
      flags: readJsonFile(resolve(STORY_FIXTURE_DIR, "flags.json")),
      characters: readJsonDir(resolve(STORY_FIXTURE_DIR, "characters")),
      scenes: readJsonDir(resolve(STORY_FIXTURE_DIR, "scenes")),
      storylines: readJsonDir(resolve(STORY_FIXTURE_DIR, "storylines/chapter1")),
    });
    expect(story.id).toBe("story_test");
    expect(story.title).toBe("Test Story");
    expect(story.entryPoint).toBe("storylines/chapter1/meet_sparrow.json");
    expect(Object.keys(story.characters)).toContain("sparrow");
    expect(Object.keys(story.scenes)).toEqual(expect.arrayContaining(["tavern", "harbor"]));
    expect(Object.keys(story.storylines)).toContain("meet_sparrow");
    expect(story.map).toHaveLength(3);
    expect(story.flags).toEqual(["trust_sparrow", "found_treasure"]);
    expect(story.narrator.voice).toBe("ballad");
  });

  it("validates that storyline.scene refers to a real scene", () => {
    expect(() =>
      loadStory({
        manifest: readJsonFile(resolve(STORY_FIXTURE_DIR, "manifest.json")),
        map: [],
        flags: [],
        characters: {},
        scenes: { tavern: readJsonFile(resolve(STORY_FIXTURE_DIR, "scenes/tavern.json")) },
        storylines: { bad_node: { id: "bad_node", scene: "nonexistent", type: "dialogue", speaker: "x", text: "y", actions: [] } },
      })
    ).toThrow(/scene "nonexistent"/);
  });

  it("validates that action.next refers to a real storyline node", () => {
    expect(() =>
      loadStory({
        manifest: readJsonFile(resolve(STORY_FIXTURE_DIR, "manifest.json")),
        map: [],
        flags: [],
        characters: {},
        scenes: { tavern: readJsonFile(resolve(STORY_FIXTURE_DIR, "scenes/tavern.json")) },
        storylines: {
          a: { id: "a", scene: "tavern", type: "dialogue", speaker: "x", text: "y",
               actions: [{ id: "go", description: "go", next: "missing" }] },
        },
      })
    ).toThrow(/storyline "missing"/);
  });
});
```

- [ ] **Step 3: Run tests β€” expected to fail**

```bash
npm test --workspace story-engine
```

Expected: FAIL β€” `loadStory`, `loadMapEdges`, `loadFlags` not exported.

- [ ] **Step 4: Implement the new loaders** β€” append to `packages/story-engine/src/loader.ts`:

```typescript
import type { MapEdge, FlagCondition, Story } from "./types.js";

interface RawCondition {
  type: string;
  flag: string;
  condition_failed: string;
}

interface RawMapEdge {
  from: string;
  to: string;
  description: string;
  conditions?: RawCondition[];
}

export function loadMapEdges(raw: unknown): MapEdge[] {
  if (!Array.isArray(raw)) throw new Error("map.json must be an array");
  return raw.map((e: RawMapEdge, i) => {
    if (typeof e.from !== "string" || typeof e.to !== "string" || typeof e.description !== "string") {
      throw new Error(`Map edge[${i}]: missing from/to/description`);
    }
    const conditions: FlagCondition[] | undefined = e.conditions?.map((c, j) => {
      if (c.type !== "requires_flag" || typeof c.flag !== "string" || typeof c.condition_failed !== "string") {
        throw new Error(`Map edge[${i}] condition[${j}]: invalid`);
      }
      return { type: "requires_flag", flag: c.flag, conditionFailed: c.condition_failed };
    });
    return { from: e.from, to: e.to, description: e.description, conditions };
  });
}

export function loadFlags(raw: unknown): string[] {
  if (!Array.isArray(raw)) throw new Error("flags.json must be an array of strings");
  for (const f of raw) {
    if (typeof f !== "string") throw new Error("flags.json: every entry must be a string");
  }
  return raw as string[];
}

interface RawManifest {
  id: string;
  title: string;
  description: string;
  languages: string[];
  entry_point: string;
  narrator: RawCharacter;
}

export interface StoryRawInputs {
  manifest: unknown;
  map: unknown;
  flags: unknown;
  characters: Record<string, unknown>;   // id β†’ raw character JSON
  scenes: Record<string, unknown>;       // id β†’ raw scene JSON
  storylines: Record<string, unknown>;   // id β†’ raw storyline node JSON
}

export function loadStory(inputs: StoryRawInputs): Story {
  const m = inputs.manifest as RawManifest;
  if (!m || typeof m !== "object") throw new Error("manifest.json: not an object");
  for (const field of ["id", "title", "description", "entry_point"] as const) {
    if (typeof m[field] !== "string" || !m[field]) {
      throw new Error(`manifest missing required field: ${field}`);
    }
  }
  if (!Array.isArray(m.languages)) throw new Error("manifest.languages must be an array");

  // Story-specific narrator: load as Character (same shape) but flag the id as "narrator"
  const rawNarr = m.narrator;
  const narrator: Character = loadCharacter("narrator", rawNarr);

  const characters: Record<string, Character> = {};
  for (const [id, raw] of Object.entries(inputs.characters)) {
    characters[id] = loadCharacter(id, raw);
  }

  const scenes: Record<string, import("./types.js").Scene> = {};
  for (const [id, raw] of Object.entries(inputs.scenes)) {
    scenes[id] = loadScene(id, raw);
  }

  const storylines: Record<string, StorylineNode> = {};
  for (const [_, raw] of Object.entries(inputs.storylines)) {
    const node = loadStorylineNode(raw);
    storylines[node.id] = node;
  }

  const map = loadMapEdges(inputs.map);
  const flags = loadFlags(inputs.flags);

  // Reference integrity checks
  for (const node of Object.values(storylines)) {
    if (!scenes[node.scene]) {
      throw new Error(`Storyline "${node.id}" references unknown scene "${node.scene}"`);
    }
    for (const action of node.actions) {
      if (action.next !== undefined && !storylines[action.next]) {
        throw new Error(`Storyline "${node.id}" action "${action.id}" references unknown storyline "${action.next}"`);
      }
    }
  }
  for (const edge of map) {
    if (!scenes[edge.from]) throw new Error(`Map edge: from-scene "${edge.from}" not found`);
    if (!scenes[edge.to]) throw new Error(`Map edge: to-scene "${edge.to}" not found`);
  }
  for (const scene of Object.values(scenes)) {
    for (const cp of scene.charactersPresent) {
      // characters_present can use either id or display name in legacy data; we accept either
      const knownIds = new Set(Object.keys(characters));
      const knownNames = new Set(Object.values(characters).map((c) => c.name));
      if (!knownIds.has(cp) && !knownNames.has(cp)) {
        throw new Error(`Scene "${scene.id}": characters_present references unknown character "${cp}"`);
      }
    }
  }

  return {
    id: m.id,
    title: m.title,
    description: m.description,
    languages: m.languages,
    entryPoint: m.entry_point,
    narrator,
    characters,
    scenes,
    storylines,
    map,
    flags,
  };
}
```

- [ ] **Step 5: Run tests, confirm pass**

```bash
npm test --workspace story-engine
```

Expected: PASS (all loader tests).

- [ ] **Step 6: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): loadStory with reference-integrity validation"
```

---

### Task 7: Engine state initialization & menu mode

**Files:**
- Create: `packages/story-engine/src/state.ts`
- Create: `packages/story-engine/src/engine.ts`
- Create: `packages/story-engine/tests/engine-menu.test.ts`

- [ ] **Step 1: Write `state.ts`** β€” initial-state factory

```typescript
import type { GameState, Narrator } from "./types.js";

export function createInitialState(narrator: Narrator): GameState {
  return {
    mode: "menu",
    currentSpeaker: narrator.id,
    flags: {},
    discoveredScenes: [],
    metCharacters: [],
    recentTransitions: [],
  };
}

export const RECENT_TRANSITIONS_LIMIT = 20;

export function appendTransition(
  events: GameState["recentTransitions"],
  newEvents: GameState["recentTransitions"],
): GameState["recentTransitions"] {
  const combined = [...events, ...newEvents];
  if (combined.length > RECENT_TRANSITIONS_LIMIT) {
    return combined.slice(combined.length - RECENT_TRANSITIONS_LIMIT);
  }
  return combined;
}
```

- [ ] **Step 2: Write failing test** β€” `packages/story-engine/tests/engine-menu.test.ts`:

```typescript
import { describe, it, expect } from "vitest";
import { readFileSync, readdirSync } from "node:fs";
import { resolve } from "node:path";
import { StoryEngine } from "../src/engine.js";
import type { LoadedContent } from "../src/types.js";
import { loadNarrator, loadStory } from "../src/loader.js";

function readJsonFile(p: string): unknown { return JSON.parse(readFileSync(p, "utf-8")); }
function readJsonDir(dir: string): Record<string, unknown> {
  const out: Record<string, unknown> = {};
  for (const f of readdirSync(dir)) {
    if (f.endsWith(".json")) out[f.replace(/\.json$/, "")] = readJsonFile(resolve(dir, f));
  }
  return out;
}

const FIX = resolve(__dirname, "fixtures");

function loadTestContent(): LoadedContent {
  const narrator = loadNarrator(readJsonFile(resolve(FIX, "narrator/narrator.json")));
  const story = loadStory({
    manifest: readJsonFile(resolve(FIX, "story_test/manifest.json")),
    map: readJsonFile(resolve(FIX, "story_test/map.json")),
    flags: readJsonFile(resolve(FIX, "story_test/flags.json")),
    characters: readJsonDir(resolve(FIX, "story_test/characters")),
    scenes: readJsonDir(resolve(FIX, "story_test/scenes")),
    storylines: readJsonDir(resolve(FIX, "story_test/storylines/chapter1")),
  });
  return { narrator, stories: { story_test: story } };
}

describe("StoryEngine β€” menu mode", () => {
  it("starts in menu mode with the narrator as the current speaker", () => {
    const engine = new StoryEngine(loadTestContent());
    const state = engine.getState();
    expect(state.mode).toBe("menu");
    expect(state.currentSpeaker).toBe("narrator");
    expect(state.storyId).toBeUndefined();
    expect(state.flags).toEqual({});
  });

  it("lists available stories", () => {
    const engine = new StoryEngine(loadTestContent());
    const stories = engine.getAvailableStories();
    expect(stories).toEqual([{ id: "story_test", title: "Test Story", description: "A short test story." }]);
  });

  it("returns the menu narrator as current character", () => {
    const engine = new StoryEngine(loadTestContent());
    const c = engine.getCurrentCharacter();
    expect(c).not.toBeNull();
    expect(c!.id).toBe("narrator");
  });

  it("reset() returns to fresh menu state", () => {
    const engine = new StoryEngine(loadTestContent());
    const fresh = engine.reset();
    expect(fresh.mode).toBe("menu");
    expect(fresh.flags).toEqual({});
  });
});
```

- [ ] **Step 3: Run tests β€” FAIL** (StoryEngine not implemented)

```bash
npm test --workspace story-engine
```

- [ ] **Step 4: Implement `engine.ts`** β€” the menu-mode subset:

```typescript
import type {
  Character, GameState, LoadedContent, Narrator, Scene, StorylineAction, StorylineNode,
} from "./types.js";
import { createInitialState } from "./state.js";

export class StoryEngine {
  private content: LoadedContent;
  private state: GameState;

  constructor(content: LoadedContent) {
    this.content = content;
    this.state = createInitialState(content.narrator);
  }

  reset(): GameState {
    this.state = createInitialState(this.content.narrator);
    return this.state;
  }

  getState(): Readonly<GameState> {
    return this.state;
  }

  getAvailableStories(): Array<{ id: string; title: string; description: string }> {
    return Object.values(this.content.stories).map((s) => ({
      id: s.id, title: s.title, description: s.description,
    }));
  }

  getCurrentCharacter(): Character | Narrator | null {
    if (this.state.mode === "menu") return this.content.narrator;
    if (!this.state.storyId) return null;
    const story = this.content.stories[this.state.storyId];
    if (!story) return null;
    if (this.state.currentSpeaker === "narrator") return story.narrator;
    if (!this.state.currentSpeaker) return null;
    return story.characters[this.state.currentSpeaker] ?? null;
  }

  getCurrentNode(): StorylineNode | null {
    if (this.state.mode !== "story" || !this.state.storyId || !this.state.currentNodeId) return null;
    return this.content.stories[this.state.storyId]?.storylines[this.state.currentNodeId] ?? null;
  }

  getCurrentScene(): Scene | null {
    if (this.state.mode !== "story" || !this.state.storyId || !this.state.currentSceneId) return null;
    return this.content.stories[this.state.storyId]?.scenes[this.state.currentSceneId] ?? null;
  }
}
```

- [ ] **Step 5: Run tests β€” PASS**

```bash
npm test --workspace story-engine
```

- [ ] **Step 6: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): StoryEngine class β€” menu-mode operations"
```

---

### Task 8: Engine β€” enterStoryMode / exitStoryMode

**Files:**
- Modify: `packages/story-engine/src/engine.ts`
- Create: `packages/story-engine/tests/engine-lifecycle.test.ts`

- [ ] **Step 1: Write failing tests** β€” `packages/story-engine/tests/engine-lifecycle.test.ts`:

```typescript
import { describe, it, expect } from "vitest";
import { StoryEngine } from "../src/engine.js";
// reuse the fixture loader from engine-menu test
import { readFileSync, readdirSync } from "node:fs";
import { resolve } from "node:path";
import type { LoadedContent } from "../src/types.js";
import { loadNarrator, loadStory } from "../src/loader.js";

function readJsonFile(p: string): unknown { return JSON.parse(readFileSync(p, "utf-8")); }
function readJsonDir(dir: string): Record<string, unknown> {
  const out: Record<string, unknown> = {};
  for (const f of readdirSync(dir)) if (f.endsWith(".json")) out[f.replace(/\.json$/, "")] = readJsonFile(resolve(dir, f));
  return out;
}
const FIX = resolve(__dirname, "fixtures");
function loadTestContent(): LoadedContent {
  const narrator = loadNarrator(readJsonFile(resolve(FIX, "narrator/narrator.json")));
  const story = loadStory({
    manifest: readJsonFile(resolve(FIX, "story_test/manifest.json")),
    map: readJsonFile(resolve(FIX, "story_test/map.json")),
    flags: readJsonFile(resolve(FIX, "story_test/flags.json")),
    characters: readJsonDir(resolve(FIX, "story_test/characters")),
    scenes: readJsonDir(resolve(FIX, "story_test/scenes")),
    storylines: readJsonDir(resolve(FIX, "story_test/storylines/chapter1")),
  });
  return { narrator, stories: { story_test: story } };
}

describe("enterStoryMode", () => {
  it("transitions from menu to story mode with correct initial state", () => {
    const engine = new StoryEngine(loadTestContent());
    const result = engine.enterStoryMode("story_test");
    expect(result.state.mode).toBe("story");
    expect(result.state.storyId).toBe("story_test");
    expect(result.state.currentSceneId).toBe("tavern");
    expect(result.state.currentNodeId).toBe("meet_sparrow");
    expect(result.state.currentSpeaker).toBe("Sparrow");
  });

  it("emits storyEntered + sceneChanged + speakerChanged events", () => {
    const engine = new StoryEngine(loadTestContent());
    const { events } = engine.enterStoryMode("story_test");
    const types = events.map((e) => e.type);
    expect(types).toContain("storyEntered");
    expect(types).toContain("sceneChanged");
    expect(types).toContain("speakerChanged");
    const sp = events.find((e) => e.type === "speakerChanged");
    expect(sp).toBeDefined();
    expect((sp as Extract<typeof sp, { type: "speakerChanged" }>).to).toBe("Sparrow");
    expect((sp as Extract<typeof sp, { type: "speakerChanged" }>).newCharacter.voice).toBe("ash");
  });

  it("emits a blocked event for unknown story id", () => {
    const engine = new StoryEngine(loadTestContent());
    const result = engine.enterStoryMode("nope");
    expect(result.events.find((e) => e.type === "blocked")).toBeDefined();
    expect(result.state.mode).toBe("menu");
  });
});

describe("exitStoryMode", () => {
  it("returns to menu state and emits storyExited + speakerChanged", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const result = engine.exitStoryMode();
    expect(result.state.mode).toBe("menu");
    expect(result.state.storyId).toBeUndefined();
    expect(result.state.currentSpeaker).toBe("narrator");
    const types = result.events.map((e) => e.type);
    expect(types).toContain("storyExited");
    expect(types).toContain("speakerChanged");
  });
});
```

- [ ] **Step 2: Run β€” FAIL**

- [ ] **Step 3: Implement `enterStoryMode` and `exitStoryMode`** β€” append to `engine.ts`:

```typescript
import type { TransitionEvent, TransitionResult } from "./types.js";
import { appendTransition } from "./state.js";

// Add to StoryEngine class:

  enterStoryMode(storyId: string): TransitionResult {
    const story = this.content.stories[storyId];
    if (!story) {
      return this.blockedResult(`Unknown story: ${storyId}`);
    }
    // Find the entry-point node
    const entryNode = this.findEntryNode(story);
    if (!entryNode) {
      return this.blockedResult(`Entry node not resolvable for story ${storyId}`);
    }
    const events: TransitionEvent[] = [
      { type: "storyEntered", storyId },
      { type: "sceneChanged", from: undefined, to: entryNode.scene },
    ];
    // Speaker change: from narrator to entry-node speaker
    const newCharacter = this.resolveCharacter(story, entryNode.speaker);
    if (newCharacter) {
      events.push({
        type: "speakerChanged",
        from: this.state.currentSpeaker,
        to: entryNode.speaker,
        newCharacter,
      });
    }
    this.state = {
      ...this.state,
      mode: "story",
      storyId,
      currentSceneId: entryNode.scene,
      currentNodeId: entryNode.id,
      currentSpeaker: entryNode.speaker,
      discoveredScenes: [entryNode.scene],
      metCharacters: newCharacter && newCharacter.id !== "narrator" ? [newCharacter.id] : [],
      recentTransitions: appendTransition(this.state.recentTransitions, events),
    };
    return { state: this.state, events };
  }

  exitStoryMode(): TransitionResult {
    if (this.state.mode !== "story") {
      return { state: this.state, events: [] };
    }
    const events: TransitionEvent[] = [
      { type: "storyExited" },
      {
        type: "speakerChanged",
        from: this.state.currentSpeaker,
        to: "narrator",
        newCharacter: this.content.narrator,
      },
    ];
    this.state = {
      ...this.state,
      mode: "menu",
      storyId: undefined,
      currentSceneId: undefined,
      currentNodeId: undefined,
      currentSpeaker: "narrator",
      flags: {},
      discoveredScenes: [],
      metCharacters: [],
      recentTransitions: appendTransition(this.state.recentTransitions, events),
    };
    return { state: this.state, events };
  }

  // ─── private helpers ──────────────────────────────────────────────────

  private blockedResult(reason: string): TransitionResult {
    const events: TransitionEvent[] = [{ type: "blocked", reason }];
    this.state = {
      ...this.state,
      recentTransitions: appendTransition(this.state.recentTransitions, events),
    };
    return { state: this.state, events };
  }

  private findEntryNode(story: import("./types.js").Story): StorylineNode | null {
    // entryPoint is path like "storylines/chapter1/meet_sparrow.json"
    const stem = story.entryPoint.split("/").pop()?.replace(/\.json$/, "");
    if (!stem) return null;
    return story.storylines[stem] ?? null;
  }

  private resolveCharacter(
    story: import("./types.js").Story,
    speakerId: string,
  ): Character | Narrator | null {
    if (!speakerId || speakerId === "narrator") return story.narrator;
    // speakerId in legacy data may be display name (e.g. "Sparrow"); normalize
    const byId = story.characters[speakerId];
    if (byId) return byId;
    const byName = Object.values(story.characters).find((c) => c.name === speakerId);
    return byName ?? null;
  }
```

- [ ] **Step 4: Run tests β€” PASS**

```bash
npm test --workspace story-engine
```

- [ ] **Step 5: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): enterStoryMode and exitStoryMode with events"
```

---

### Task 9: Engine β€” advanceStoryline

**Files:**
- Modify: `packages/story-engine/src/engine.ts`
- Create: `packages/story-engine/tests/engine-storyline.test.ts`

- [ ] **Step 1: Write failing tests**

```typescript
import { describe, it, expect } from "vitest";
import { StoryEngine } from "../src/engine.js";
// reuse helper at top of file (copy from engine-lifecycle.test.ts)
import { readFileSync, readdirSync } from "node:fs";
import { resolve } from "node:path";
import type { LoadedContent } from "../src/types.js";
import { loadNarrator, loadStory } from "../src/loader.js";
function readJsonFile(p: string): unknown { return JSON.parse(readFileSync(p, "utf-8")); }
function readJsonDir(dir: string): Record<string, unknown> {
  const out: Record<string, unknown> = {};
  for (const f of readdirSync(dir)) if (f.endsWith(".json")) out[f.replace(/\.json$/, "")] = readJsonFile(resolve(dir, f));
  return out;
}
const FIX = resolve(__dirname, "fixtures");
function loadTestContent(): LoadedContent {
  const narrator = loadNarrator(readJsonFile(resolve(FIX, "narrator/narrator.json")));
  const story = loadStory({
    manifest: readJsonFile(resolve(FIX, "story_test/manifest.json")),
    map: readJsonFile(resolve(FIX, "story_test/map.json")),
    flags: readJsonFile(resolve(FIX, "story_test/flags.json")),
    characters: readJsonDir(resolve(FIX, "story_test/characters")),
    scenes: readJsonDir(resolve(FIX, "story_test/scenes")),
    storylines: readJsonDir(resolve(FIX, "story_test/storylines/chapter1")),
  });
  return { narrator, stories: { story_test: story } };
}

describe("advanceStoryline", () => {
  it("advances to the next node, sets flags, emits flagSet events", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const result = engine.advanceStoryline("greet_respectfully");
    expect(result.state.currentNodeId).toBe("friendly_response");
    expect(result.state.flags["trust_sparrow"]).toBe(true);
    const flagEvents = result.events.filter((e) => e.type === "flagSet");
    expect(flagEvents).toHaveLength(1);
    expect((flagEvents[0] as Extract<typeof flagEvents[0], { type: "flagSet" }>).name).toBe("trust_sparrow");
  });

  it("does NOT emit speakerChanged when the next node has the same speaker", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const result = engine.advanceStoryline("greet_respectfully");
    expect(result.events.find((e) => e.type === "speakerChanged")).toBeUndefined();
  });

  it("returns blocked event when actionId not in current node", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const result = engine.advanceStoryline("nonexistent_action");
    expect(result.events.find((e) => e.type === "blocked")).toBeDefined();
    expect(result.state.currentNodeId).toBe("meet_sparrow");
  });

  it("returns blocked event when not in story mode", () => {
    const engine = new StoryEngine(loadTestContent());
    const result = engine.advanceStoryline("anything");
    expect(result.events.find((e) => e.type === "blocked")).toBeDefined();
  });
});
```

- [ ] **Step 2: Run β€” FAIL**

- [ ] **Step 3: Implement `advanceStoryline`** β€” add to `engine.ts`:

```typescript
  advanceStoryline(actionId: string): TransitionResult {
    if (this.state.mode !== "story" || !this.state.storyId || !this.state.currentNodeId) {
      return this.blockedResult("Not in story mode");
    }
    const story = this.content.stories[this.state.storyId];
    const currentNode = story?.storylines[this.state.currentNodeId];
    if (!story || !currentNode) {
      return this.blockedResult("Current state has no valid node");
    }
    const action = currentNode.actions.find((a) => a.id === actionId);
    if (!action) {
      return this.blockedResult(`Action "${actionId}" not available at current node`);
    }
    if (!action.next) {
      return this.blockedResult(`Action "${actionId}" has no next node`);
    }
    const nextNode = story.storylines[action.next];
    if (!nextNode) {
      return this.blockedResult(`Action "${actionId}" points to unknown node "${action.next}"`);
    }

    const events: TransitionEvent[] = [];
    const newFlags = { ...this.state.flags };
    if (action.effects?.setFlags) {
      for (const [name, value] of Object.entries(action.effects.setFlags)) {
        newFlags[name] = value;
        events.push({ type: "flagSet", name, value });
      }
    }
    let newSceneId = this.state.currentSceneId!;
    if (nextNode.scene !== this.state.currentSceneId) {
      events.push({ type: "sceneChanged", from: this.state.currentSceneId, to: nextNode.scene });
      newSceneId = nextNode.scene;
    }
    let newSpeaker = this.state.currentSpeaker;
    if (nextNode.speaker && nextNode.speaker !== this.state.currentSpeaker) {
      const newCharacter = this.resolveCharacter(story, nextNode.speaker);
      if (newCharacter) {
        events.push({
          type: "speakerChanged",
          from: this.state.currentSpeaker,
          to: nextNode.speaker,
          newCharacter,
        });
      }
      newSpeaker = nextNode.speaker;
    }

    const newDiscovered = this.state.discoveredScenes.includes(newSceneId)
      ? this.state.discoveredScenes
      : [...this.state.discoveredScenes, newSceneId];
    const newMet = newSpeaker && newSpeaker !== "narrator" && !this.state.metCharacters.includes(newSpeaker)
      ? [...this.state.metCharacters, newSpeaker]
      : this.state.metCharacters;

    this.state = {
      ...this.state,
      currentNodeId: nextNode.id,
      currentSceneId: newSceneId,
      currentSpeaker: newSpeaker,
      flags: newFlags,
      discoveredScenes: newDiscovered,
      metCharacters: newMet,
      recentTransitions: appendTransition(this.state.recentTransitions, events),
    };
    return { state: this.state, events };
  }
```

- [ ] **Step 4: Run tests β€” PASS**

- [ ] **Step 5: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): advanceStoryline with flag effects + speaker/scene transitions"
```

---

### Task 10: Engine β€” navigateScene with flag-gated edges

**Files:**
- Modify: `packages/story-engine/src/engine.ts`
- Create: `packages/story-engine/tests/engine-navigation.test.ts`

- [ ] **Step 1: Write failing tests**

```typescript
import { describe, it, expect } from "vitest";
import { StoryEngine } from "../src/engine.js";
// (copy fixture loader helper from prior test files at top)
// ... loadTestContent ...

describe("navigateScene", () => {
  it("succeeds for an unconditional edge", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const result = engine.navigateScene("harbor");
    expect(result.state.currentSceneId).toBe("harbor");
    const sc = result.events.find((e) => e.type === "sceneChanged");
    expect(sc).toBeDefined();
  });

  it("blocks an edge with unmet condition_failed flag", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    // trust_sparrow is false at this point
    const result = engine.navigateScene("docks");
    expect(result.state.currentSceneId).toBe("tavern");
    const blocked = result.events.find((e) => e.type === "blocked");
    expect(blocked).toBeDefined();
    expect((blocked as Extract<typeof blocked, { type: "blocked" }>).reason)
      .toMatch(/don't trust him/);
  });

  it("succeeds once the gating flag is set", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    engine.advanceStoryline("greet_respectfully"); // sets trust_sparrow=true
    // navigate from tavern to docks
    const result = engine.navigateScene("docks");
    // docks isn't a real scene in our fixture map; we need to add it OR test this with harbor.
    // Adjust: harbor edge is unconditional and tavern→harbor exists, so use that case.
    // For a cleaner test, modify map fixture to include docks as a scene file as well.
    expect(result.events.find((e) => e.type === "blocked")).toBeUndefined();
  });

  it("blocks an edge that doesn't exist in the map", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const result = engine.navigateScene("nonexistent_scene");
    expect(result.events.find((e) => e.type === "blocked")).toBeDefined();
  });
});

describe("getReachableScenes", () => {
  it("returns scenes reachable from current scene with availability flags", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const reachable = engine.getReachableScenes();
    const harborEntry = reachable.find((r) => r.scene.id === "harbor");
    expect(harborEntry).toBeDefined();
    expect(harborEntry!.available).toBe(true);
    const docksEntry = reachable.find((r) => r.scene.id === "docks");
    if (docksEntry) {
      expect(docksEntry.available).toBe(false);
      expect(docksEntry.blockedReason).toBeDefined();
    }
  });
});
```

- [ ] **Step 2: Add a `docks` scene fixture so navigation tests work**

`packages/story-engine/tests/fixtures/story_test/scenes/docks.json`:

```json
{
  "name": "Old Docks",
  "description": "Splintered planks and shadowy crates.",
  "actions": [],
  "characters_present": []
}
```

- [ ] **Step 3: Run tests β€” FAIL**

- [ ] **Step 4: Implement `navigateScene` and `getReachableScenes`** β€” add to `engine.ts`:

```typescript
import type { MapEdge, Scene } from "./types.js";

  navigateScene(sceneId: string): TransitionResult {
    if (this.state.mode !== "story" || !this.state.storyId || !this.state.currentSceneId) {
      return this.blockedResult("Not in story mode");
    }
    const story = this.content.stories[this.state.storyId];
    if (!story) return this.blockedResult("No active story");
    const edge = story.map.find((e) => e.from === this.state.currentSceneId && e.to === sceneId);
    if (!edge) return this.blockedResult(`No path from "${this.state.currentSceneId}" to "${sceneId}"`);
    const blockedCondition = (edge.conditions ?? []).find((c) => !this.state.flags[c.flag]);
    if (blockedCondition) return this.blockedResult(blockedCondition.conditionFailed);

    const events: TransitionEvent[] = [
      { type: "sceneChanged", from: this.state.currentSceneId, to: sceneId },
    ];
    const newDiscovered = this.state.discoveredScenes.includes(sceneId)
      ? this.state.discoveredScenes
      : [...this.state.discoveredScenes, sceneId];

    this.state = {
      ...this.state,
      currentSceneId: sceneId,
      discoveredScenes: newDiscovered,
      recentTransitions: appendTransition(this.state.recentTransitions, events),
    };
    return { state: this.state, events };
  }

  getReachableScenes(): Array<{ scene: Scene; description: string; available: boolean; blockedReason?: string }> {
    if (this.state.mode !== "story" || !this.state.storyId || !this.state.currentSceneId) return [];
    const story = this.content.stories[this.state.storyId];
    if (!story) return [];
    const fromHere = story.map.filter((e) => e.from === this.state.currentSceneId);
    return fromHere.flatMap((edge) => {
      const scene = story.scenes[edge.to];
      if (!scene) return [];
      const blocked = (edge.conditions ?? []).find((c) => !this.state.flags[c.flag]);
      return [{
        scene,
        description: edge.description,
        available: !blocked,
        blockedReason: blocked?.conditionFailed,
      }];
    });
  }
```

- [ ] **Step 5: Run tests β€” PASS**

- [ ] **Step 6: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): navigateScene and getReachableScenes with flag gating"
```

---

### Task 11: Engine β€” performSceneAction & remaining queries

**Files:**
- Modify: `packages/story-engine/src/engine.ts`
- Create: `packages/story-engine/tests/engine-scene-actions.test.ts`

- [ ] **Step 1: Write failing tests**

```typescript
import { describe, it, expect } from "vitest";
import { StoryEngine } from "../src/engine.js";
// ... fixture loader as above ...

describe("performSceneAction", () => {
  it("returns the atmospheric description and does NOT change story state", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const before = engine.getState();
    const result = engine.performSceneAction("examine_memorabilia");
    expect(result.state.currentNodeId).toBe(before.currentNodeId);
    expect(result.state.currentSceneId).toBe(before.currentSceneId);
    expect(result.events.find((e) => e.type === "blocked")).toBeUndefined();
  });

  it("returns blocked for unknown scene action id", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const result = engine.performSceneAction("nope");
    expect(result.events.find((e) => e.type === "blocked")).toBeDefined();
  });
});

describe("getAvailableActions / getAvailableSceneActions", () => {
  it("returns the storyline actions for the current node", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const actions = engine.getAvailableActions();
    expect(actions.map((a) => a.id)).toEqual(["greet_respectfully", "mock_sparrow"]);
  });

  it("returns the scene actions for the current scene", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const sceneActions = engine.getAvailableSceneActions();
    expect(sceneActions.map((a) => a.id)).toEqual(["examine_memorabilia"]);
  });
});
```

- [ ] **Step 2: Run β€” FAIL**

- [ ] **Step 3: Implement** β€” add to `engine.ts`:

```typescript
  performSceneAction(actionId: string): TransitionResult {
    if (this.state.mode !== "story" || !this.state.storyId || !this.state.currentSceneId) {
      return this.blockedResult("Not in story mode");
    }
    const story = this.content.stories[this.state.storyId];
    const scene = story?.scenes[this.state.currentSceneId];
    const action = scene?.actions.find((a) => a.id === actionId);
    if (!action) return this.blockedResult(`Scene action "${actionId}" not available`);
    // Atmospheric β€” no state mutation, no events
    return { state: this.state, events: [] };
  }

  getAvailableActions(): StorylineAction[] {
    const node = this.getCurrentNode();
    return node ? node.actions : [];
  }

  getAvailableSceneActions(): import("./types.js").SceneAction[] {
    const scene = this.getCurrentScene();
    return scene ? scene.actions : [];
  }
```

- [ ] **Step 4: Run β€” PASS**

- [ ] **Step 5: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): performSceneAction + read queries for actions"
```

---

### Task 12: Engine β€” prompt builder

**Files:**
- Create: `packages/story-engine/src/prompt-builder.ts`
- Modify: `packages/story-engine/src/engine.ts`
- Create: `packages/story-engine/tests/prompt-builder.test.ts`

- [ ] **Step 1: Write failing tests**

```typescript
import { describe, it, expect } from "vitest";
import { StoryEngine } from "../src/engine.js";
// ... fixture loader ...

describe("buildSystemPrompt β€” menu mode", () => {
  it("includes narrator persona, intro, and the list of available stories", () => {
    const engine = new StoryEngine(loadTestContent());
    const prompt = engine.buildSystemPrompt();
    expect(prompt).toContain("The Narrator");
    expect(prompt).toContain("Welcome adventurer!");
    expect(prompt).toMatch(/Test Story/);
    expect(prompt).toContain("select_story");
  });
});

describe("buildSystemPrompt β€” story mode", () => {
  it("includes character persona, scene description, scripted line, available actions, and the LLM rules", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const prompt = engine.buildSystemPrompt();
    expect(prompt).toContain("Sparrow");                     // character name
    expect(prompt).toContain("Notorious pirate");            // background
    expect(prompt).toContain("Rusty Anchor Tavern");         // scene name
    expect(prompt).toContain("Friend or foe?");              // scripted line
    expect(prompt).toContain("greet_respectfully");          // action id
    expect(prompt).toContain("mock_sparrow");                // action id
    expect(prompt).toMatch(/never advance the plot/i);       // rules block
  });

  it("renders set flags as plain English", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    engine.advanceStoryline("greet_respectfully");
    const prompt = engine.buildSystemPrompt();
    expect(prompt).toContain("trust_sparrow"); // mentioned somewhere in flag list
  });
});

describe("formatOptionsRecap", () => {
  it("renders the available actions as a short spoken-style sentence", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const recap = engine.formatOptionsRecap();
    expect(recap).toMatch(/show respect/i);
    expect(recap).toMatch(/mock/i);
  });
});
```

- [ ] **Step 2: Run β€” FAIL**

- [ ] **Step 3: Implement `prompt-builder.ts`**

```typescript
import type { Character, GameState, LoadedContent, Narrator, Scene, StorylineAction, StorylineNode } from "./types.js";

const COMMON_RULES = `# Conversation rules
- You are in a voice conversation. Keep replies short, warm, spoken (1-2 sentences). No formatting, no asterisks, no emojis.
- Speak naturally as if to a real person.
`;

const MENU_RULES = `# Menu rules
- The user is choosing a story. Briefly describe options and help them decide.
- When the user clearly picks a story, call \`select_story\` with its id.
`;

const STORY_RULES = `# Story rules
- You voice a single character. Stay in character.
- Speak the SCRIPTED LINE below in your character's voice β€” paraphrase if needed but never invent new plot.
- React to the user with full awareness of the scene, your character, and what just happened.
- NEVER advance the plot without calling \`advance_storyline\` with one of the AVAILABLE ACTION ids.
- If the user clearly picks one of the available actions, call \`advance_storyline\` immediately.
- If the user just chats, respond in character without a tool call.
- If the user is lost or asks "what can I do?", call \`request_options\`.
- If the user wants to go somewhere new in the world, call \`navigate_scene\`.
- If the user explicitly does an atmospheric scene action, call \`perform_scene_action\`.
- If the user wants to stop / go back to menu, call \`exit_story\`.
`;

export function buildMenuPrompt(content: LoadedContent): string {
  const n = content.narrator;
  const stories = Object.values(content.stories)
    .map((s) => `- id: "${s.id}" β€” ${s.title}: ${s.description}`)
    .join("\n");
  return [
    COMMON_RULES,
    `# You are\nName: ${n.name}\nDescription: ${n.description}`,
    `# Voice tone\n${n.voiceTone}`,
    `# Background\n${n.background}`,
    `# Goal\n${n.goal}`,
    `# Greeting\nIf the user says hello first, respond with: "${n.introduction}"`,
    `# Available stories\n${stories}`,
    MENU_RULES,
  ].join("\n\n");
}

export function buildStoryPrompt(args: {
  state: GameState;
  character: Character | Narrator;
  scene: Scene;
  node: StorylineNode;
  availableActions: StorylineAction[];
  reachableScenes: Array<{ id: string; description: string; available: boolean; blockedReason?: string }>;
  sceneActions: Array<{ id: string; description: string }>;
  setFlagNames: string[];
}): string {
  const { character: c, scene, node, availableActions, reachableScenes, sceneActions, setFlagNames } = args;
  const actionsList = availableActions.length === 0
    ? "(none β€” this is an end node)"
    : availableActions.map((a) => `- id: "${a.id}" β€” ${a.description}`).join("\n");
  const scenesList = reachableScenes.length === 0
    ? "(none)"
    : reachableScenes.map((r) =>
        `- id: "${r.id}" β€” ${r.description}` + (r.available ? "" : ` (BLOCKED: ${r.blockedReason})`),
      ).join("\n");
  const sceneActionsList = sceneActions.length === 0
    ? "(none)"
    : sceneActions.map((a) => `- id: "${a.id}" β€” ${a.description}`).join("\n");
  const flagsList = setFlagNames.length === 0
    ? "(no flags set yet)"
    : setFlagNames.map((f) => `- ${f}`).join("\n");
  return [
    COMMON_RULES,
    `# You are\nName: ${c.name}\nDescription: ${c.description}`,
    `# Voice tone\n${c.voiceTone}`,
    `# Background\n${c.background}`,
    `# Goal\n${c.goal}`,
    `# Current scene\n${scene.name}\n${scene.description}`,
    `# Scripted line to speak now (paraphrase in character)\n"${node.text}"`,
    `# Available actions (the user must clearly pick one before you call advance_storyline)\n${actionsList}`,
    `# Reachable scenes (for navigate_scene)\n${scenesList}`,
    `# Atmospheric scene actions (for perform_scene_action)\n${sceneActionsList}`,
    `# Currently set story flags\n${flagsList}`,
    STORY_RULES,
  ].join("\n\n");
}
```

- [ ] **Step 4: Wire into `engine.ts`**

```typescript
import { buildMenuPrompt, buildStoryPrompt } from "./prompt-builder.js";

  buildSystemPrompt(): string {
    if (this.state.mode === "menu") {
      return buildMenuPrompt(this.content);
    }
    const story = this.state.storyId ? this.content.stories[this.state.storyId] : undefined;
    const character = this.getCurrentCharacter();
    const scene = this.getCurrentScene();
    const node = this.getCurrentNode();
    if (!story || !character || !scene || !node) return buildMenuPrompt(this.content);
    return buildStoryPrompt({
      state: this.state,
      character,
      scene,
      node,
      availableActions: this.getAvailableActions(),
      reachableScenes: this.getReachableScenes().map((r) => ({
        id: r.scene.id, description: r.description, available: r.available, blockedReason: r.blockedReason,
      })),
      sceneActions: this.getAvailableSceneActions().map((a) => ({ id: a.id, description: a.description })),
      setFlagNames: Object.entries(this.state.flags).filter(([, v]) => v).map(([k]) => k),
    });
  }

  formatOptionsRecap(): string {
    const actions = this.getAvailableActions();
    if (actions.length === 0) return "There's nothing more to do here right now.";
    if (actions.length === 1) return `You could ${actions[0]!.description}.`;
    const phrases = actions.map((a) => a.description);
    const last = phrases.pop();
    return `You could ${phrases.join(", ")}, or ${last}.`;
  }
```

- [ ] **Step 5: Run tests β€” PASS**

- [ ] **Step 6: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): system prompt builder + options recap"
```

---

### Task 13: Engine β€” dynamic tool definitions

**Files:**
- Modify: `packages/story-engine/src/engine.ts`
- Create: `packages/story-engine/tests/tool-defs.test.ts`

- [ ] **Step 1: Write failing tests**

```typescript
import { describe, it, expect } from "vitest";
import { StoryEngine } from "../src/engine.js";
// ... fixture loader ...

describe("buildToolDefinitions β€” menu mode", () => {
  it("exposes select_story with current story ids in the enum", () => {
    const engine = new StoryEngine(loadTestContent());
    const tools = engine.buildToolDefinitions();
    const selectStory = tools.find((t) => t.name === "select_story");
    expect(selectStory).toBeDefined();
    expect((selectStory!.parameters.properties.storyId as { enum: string[] }).enum)
      .toEqual(["story_test"]);
  });
});

describe("buildToolDefinitions β€” story mode", () => {
  it("exposes advance_storyline with current node action ids in the enum", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const tools = engine.buildToolDefinitions();
    const advance = tools.find((t) => t.name === "advance_storyline");
    expect((advance!.parameters.properties.actionId as { enum: string[] }).enum)
      .toEqual(["greet_respectfully", "mock_sparrow"]);
  });

  it("exposes navigate_scene with currently reachable scene ids", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const tools = engine.buildToolDefinitions();
    const nav = tools.find((t) => t.name === "navigate_scene");
    const enumIds = (nav!.parameters.properties.sceneId as { enum: string[] }).enum;
    expect(enumIds).toEqual(expect.arrayContaining(["harbor"]));
  });

  it("exposes perform_scene_action with current scene action ids", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const tools = engine.buildToolDefinitions();
    const sa = tools.find((t) => t.name === "perform_scene_action");
    expect((sa!.parameters.properties.actionId as { enum: string[] }).enum)
      .toEqual(["examine_memorabilia"]);
  });

  it("always exposes request_options and exit_story in story mode", () => {
    const engine = new StoryEngine(loadTestContent());
    engine.enterStoryMode("story_test");
    const tools = engine.buildToolDefinitions();
    expect(tools.find((t) => t.name === "request_options")).toBeDefined();
    expect(tools.find((t) => t.name === "exit_story")).toBeDefined();
  });
});
```

- [ ] **Step 2: Run β€” FAIL**

- [ ] **Step 3: Implement `buildToolDefinitions`** β€” add to `engine.ts`:

```typescript
import type { ToolDef } from "./types.js";

  buildToolDefinitions(): ToolDef[] {
    if (this.state.mode === "menu") {
      const storyIds = Object.keys(this.content.stories);
      return [{
        name: "select_story",
        description: "Confirm the user has chosen a story; transitions into story mode.",
        parameters: {
          type: "object",
          properties: {
            storyId: { type: "string", enum: storyIds, description: "Id of the chosen story." },
          },
          required: ["storyId"],
        },
      }];
    }
    const node = this.getCurrentNode();
    const actionIds = node ? node.actions.map((a) => a.id) : [];
    const reachable = this.getReachableScenes().map((r) => r.scene.id);
    const sceneActionIds = this.getAvailableSceneActions().map((a) => a.id);

    const tools: ToolDef[] = [];
    if (actionIds.length > 0) {
      tools.push({
        name: "advance_storyline",
        description: "Advance the plot by picking one of the listed available actions. Only call when user intent matches one.",
        parameters: {
          type: "object",
          properties: {
            actionId: { type: "string", enum: actionIds, description: "Id of the chosen storyline action." },
          },
          required: ["actionId"],
        },
      });
    }
    if (reachable.length > 0) {
      tools.push({
        name: "navigate_scene",
        description: "Move to a different scene the user wants to visit.",
        parameters: {
          type: "object",
          properties: {
            sceneId: { type: "string", enum: reachable, description: "Id of the scene to move to." },
          },
          required: ["sceneId"],
        },
      });
    }
    if (sceneActionIds.length > 0) {
      tools.push({
        name: "perform_scene_action",
        description: "Perform an atmospheric scene action (no plot effect β€” just narration).",
        parameters: {
          type: "object",
          properties: {
            actionId: { type: "string", enum: sceneActionIds, description: "Id of the scene action." },
          },
          required: ["actionId"],
        },
      });
    }
    tools.push({
      name: "request_options",
      description: "Use when the user asks what they can do or seems lost.",
      parameters: { type: "object", properties: {}, required: [] },
    });
    tools.push({
      name: "exit_story",
      description: "Use when the user wants to stop the story and return to the menu.",
      parameters: { type: "object", properties: {}, required: [] },
    });
    return tools;
  }
```

- [ ] **Step 4: Run β€” PASS**

- [ ] **Step 5: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): dynamic tool-definition builder"
```

---

### Task 14: Engine β€” recent-transitions log accessor + index export

**Files:**
- Modify: `packages/story-engine/src/engine.ts`
- Modify: `packages/story-engine/src/index.ts`

- [ ] **Step 1: Add accessor to `engine.ts`**

```typescript
  getRecentTransitionLog(): TransitionEvent[] {
    return [...this.state.recentTransitions];
  }

  getPromptContext(): {
    state: Readonly<GameState>;
    character: Character | Narrator | null;
    scene: Scene | null;
    node: StorylineNode | null;
  } {
    return {
      state: this.state,
      character: this.getCurrentCharacter(),
      scene: this.getCurrentScene(),
      node: this.getCurrentNode(),
    };
  }
```

- [ ] **Step 2: Update `src/index.ts`** to export the public API

```typescript
export { StoryEngine } from "./engine.js";
export {
  loadNarrator,
  loadCharacter,
  loadScene,
  loadStorylineNode,
  loadMapEdges,
  loadFlags,
  loadStory,
  type StoryRawInputs,
} from "./loader.js";
export {
  buildMenuPrompt,
  buildStoryPrompt,
} from "./prompt-builder.js";
export type {
  Narrator, Character, Scene, SceneAction, StorylineNode, StorylineAction,
  StorylineActionEffects, MapEdge, FlagCondition, Story, LoadedContent,
  GameState, AppMode, TransitionEvent, TransitionResult, ToolDef, StorylineType,
} from "./types.js";
```

- [ ] **Step 3: Verify everything still builds and tests pass**

```bash
npm test --workspace story-engine
```

- [ ] **Step 4: Commit**

```bash
git add packages/story-engine/
git commit -m "feat(engine): expose public API and getRecentTransitionLog"
```

---

## Phase 3 β€” Content translation

### Task 15: Translation tooling β€” write a Node script

**Files:**
- Create: `scripts/translate-content.mjs`

This script reads the original French JSON files from `/Users/nicolasrabault/Projects/AI_game/Stories/`, calls the Anthropic Claude API to translate string fields while preserving JSON structure, and writes English files to `content/`. Run once to seed the content; manual review after.

- [ ] **Step 1: Create `scripts/translate-content.mjs`**

```bash
mkdir -p /Users/nicolasrabault/Projects/reachy-tales/scripts
```

```javascript
#!/usr/bin/env node
// Translate AI_game/Stories/{narrator,story_pirates} from French to English using Anthropic Claude.
// Run: ANTHROPIC_API_KEY=sk-ant-... node scripts/translate-content.mjs

import { readFileSync, writeFileSync, readdirSync, mkdirSync, existsSync, statSync } from "node:fs";
import { resolve, relative, dirname, join } from "node:path";

const SRC_ROOT = "/Users/nicolasrabault/Projects/AI_game/Stories";
const DST_ROOT = resolve(import.meta.dirname, "../content");
const STORIES_TO_COPY = ["narrator", "story_pirates"];
const FIELDS_TO_TRANSLATE_NESTED = new Set([
  "name", "description", "introduction", "background", "goal",
  "voice_tone", "voiceTone", "text", "title", "from", "to",
  "condition_failed", "effects",
]);
// Some fields should pass through unchanged (ids, voice names, file refs).
const FIELDS_TO_PRESERVE = new Set([
  "id", "languages", "entry_point", "voice", "type",
  "speaker", "next", "scene", "characters_present",
  "set_flags", "flag", "picture", "cover_image", "tools",
]);

const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) { console.error("Missing ANTHROPIC_API_KEY"); process.exit(1); }

async function translateBatch(strings) {
  const numbered = strings.map((s, i) => `[${i}] ${s}`).join("\n---\n");
  const res = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": apiKey,
      "anthropic-version": "2023-06-01",
      "content-type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-6",
      max_tokens: 8000,
      messages: [{
        role: "user",
        content: `Translate the following French text segments to English. Each segment is preceded by [N]. Output the same numbering. Preserve tone, register, and any special formatting markers (asterisks, ellipses). Strip any French-only directives like "LANGUE : PARLER EXCLUSIVEMENT EN FRANÇAIS" — replace with English equivalent (e.g. "LANGUAGE: SPEAK EXCLUSIVELY IN ENGLISH").\n\n${numbered}`,
      }],
    }),
  });
  if (!res.ok) throw new Error(`API ${res.status}: ${await res.text()}`);
  const data = await res.json();
  const out = data.content[0].text;
  const segments = out.split(/\[(\d+)\]\s*/).filter(Boolean);
  const result = new Array(strings.length).fill("");
  for (let i = 0; i < segments.length; i += 2) {
    const idx = parseInt(segments[i], 10);
    if (!isNaN(idx)) result[idx] = (segments[i + 1] ?? "").trim().replace(/\n---$/, "").trim();
  }
  return result;
}

function collectStrings(node, path, out) {
  if (typeof node === "string") {
    if (FIELDS_TO_TRANSLATE_NESTED.has(path[path.length - 1])) {
      out.push({ path: [...path], value: node });
    }
  } else if (Array.isArray(node)) {
    node.forEach((item, i) => collectStrings(item, [...path, String(i)], out));
  } else if (node && typeof node === "object") {
    for (const [k, v] of Object.entries(node)) {
      if (FIELDS_TO_PRESERVE.has(k)) continue;
      collectStrings(v, [...path, k], out);
    }
  }
}

function applyTranslations(node, translations) {
  if (typeof node === "string") return node;
  if (Array.isArray(node)) return node.map((x) => applyTranslations(x, translations));
  if (node && typeof node === "object") {
    const out = {};
    for (const [k, v] of Object.entries(node)) out[k] = applyTranslations(v, translations);
    return out;
  }
  return node;
}

function setAtPath(obj, path, value) {
  let cur = obj;
  for (let i = 0; i < path.length - 1; i++) {
    cur = Array.isArray(cur) ? cur[parseInt(path[i], 10)] : cur[path[i]];
  }
  const last = path[path.length - 1];
  if (Array.isArray(cur)) cur[parseInt(last, 10)] = value;
  else cur[last] = value;
}

async function translateFile(srcPath, dstPath) {
  const raw = JSON.parse(readFileSync(srcPath, "utf-8"));
  const strings = [];
  collectStrings(raw, [], strings);
  if (strings.length === 0) {
    mkdirSync(dirname(dstPath), { recursive: true });
    writeFileSync(dstPath, JSON.stringify(raw, null, 2) + "\n");
    return;
  }
  console.log(`  ${strings.length} strings to translate`);
  // Batch in chunks of 30 to keep prompts manageable
  const out = [];
  for (let i = 0; i < strings.length; i += 30) {
    const chunk = strings.slice(i, i + 30).map((s) => s.value);
    const translated = await translateBatch(chunk);
    out.push(...translated);
  }
  const result = JSON.parse(JSON.stringify(raw));
  out.forEach((value, idx) => setAtPath(result, strings[idx].path, value));
  mkdirSync(dirname(dstPath), { recursive: true });
  writeFileSync(dstPath, JSON.stringify(result, null, 2) + "\n");
}

function copyImage(srcPath, dstPath) {
  // Per spec, images are dropped from v1. Skip.
}

async function walkAndTranslate(srcDir, dstDir) {
  for (const entry of readdirSync(srcDir)) {
    const src = join(srcDir, entry);
    const dst = join(dstDir, entry);
    const stat = statSync(src);
    if (stat.isDirectory()) {
      await walkAndTranslate(src, dst);
    } else if (entry.endsWith(".json")) {
      console.log(`Translating ${relative(SRC_ROOT, src)}`);
      await translateFile(src, dst);
    }
  }
}

for (const story of STORIES_TO_COPY) {
  await walkAndTranslate(join(SRC_ROOT, story), join(DST_ROOT, story));
}
console.log("Done.");
```

- [ ] **Step 2: Make it executable**

```bash
chmod +x scripts/translate-content.mjs
```

- [ ] **Step 3: Run translation** (requires Anthropic API key)

```bash
ANTHROPIC_API_KEY=<your-key> node scripts/translate-content.mjs
```

Expected: `content/narrator/narrator.json` and `content/story_pirates/...` populated with English versions.

- [ ] **Step 4: Manual review pass** β€” open `content/story_pirates/storylines/chapter1/*.json` and skim. Fix anything that lost flavor (especially Sparrow's pirate dialect, which often translates flat).

- [ ] **Step 5: Add a `voice` field to characters** β€” the legacy data has `"voice": "onyx"` for everyone. Update per the design spec voice mapping:
  - `content/narrator/narrator.json`: `"voice": "cedar"`
  - `content/story_pirates/manifest.json` narrator: `"voice": "ballad"`
  - `content/story_pirates/characters/sparrow.json`: `"voice": "ash"`
  - `content/story_pirates/characters/aria.json`: `"voice": "coral"`

- [ ] **Step 6: Commit**

```bash
git add scripts/ content/
git commit -m "feat(content): translated story_pirates and narrator to English"
```

---

### Task 16: Schema doc + sanity test against translated content

**Files:**
- Create: `content/SCHEMA.md`
- Create: `packages/story-engine/tests/playthrough.test.ts`

- [ ] **Step 1: Write `content/SCHEMA.md`** β€” authoritative schema doc

```markdown
# Story Content Schema (Reachy Tales)

This file documents the **actual** schema the `story-engine` reads.
It supersedes the legacy `STORIES_DOCUMENTATION.md` from the original AI_game project.

## Layout

```
content/
β”œβ”€β”€ narrator/
β”‚   └── narrator.json
└── <story_id>/
    β”œβ”€β”€ manifest.json
    β”œβ”€β”€ map.json
    β”œβ”€β”€ flags.json
    β”œβ”€β”€ story_state_template.json
    β”œβ”€β”€ characters/<id>.json
    β”œβ”€β”€ scenes/<id>.json
    └── storylines/chapter<n>/<node_id>.json
```

## File formats

(Brief schema description β€” kept minimal to avoid drift; engine code is the source of truth.)

### narrator.json / characters/<id>.json
```json
{
  "name": "string",
  "description": "string",
  "introduction": "string",
  "background": "string",
  "goal": "string",
  "voice": "string (OpenAI Realtime voice preset name, e.g. \"cedar\", \"ash\")",
  "voice_tone": "string"
}
```

### manifest.json
```json
{
  "id": "string (matches folder name)",
  "title": "string",
  "description": "string",
  "languages": ["en"],
  "entry_point": "storylines/chapter1/<node_id>.json",
  "narrator": { /* same shape as a character */ }
}
```

### scenes/<id>.json
```json
{
  "name": "string",
  "description": "string",
  "actions": [ { "id": "string", "description": "string", "effects": "string" } ],
  "characters_present": ["character_id_or_name"]
}
```

### storylines/chapter<n>/<node_id>.json
```json
{
  "id": "string",
  "scene": "scene_id",
  "type": "dialogue | narration | character_interaction",
  "speaker": "character_id_or_name | narrator | \"\"",
  "text": "string",
  "actions": [
    {
      "id": "string",
      "description": "string",
      "next": "node_id (optional, end-node if omitted)",
      "effects": { "set_flags": { "flag_name": true } }
    }
  ]
}
```

### map.json
```json
[
  {
    "from": "scene_id",
    "to": "scene_id",
    "description": "string",
    "conditions": [
      {
        "type": "requires_flag",
        "flag": "flag_name",
        "condition_failed": "string (player-facing explanation)"
      }
    ]
  }
]
```

### flags.json
```json
["flag_name_1", "flag_name_2"]
```

## Notes
- All strings are English. Bilingual `{ "en": "...", "fr": "..." }` envelopes from the legacy schema are NOT supported.
- Image fields (`picture`, `cover_image`) are ignored by the engine.
```

- [ ] **Step 2: Write `playthrough.test.ts`** β€” exercises the full pirate story end-to-end

```typescript
import { describe, it, expect } from "vitest";
import { StoryEngine } from "../src/engine.js";
import { loadNarrator, loadStory } from "../src/loader.js";
import { readFileSync, readdirSync } from "node:fs";
import { resolve } from "node:path";
import type { LoadedContent } from "../src/types.js";

const CONTENT = resolve(__dirname, "../../../content");
function readJsonFile(p: string): unknown { return JSON.parse(readFileSync(p, "utf-8")); }
function readJsonDir(dir: string): Record<string, unknown> {
  const out: Record<string, unknown> = {};
  for (const f of readdirSync(dir)) if (f.endsWith(".json")) out[f.replace(/\.json$/, "")] = readJsonFile(resolve(dir, f));
  return out;
}

function loadRealContent(): LoadedContent {
  const narrator = loadNarrator(readJsonFile(resolve(CONTENT, "narrator/narrator.json")));
  const pirates = loadStory({
    manifest: readJsonFile(resolve(CONTENT, "story_pirates/manifest.json")),
    map: readJsonFile(resolve(CONTENT, "story_pirates/map.json")),
    flags: readJsonFile(resolve(CONTENT, "story_pirates/flags.json")),
    characters: readJsonDir(resolve(CONTENT, "story_pirates/characters")),
    scenes: readJsonDir(resolve(CONTENT, "story_pirates/scenes")),
    storylines: readJsonDir(resolve(CONTENT, "story_pirates/storylines/chapter1")),
  });
  return { narrator, stories: { story_pirates: pirates } };
}

describe("story_pirates playthrough", () => {
  it("loads cleanly and reports the expected starting state", () => {
    const engine = new StoryEngine(loadRealContent());
    const r = engine.enterStoryMode("story_pirates");
    expect(r.events.find((e) => e.type === "blocked")).toBeUndefined();
    expect(r.state.currentNodeId).toBe("meet_sparrow");
    expect(r.state.currentSceneId).toBe("tavern");
  });

  it("happy-path traversal: respect Sparrow β†’ ask treasure β†’ ... reaches an end", () => {
    const engine = new StoryEngine(loadRealContent());
    engine.enterStoryMode("story_pirates");
    // Walk the friendly branch as far as the data allows
    const visited: string[] = [];
    const walk = (actionId: string, maxSteps = 20): void => {
      for (let step = 0; step < maxSteps; step++) {
        const r = engine.advanceStoryline(actionId);
        if (r.events.some((e) => e.type === "blocked")) break;
        const node = engine.getCurrentNode();
        if (!node || node.actions.length === 0) break;
        visited.push(node.id);
        actionId = node.actions[0]!.id;
      }
    };
    walk("greet_respectfully");
    expect(visited.length).toBeGreaterThan(0);
  });
});
```

- [ ] **Step 3: Run β€” should PASS** (real content is loaded successfully)

```bash
npm test --workspace story-engine
```

If it fails, the translated content is malformed somewhere β€” fix the JSON or the engine.

- [ ] **Step 4: Commit**

```bash
git add content/SCHEMA.md packages/story-engine/tests/playthrough.test.ts
git commit -m "docs(content): authoritative SCHEMA + playthrough integration test"
```

---

## Phase 4 β€” JS app scaffolding

### Task 17: Vite app scaffolding + minimal index.html

**Files:**
- Create: `tsconfig.app.json`
- Create: `vite.config.ts`
- Create: `index.html`
- Create: `src/style.css`
- Modify: root `package.json` to add Vite-side deps

- [ ] **Step 1: Add Vite-side deps to root `package.json`**

Modify root `package.json`:

```json
{
  "dependencies": {
    "story-engine": "0.1.0"
  },
  "devDependencies": {
    "typescript": "^5.6.3",
    "vite": "^5.4.10"
  }
}
```

Run:

```bash
cd /Users/nicolasrabault/Projects/reachy-tales
npm install
```

- [ ] **Step 2: Write `tsconfig.app.json`** for the JS app side

```json
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "types": []
  },
  "include": ["src/**/*", "index.html"]
}
```

- [ ] **Step 3: Write `vite.config.ts`** β€” including the OpenAI proxy rules used in dev

```typescript
import { defineConfig } from "vite";

export default defineConfig({
  server: {
    port: 5173,
    proxy: {
      "/openai/v1/realtime": {
        target: "https://api.openai.com",
        changeOrigin: true,
        secure: true,
        rewrite: (p) => p.replace(/^\/openai/, ""),
        ws: true,
      },
      "/openai/v1/chat/completions": {
        target: "https://api.openai.com",
        changeOrigin: true,
        secure: true,
        rewrite: (p) => p.replace(/^\/openai/, ""),
      },
    },
  },
  build: {
    outDir: "dist",
    target: "es2022",
  },
});
```

- [ ] **Step 4: Write `index.html`** β€” the single-orb UI (adapted from the reference app)

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Reachy Tales</title>
    <link rel="stylesheet" href="/src/style.css" />
  </head>
  <body>
    <main class="orb-wrap">
      <button id="main-circle" class="circle state-signed-out" aria-label="Main action">
        <span class="circle-inner"></span>
      </button>
      <p id="circle-caption">Sign in</p>

      <div id="tool-toast" hidden>
        <span class="tool-toast-text"></span>
      </div>

      <aside id="robot-picker" hidden>
        <h2>Choose a Reachy</h2>
        <ul id="robot-list"></ul>
      </aside>

      <div id="hf-user" hidden>
        <img id="hf-avatar" alt="" />
        <span id="hf-user-name"></span>
      </div>

      <button id="mic-btn" hidden aria-label="Mute mic">🎀</button>
      <button id="stop-btn" hidden aria-label="Stop">⏹</button>

      <details id="settings">
        <summary>Settings</summary>
        <label>HF OAuth Client ID <input id="setting-hf-id" /></label>
        <label>OpenAI API Key <input id="setting-openai-key" type="password" /></label>
        <label>Realtime model <input id="setting-realtime-model" placeholder="gpt-realtime" /></label>
        <label>Summary model <input id="setting-summary-model" placeholder="gpt-4o-mini" /></label>
        <label>Default narrator voice <input id="setting-default-voice" placeholder="cedar" /></label>
        <button id="settings-save">Save</button>
      </details>
    </main>

    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
```

- [ ] **Step 5: Write a minimal `src/style.css`** β€” a working starting point; refine later

```css
:root {
  --bg: #0d1117;
  --fg: #e6edf3;
  --orb-base: #2d3748;
  --orb-listening: #38b2ac;
  --orb-speaking-user: #ed8936;
  --orb-speaking-ai: #9f7aea;
}
* { box-sizing: border-box; }
body {
  margin: 0; padding: 0;
  background: var(--bg); color: var(--fg);
  font-family: system-ui, -apple-system, sans-serif;
  display: flex; align-items: center; justify-content: center;
  min-height: 100vh;
}
.orb-wrap { display: flex; flex-direction: column; align-items: center; gap: 1.5rem; }
.circle {
  width: 240px; height: 240px; border-radius: 50%;
  border: none; background: var(--orb-base);
  cursor: pointer; transition: background 0.3s, transform 0.2s;
  box-shadow: 0 0 60px rgba(0,0,0,0.5);
}
.circle:disabled { cursor: not-allowed; opacity: 0.6; }
.circle.state-listening { background: var(--orb-listening); animation: pulse 2s infinite; }
.circle.state-user-speaking { background: var(--orb-speaking-user); }
.circle.state-ai-speaking { background: var(--orb-speaking-ai); animation: pulse 1s infinite; }
.circle.state-swapping-character, .circle.state-swapping-story { animation: spin 1.2s linear infinite; }
@keyframes pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.05); } }
@keyframes spin { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } }
#circle-caption { font-size: 1.1rem; opacity: 0.9; }
#tool-toast {
  position: fixed; bottom: 2rem; left: 50%; transform: translateX(-50%);
  background: rgba(0,0,0,0.8); padding: 0.5rem 1rem; border-radius: 4px;
}
#settings { position: fixed; top: 1rem; right: 1rem; }
#settings label { display: block; margin: 0.5rem 0; }
#settings input { width: 280px; }
#hf-user { position: fixed; top: 1rem; left: 1rem; display: flex; gap: 0.5rem; align-items: center; }
#hf-avatar { width: 32px; height: 32px; border-radius: 50%; }
#mic-btn, #stop-btn { font-size: 1.5rem; padding: 0.5rem 1rem; }
```

- [ ] **Step 6: Write a stub `src/main.ts` so dev server can boot**

```typescript
import "./style.css";
console.log("Reachy Tales β€” boot");
```

- [ ] **Step 7: Verify dev server starts**

```bash
npm run dev
# Open http://localhost:5173 β€” should show the orb UI; ctrl-C to stop.
```

- [ ] **Step 8: Verify build**

```bash
npm run build
```

Expected: `dist/` created, no errors.

- [ ] **Step 9: Commit**

```bash
git add tsconfig.app.json vite.config.ts index.html src/ package-lock.json package.json
git commit -m "feat(app): Vite scaffolding + orb UI shell"
```

---

### Task 18: Copy plumbing files from the reference app

**Files:**
- Create: `src/openai-realtime.ts`
- Create: `src/antennas.ts`
- Create: `src/head-wobbler.ts`
- Create: `src/move-player.ts`
- Create: `src/globals.d.ts`
- Create: `src/robot-tools.ts`

- [ ] **Step 1: Copy `openai-realtime.ts`** verbatim from the reference

```bash
curl -sL "https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app/raw/main/src/openai-realtime.ts" \
  > /Users/nicolasrabault/Projects/reachy-tales/src/openai-realtime.ts
```

- [ ] **Step 2: Copy `antennas.ts`**

```bash
curl -sL "https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app/raw/main/src/antennas.ts" \
  > /Users/nicolasrabault/Projects/reachy-tales/src/antennas.ts
```

- [ ] **Step 3: Copy `head-wobbler.ts`**

```bash
curl -sL "https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app/raw/main/src/head-wobbler.ts" \
  > /Users/nicolasrabault/Projects/reachy-tales/src/head-wobbler.ts
```

- [ ] **Step 4: Copy `move-player.ts`**

```bash
curl -sL "https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app/raw/main/src/move-player.ts" \
  > /Users/nicolasrabault/Projects/reachy-tales/src/move-player.ts
```

- [ ] **Step 5: Copy `globals.d.ts`**

```bash
curl -sL "https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app/raw/main/src/globals.d.ts" \
  > /Users/nicolasrabault/Projects/reachy-tales/src/globals.d.ts
```

- [ ] **Step 6: Extract `robot-tools.ts` from the reference's `main.ts`** β€” the `HEAD_POSES`, `ROBOT_TOOLS` definitions and the dispatch handlers (search the reference `main.ts` for `const HEAD_POSES`, `const ROBOT_TOOLS`, and the tool-execution code paths starting around line 60-115 and the dispatch around the realtime client setup). Copy those pieces into a new file `src/robot-tools.ts`.

```typescript
// src/robot-tools.ts β€” extracted from the reference app's main.ts
import {
  MovePlayer,
  MOVE_CATALOG,
  MOVE_IDS,
  type MoveId,
} from "./move-player.js";
import type { ReachyMiniInstance } from "./globals.d.ts";
import type { RealtimeTool } from "./openai-realtime.js";

const HEAD_POSES = {
  center: { roll: 0, pitch: 0, yaw: 0 },
  up: { roll: 0, pitch: -18, yaw: 0 },
  down: { roll: 0, pitch: 18, yaw: 0 },
  left: { roll: 0, pitch: 0, yaw: 25 },
  right: { roll: 0, pitch: 0, yaw: -25 },
  tilt_left: { roll: -15, pitch: 0, yaw: 0 },
  tilt_right: { roll: 15, pitch: 0, yaw: 0 },
} as const;

export const ROBOT_TOOLS: RealtimeTool[] = [
  {
    name: "move_head",
    description:
      "Point the robot's head in a named direction. Use to accompany speech with a tiny gesture.",
    parameters: {
      type: "object",
      properties: {
        direction: { type: "string", enum: Object.keys(HEAD_POSES),
                     description: "Named head pose to assume." },
      },
      required: ["direction"],
    },
  },
  {
    name: "play_move",
    description:
      "Trigger a short pre-recorded body-language move (1-4s) from the Reachy library.\n" +
      MOVE_CATALOG.map((m) => `  - ${m.id} | ${m.kind} | ${m.description}`).join("\n"),
    parameters: {
      type: "object",
      properties: {
        name: { type: "string", enum: [...MOVE_IDS],
                description: "Catalog id." },
      },
      required: ["name"],
    },
  },
];

export class RobotToolDispatcher {
  private movePlayer: MovePlayer;
  constructor(robot: ReachyMiniInstance) {
    this.movePlayer = new MovePlayer(robot);
  }
  async handle(robot: ReachyMiniInstance, name: string, args: Record<string, unknown>): Promise<string> {
    if (name === "move_head") {
      const dir = args.direction as keyof typeof HEAD_POSES;
      const pose = HEAD_POSES[dir];
      if (!pose) return `Unknown direction: ${args.direction}`;
      robot.setHeadPose(pose.roll, pose.pitch, pose.yaw);
      return `Head moved to ${dir}.`;
    }
    if (name === "play_move") {
      const moveId = args.name as MoveId;
      await this.movePlayer.play(moveId);
      return `Played move: ${moveId}.`;
    }
    return `Unknown robot tool: ${name}`;
  }
}
```

- [ ] **Step 7: Verify build still works**

```bash
npm run build
```

Expected: build succeeds. If TypeScript errors arise from the copied files (e.g. import paths use `.ts` vs `.js`), normalize them β€” Vite + TypeScript "bundler" resolution accepts `.ts` extensions in imports.

- [ ] **Step 8: Commit**

```bash
git add src/
git commit -m "feat(app): copy plumbing (openai-realtime, antennas, head-wobbler, move-player, robot-tools) from reference app"
```

---

### Task 19: Story tools definitions for the LLM

**Files:**
- Create: `src/story-tools.ts`

- [ ] **Step 1: Write `src/story-tools.ts`** β€” re-exports the engine's tool definitions in the shape expected by the OpenAI Realtime client (matches `RealtimeTool` from the copied `openai-realtime.ts`)

```typescript
import type { ToolDef } from "story-engine";
import type { RealtimeTool } from "./openai-realtime.js";

/**
 * Convert engine ToolDef[] to the RealtimeTool[] shape used by openai-realtime.ts.
 * The shapes are structurally compatible; this is a typed pass-through.
 */
export function toRealtimeTools(toolDefs: ToolDef[]): RealtimeTool[] {
  return toolDefs as RealtimeTool[];
}

export const STORY_TOOL_NAMES = [
  "select_story",
  "advance_storyline",
  "navigate_scene",
  "perform_scene_action",
  "request_options",
  "exit_story",
] as const;
export type StoryToolName = (typeof STORY_TOOL_NAMES)[number];

export function isStoryTool(name: string): name is StoryToolName {
  return (STORY_TOOL_NAMES as readonly string[]).includes(name);
}
```

- [ ] **Step 2: Verify build**

```bash
npm run build
```

If `RealtimeTool`'s shape isn't structurally identical, adjust `toRealtimeTools` to re-shape. Most likely both use the same `{ name, description, parameters: { type, properties, required } }` form.

- [ ] **Step 3: Commit**

```bash
git add src/story-tools.ts
git commit -m "feat(app): story-tools.ts β€” bridge engine ToolDef β†’ RealtimeTool"
```

---

### Task 20: Summary builder

**Files:**
- Create: `src/summary-builder.ts`

- [ ] **Step 1: Write `src/summary-builder.ts`** β€” calls the proxied `/openai/v1/chat/completions` to summarize recent transitions on character swap

```typescript
import type { TransitionEvent } from "story-engine";

export interface SummaryBuilderOptions {
  apiKey: string;
  model?: string;          // defaults to gpt-4o-mini
  baseUrl?: string;        // defaults to /openai/v1/chat/completions
}

export class SummaryBuilder {
  private apiKey: string;
  private model: string;
  private baseUrl: string;

  constructor(opts: SummaryBuilderOptions) {
    this.apiKey = opts.apiKey;
    this.model = opts.model ?? "gpt-4o-mini";
    this.baseUrl = opts.baseUrl ?? "/openai/v1/chat/completions";
  }

  async summarize(events: TransitionEvent[]): Promise<string> {
    if (events.length === 0) return "(The story is just beginning.)";
    const log = events
      .map((e) => {
        switch (e.type) {
          case "storyEntered": return `Story "${e.storyId}" began.`;
          case "storyExited": return `User exited the story.`;
          case "sceneChanged": return `Scene changed: ${e.from ?? "?"} β†’ ${e.to}.`;
          case "speakerChanged": return `Now speaking: ${e.to} (was ${e.from ?? "narrator"}).`;
          case "flagSet": return `Flag set: ${e.name} = ${e.value}.`;
          case "blocked": return `Blocked: ${e.reason}.`;
        }
      })
      .join("\n");

    const prompt = `Given these recent story events, write a 2-3 sentence summary suitable for handing off to a new character voice. Capture what just happened and what the user was doing. Plain spoken English, no markdown.\n\nEvents:\n${log}`;

    const res = await fetch(this.baseUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${this.apiKey}`,
      },
      body: JSON.stringify({
        model: this.model,
        messages: [{ role: "user", content: prompt }],
        max_tokens: 200,
        temperature: 0.4,
      }),
    });
    if (!res.ok) {
      throw new Error(`Summary API ${res.status}: ${await res.text()}`);
    }
    const data = await res.json();
    return data.choices[0]?.message?.content?.trim() ?? "(No summary available.)";
  }
}
```

- [ ] **Step 2: Verify build**

```bash
npm run build
```

- [ ] **Step 3: Commit**

```bash
git add src/summary-builder.ts
git commit -m "feat(app): summary-builder for character-swap context handoff"
```

---

### Task 21: Story bridge β€” engine ↔ Realtime adapter

**Files:**
- Create: `src/story-bridge.ts`

The bridge holds the `StoryEngine`, the active `OpenaiRealtimeClient`, and the `RobotToolDispatcher`. It dispatches tool calls and orchestrates voice-swap session restarts.

- [ ] **Step 1: Write `src/story-bridge.ts`**

```typescript
import { StoryEngine, type TransitionResult, type LoadedContent } from "story-engine";
import { OpenaiRealtimeClient } from "./openai-realtime.js";
import { SummaryBuilder } from "./summary-builder.js";
import { ROBOT_TOOLS, RobotToolDispatcher } from "./robot-tools.js";
import { toRealtimeTools, isStoryTool } from "./story-tools.js";
import type { ReachyMiniInstance } from "./globals.d.ts";

export interface StoryBridgeOptions {
  content: LoadedContent;
  robot: ReachyMiniInstance;
  apiKey: string;
  realtimeModel: string;          // e.g. "gpt-realtime"
  summaryModel: string;           // e.g. "gpt-4o-mini"
  defaultVoice: string;           // fallback if a character has no voice
  /** Provider for the input audio track (the robot's mic). */
  getRobotMicTrack: () => MediaStreamTrack | null;
  /** Called when the OpenAI output track is ready, so caller can route it to the robot. */
  onOpenAiOutputTrack: (track: MediaStreamTrack) => void;
  /** Called whenever the app should react visually (state machine transitions). */
  onAppStateChange: (state: BridgeAppState) => void;
}

export type BridgeAppState =
  | "starting"
  | "listening"
  | "user-speaking"
  | "processing"
  | "ai-speaking"
  | "swapping-character"
  | "swapping-story"
  | "error";

export class StoryBridge {
  private engine: StoryEngine;
  private realtime: OpenaiRealtimeClient | null = null;
  private summary: SummaryBuilder;
  private robotDispatcher: RobotToolDispatcher;
  private currentVoice: string | null = null;
  private opts: StoryBridgeOptions;

  constructor(opts: StoryBridgeOptions) {
    this.opts = opts;
    this.engine = new StoryEngine(opts.content);
    this.summary = new SummaryBuilder({ apiKey: opts.apiKey, model: opts.summaryModel });
    this.robotDispatcher = new RobotToolDispatcher(opts.robot);
  }

  async start(): Promise<void> {
    this.opts.onAppStateChange("starting");
    const narrator = this.engine.getCurrentCharacter();
    const voice = narrator?.voice ?? this.opts.defaultVoice;
    await this.openSession(voice);
    this.opts.onAppStateChange("listening");
  }

  async stop(): Promise<void> {
    if (this.realtime) {
      await this.realtime.close();
      this.realtime = null;
    }
  }

  private async openSession(voice: string): Promise<void> {
    const tools = [...toRealtimeTools(this.engine.buildToolDefinitions()), ...ROBOT_TOOLS];
    const instructions = this.engine.buildSystemPrompt();
    this.realtime = new OpenaiRealtimeClient({
      apiKey: this.opts.apiKey,
      model: this.opts.realtimeModel,
      voice,
      instructions,
      tools,
      inputAudioTrack: this.opts.getRobotMicTrack(),
      onOutputTrack: this.opts.onOpenAiOutputTrack,
      onToolCall: (name, args) => this.handleToolCall(name, args),
      onStateChange: (s) => this.translateRealtimeState(s),
    });
    await this.realtime.connect();
    this.currentVoice = voice;
  }

  private translateRealtimeState(rtState: string): void {
    // Map openai-realtime states to BridgeAppState
    switch (rtState) {
      case "listening":
      case "user-speaking":
      case "processing":
      case "ai-speaking":
        this.opts.onAppStateChange(rtState as BridgeAppState);
        break;
      case "error":
        this.opts.onAppStateChange("error");
        break;
    }
  }

  /** Called by openai-realtime.ts when the LLM emits a tool call. */
  async handleToolCall(name: string, args: Record<string, unknown>): Promise<string> {
    if (!isStoryTool(name)) {
      return this.robotDispatcher.handle(this.opts.robot, name, args);
    }
    let result: TransitionResult;
    switch (name) {
      case "select_story":
        result = this.engine.enterStoryMode(args.storyId as string);
        return this.applyTransition(result, "swapping-story");
      case "advance_storyline":
        result = this.engine.advanceStoryline(args.actionId as string);
        return this.applyTransition(result);
      case "navigate_scene":
        result = this.engine.navigateScene(args.sceneId as string);
        return this.applyTransition(result);
      case "perform_scene_action":
        result = this.engine.performSceneAction(args.actionId as string);
        return this.applyTransition(result);
      case "request_options":
        return this.engine.formatOptionsRecap();
      case "exit_story":
        result = this.engine.exitStoryMode();
        return this.applyTransition(result, "swapping-story");
      default:
        return `Unknown tool: ${name}`;
    }
  }

  private async applyTransition(
    result: TransitionResult,
    transientState: "swapping-character" | "swapping-story" = "swapping-character",
  ): Promise<string> {
    const blocked = result.events.find((e) => e.type === "blocked");
    if (blocked) return `Cannot do that: ${(blocked as Extract<typeof blocked, { type: "blocked" }>).reason}`;

    const speakerChange = result.events.find((e) => e.type === "speakerChanged") as
      | Extract<TransitionResult["events"][number], { type: "speakerChanged" }>
      | undefined;

    if (speakerChange) {
      const newVoice = speakerChange.newCharacter.voice ?? this.opts.defaultVoice;
      if (newVoice !== this.currentVoice) {
        this.opts.onAppStateChange(transientState);
        await this.swapSession(newVoice);
        this.opts.onAppStateChange("ai-speaking");
        return ""; // new session takes over
      }
    }

    // Same voice β€” just push updated instructions + tool defs to the live session
    if (this.realtime) {
      await this.realtime.updateSession({
        instructions: this.engine.buildSystemPrompt(),
        tools: [...toRealtimeTools(this.engine.buildToolDefinitions()), ...ROBOT_TOOLS],
      });
    }
    return this.engine.getCurrentNode()?.text ?? "";
  }

  private async swapSession(newVoice: string): Promise<void> {
    let summaryText = "(no summary)";
    try {
      summaryText = await this.summary.summarize(this.engine.getRecentTransitionLog());
    } catch (e) {
      console.warn("Summary failed, continuing with no summary:", e);
    }
    if (this.realtime) {
      await this.realtime.close();
      this.realtime = null;
    }
    const tools = [...toRealtimeTools(this.engine.buildToolDefinitions()), ...ROBOT_TOOLS];
    const instructions = this.engine.buildSystemPrompt() +
      `\n\n# RECENT STORY CONTEXT\n${summaryText}\n\nSpeak the next scripted line now, in character.`;
    this.realtime = new OpenaiRealtimeClient({
      apiKey: this.opts.apiKey,
      model: this.opts.realtimeModel,
      voice: newVoice,
      instructions,
      tools,
      inputAudioTrack: this.opts.getRobotMicTrack(),
      onOutputTrack: this.opts.onOpenAiOutputTrack,
      onToolCall: (name, args) => this.handleToolCall(name, args),
      onStateChange: (s) => this.translateRealtimeState(s),
    });
    await this.realtime.connect();
    this.currentVoice = newVoice;
  }
}
```

> **Note on `OpenaiRealtimeClient` API surface**: The reference app exposes the client's API in its `openai-realtime.ts` file. The bridge here assumes methods `connect()`, `close()`, `updateSession({ instructions, tools })`, and constructor options for `inputAudioTrack`, `onOutputTrack`, `onToolCall`, `onStateChange`. **Verify these match the actual reference file** after copying in Task 18 β€” adapt the bridge if names differ (e.g. the reference may call it `setSessionConfig` or `start`/`stop`). This is one of the items called out in Β§9 of the design spec.

- [ ] **Step 2: Verify build**

```bash
npm run build
```

If type errors flag missing methods on `OpenaiRealtimeClient`, read the actual `src/openai-realtime.ts` and adapt the bridge calls to match. Don't fake methods on the client β€” make the bridge use what the client actually exposes.

- [ ] **Step 3: Commit**

```bash
git add src/story-bridge.ts
git commit -m "feat(app): story-bridge orchestrating engine + realtime + voice swap"
```

---

### Task 22: Bridge transition unit tests with a fake OpenAI client

**Files:**
- Create: `tests/story-bridge.test.ts` (at repo root, with a small Vitest config for the app side)
- Create: `vitest.config.app.ts` (root)
- Modify: root `package.json` (add `test:app` script)

The bridge has logic worth testing without OpenAI / robot infrastructure. Use a recording fake for the realtime client.

- [ ] **Step 1: Write `vitest.config.app.ts`**

```typescript
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    include: ["tests/**/*.test.ts"],
    environment: "node",
  },
  resolve: {
    alias: {
      "story-engine": new URL("./packages/story-engine/src/index.ts", import.meta.url).pathname,
    },
  },
});
```

- [ ] **Step 2: Add a script to root `package.json`**

```json
  "scripts": {
    "...": "...",
    "test:app": "vitest run --config vitest.config.app.ts",
    "test:all": "npm run test --workspaces --if-present && npm run test:app"
  },
  "devDependencies": {
    "vitest": "^2.1.0"
  }
```

```bash
npm install
```

- [ ] **Step 3: Write the test** β€” `tests/story-bridge.test.ts`

```typescript
import { describe, it, expect, vi } from "vitest";
import { StoryBridge } from "../src/story-bridge";
import { loadNarrator, loadStory } from "story-engine";
import type { LoadedContent } from "story-engine";
import { readFileSync, readdirSync } from "node:fs";
import { resolve } from "node:path";

// Avoid actually instantiating the real OpenAI client + robot.
// Use module-mocking to swap them out.

vi.mock("../src/openai-realtime", () => {
  return {
    OpenaiRealtimeClient: class {
      static instances: any[] = [];
      opts: any;
      constructor(opts: any) {
        this.opts = opts;
        (this.constructor as any).instances.push(this);
      }
      async connect() { /* noop */ }
      async close() { /* noop */ }
      async updateSession(_opts: any) { /* noop */ }
    },
  };
});

vi.mock("../src/summary-builder", () => {
  return {
    SummaryBuilder: class {
      async summarize() { return "Stub summary."; }
    },
  };
});

vi.mock("../src/robot-tools", () => {
  return {
    ROBOT_TOOLS: [],
    RobotToolDispatcher: class {
      async handle() { return "ok"; }
    },
  };
});

const FIX = resolve(__dirname, "../packages/story-engine/tests/fixtures");
function readJsonFile(p: string): unknown { return JSON.parse(readFileSync(p, "utf-8")); }
function readJsonDir(dir: string): Record<string, unknown> {
  const out: Record<string, unknown> = {};
  for (const f of readdirSync(dir)) if (f.endsWith(".json")) out[f.replace(/\.json$/, "")] = readJsonFile(resolve(dir, f));
  return out;
}

function loadFixtureContent(): LoadedContent {
  const narrator = loadNarrator(readJsonFile(resolve(FIX, "narrator/narrator.json")));
  const story = loadStory({
    manifest: readJsonFile(resolve(FIX, "story_test/manifest.json")),
    map: readJsonFile(resolve(FIX, "story_test/map.json")),
    flags: readJsonFile(resolve(FIX, "story_test/flags.json")),
    characters: readJsonDir(resolve(FIX, "story_test/characters")),
    scenes: readJsonDir(resolve(FIX, "story_test/scenes")),
    storylines: readJsonDir(resolve(FIX, "story_test/storylines/chapter1")),
  });
  return { narrator, stories: { story_test: story } };
}

function makeFakeRobot(): any {
  return { setHeadPose: vi.fn(), setAntennas: vi.fn(), playSound: vi.fn() };
}

describe("StoryBridge", () => {
  it("starts a session in menu mode with the narrator's voice", async () => {
    const stateChanges: string[] = [];
    const bridge = new StoryBridge({
      content: loadFixtureContent(),
      robot: makeFakeRobot(),
      apiKey: "test-key",
      realtimeModel: "gpt-realtime",
      summaryModel: "gpt-4o-mini",
      defaultVoice: "cedar",
      getRobotMicTrack: () => null,
      onOpenAiOutputTrack: () => {},
      onAppStateChange: (s) => { stateChanges.push(s); },
    });
    await bridge.start();
    const { OpenaiRealtimeClient } = await import("../src/openai-realtime");
    const inst = (OpenaiRealtimeClient as any).instances[0];
    expect(inst.opts.voice).toBe("cedar");
    expect(stateChanges).toContain("starting");
    expect(stateChanges).toContain("listening");
  });

  it("on select_story tool call β†’ transitions to story and swaps voice to character", async () => {
    const bridge = new StoryBridge({
      content: loadFixtureContent(),
      robot: makeFakeRobot(),
      apiKey: "test-key",
      realtimeModel: "gpt-realtime",
      summaryModel: "gpt-4o-mini",
      defaultVoice: "cedar",
      getRobotMicTrack: () => null,
      onOpenAiOutputTrack: () => {},
      onAppStateChange: () => {},
    });
    await bridge.start();
    await bridge.handleToolCall("select_story", { storyId: "story_test" });
    const { OpenaiRealtimeClient } = await import("../src/openai-realtime");
    const inst = (OpenaiRealtimeClient as any).instances[1]; // second client = post-swap
    expect(inst.opts.voice).toBe("ash"); // Sparrow's voice
  });

  it("on advance_storyline β†’ no voice swap when speaker unchanged", async () => {
    const bridge = new StoryBridge({
      content: loadFixtureContent(),
      robot: makeFakeRobot(),
      apiKey: "test-key",
      realtimeModel: "gpt-realtime",
      summaryModel: "gpt-4o-mini",
      defaultVoice: "cedar",
      getRobotMicTrack: () => null,
      onOpenAiOutputTrack: () => {},
      onAppStateChange: () => {},
    });
    await bridge.start();
    await bridge.handleToolCall("select_story", { storyId: "story_test" });
    const { OpenaiRealtimeClient } = await import("../src/openai-realtime");
    const countBefore = (OpenaiRealtimeClient as any).instances.length;
    await bridge.handleToolCall("advance_storyline", { actionId: "greet_respectfully" });
    const countAfter = (OpenaiRealtimeClient as any).instances.length;
    expect(countAfter).toBe(countBefore); // no new session opened
  });
});
```

- [ ] **Step 4: Run app tests**

```bash
npm run test:app
```

If the test file imports fail (e.g. circular workspace resolution), adjust `vitest.config.app.ts` aliases until it works.

- [ ] **Step 5: Commit**

```bash
git add tests/ vitest.config.app.ts package.json package-lock.json
git commit -m "test(app): bridge transition unit tests with fake realtime client"
```

---

## Phase 5 β€” JS app orchestration (main.ts wiring)

### Task 23: Settings + OAuth + robot connection (port from reference app)

**Files:**
- Modify: `src/main.ts`

This task ports the OAuth + robot-connection + settings logic from the reference app's `main.ts`. We'll keep our story-aware additions for the next task.

- [ ] **Step 1: Read the reference `main.ts`** β€” focus on lines that handle:
  - Settings load/save (localStorage keys: `reachyMini.hf.clientId`, `reachyMini.openai.apiKey`, `reachyMini.openai.model`, `reachyMini.openai.voice`)
  - HF OAuth: `robot.authenticate()`, `robot.login()`, OAuth callback handling
  - Robot connection: `robot.connect()`, robot picker, `robot.startSession(robotId)`
  - State machine + orb DOM updates

```bash
curl -sL "https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app/raw/main/src/main.ts" \
  > /tmp/reference-main.ts
wc -l /tmp/reference-main.ts
```

- [ ] **Step 2: Write `src/main.ts`** β€” adapt the reference, replacing the simple instructions/tools wiring with our `StoryBridge`. Only the parts that change:

```typescript
import "./style.css";

import { ReachyMini } from "/* CDN */";
// import resolved at runtime β€” see reference app for exact import path / ESM module URL.
// Use the JS SDK loaded from jsDelivr per AGENTS.md:
//   import { ReachyMini } from "https://cdn.jsdelivr.net/gh/pollen-robotics/reachy_mini@<TAG>/js/reachy-mini.js";
// At plan time, look up the latest tag with:
//   git ls-remote --tags --refs --sort=-v:refname https://github.com/pollen-robotics/reachy_mini.git | head -1

import { HeadWobbler } from "./head-wobbler.js";
import { AntennasOscillator } from "./antennas.js";
import { StoryBridge, type BridgeAppState } from "./story-bridge.js";
import { loadNarrator, loadStory } from "story-engine";
import type { LoadedContent } from "story-engine";

// ─── Content loading (Vite bundles content/ as static assets) ────────────

// Vite supports `import.meta.glob` for batch-importing JSON.
const narratorJson = (await import("../content/narrator/narrator.json")).default;
const piratesManifest = (await import("../content/story_pirates/manifest.json")).default;
const piratesMap = (await import("../content/story_pirates/map.json")).default;
const piratesFlags = (await import("../content/story_pirates/flags.json")).default;

const piratesCharacters: Record<string, any> = {};
const characterModules = import.meta.glob("../content/story_pirates/characters/*.json", { eager: true });
for (const [path, mod] of Object.entries(characterModules)) {
  const id = path.split("/").pop()!.replace(/\.json$/, "");
  piratesCharacters[id] = (mod as any).default;
}

const piratesScenes: Record<string, any> = {};
const sceneModules = import.meta.glob("../content/story_pirates/scenes/*.json", { eager: true });
for (const [path, mod] of Object.entries(sceneModules)) {
  const id = path.split("/").pop()!.replace(/\.json$/, "");
  piratesScenes[id] = (mod as any).default;
}

const piratesStorylines: Record<string, any> = {};
const storylineModules = import.meta.glob("../content/story_pirates/storylines/chapter1/*.json", { eager: true });
for (const [path, mod] of Object.entries(storylineModules)) {
  const id = path.split("/").pop()!.replace(/\.json$/, "");
  piratesStorylines[id] = (mod as any).default;
}

const content: LoadedContent = {
  narrator: loadNarrator(narratorJson),
  stories: {
    story_pirates: loadStory({
      manifest: piratesManifest,
      map: piratesMap,
      flags: piratesFlags,
      characters: piratesCharacters,
      scenes: piratesScenes,
      storylines: piratesStorylines,
    }),
  },
};

// ─── Settings persistence (matching the reference app keys) ─────────────

const STORAGE_KEYS = {
  hfClientId: "reachyMini.hf.clientId",
  apiKey: "reachyMini.openai.apiKey",
  realtimeModel: "reachyTales.openai.realtimeModel",
  summaryModel: "reachyTales.openai.summaryModel",
  defaultVoice: "reachyTales.openai.defaultVoice",
} as const;

function loadSettings() {
  return {
    hfClientId: localStorage.getItem(STORAGE_KEYS.hfClientId) ?? "",
    apiKey: localStorage.getItem(STORAGE_KEYS.apiKey) ?? "",
    realtimeModel: localStorage.getItem(STORAGE_KEYS.realtimeModel) ?? "gpt-realtime",
    summaryModel: localStorage.getItem(STORAGE_KEYS.summaryModel) ?? "gpt-4o-mini",
    defaultVoice: localStorage.getItem(STORAGE_KEYS.defaultVoice) ?? "cedar",
  };
}

function saveSettings(s: ReturnType<typeof loadSettings>) {
  localStorage.setItem(STORAGE_KEYS.hfClientId, s.hfClientId);
  localStorage.setItem(STORAGE_KEYS.apiKey, s.apiKey);
  localStorage.setItem(STORAGE_KEYS.realtimeModel, s.realtimeModel);
  localStorage.setItem(STORAGE_KEYS.summaryModel, s.summaryModel);
  localStorage.setItem(STORAGE_KEYS.defaultVoice, s.defaultVoice);
}

// ─── DOM refs ────────────────────────────────────────────────────────────

function $<T extends HTMLElement>(sel: string): T {
  const el = document.querySelector<T>(sel);
  if (!el) throw new Error(`Missing element: ${sel}`);
  return el;
}

const circleBtn = $<HTMLButtonElement>("#main-circle");
const circleCaption = $<HTMLParagraphElement>("#circle-caption");
const settingsHfId = $<HTMLInputElement>("#setting-hf-id");
const settingsApiKey = $<HTMLInputElement>("#setting-openai-key");
const settingsRealtimeModel = $<HTMLInputElement>("#setting-realtime-model");
const settingsSummaryModel = $<HTMLInputElement>("#setting-summary-model");
const settingsDefaultVoice = $<HTMLInputElement>("#setting-default-voice");
const settingsSave = $<HTMLButtonElement>("#settings-save");

// Populate settings UI
const initialSettings = loadSettings();
settingsHfId.value = initialSettings.hfClientId;
settingsApiKey.value = initialSettings.apiKey;
settingsRealtimeModel.value = initialSettings.realtimeModel;
settingsSummaryModel.value = initialSettings.summaryModel;
settingsDefaultVoice.value = initialSettings.defaultVoice;
settingsSave.addEventListener("click", () => {
  saveSettings({
    hfClientId: settingsHfId.value, apiKey: settingsApiKey.value,
    realtimeModel: settingsRealtimeModel.value, summaryModel: settingsSummaryModel.value,
    defaultVoice: settingsDefaultVoice.value,
  });
  alert("Settings saved.");
});

// ─── App state ───────────────────────────────────────────────────────────

type AppState =
  | "signed-out" | "authenticated" | "connecting" | "connected"
  | "starting" | "listening" | "user-speaking" | "processing" | "ai-speaking"
  | "swapping-character" | "swapping-story" | "error";

const STATE_CAPTIONS: Record<AppState, string> = {
  "signed-out": "Sign in",
  authenticated: "Tap to start",
  connecting: "Connecting…",
  connected: "Choose a Reachy",
  starting: "Starting…",
  listening: "",
  "user-speaking": "",
  processing: "",
  "ai-speaking": "",
  "swapping-character": "Changing voice…",
  "swapping-story": "Loading story…",
  error: "Tap to retry",
};

let appState: AppState = "signed-out";
function setAppState(s: AppState) {
  appState = s;
  circleBtn.className = `circle state-${s}`;
  circleCaption.textContent = STATE_CAPTIONS[s];
}

// ─── Robot connection β€” borrowed from the reference app ───────────────────

const robot = new ReachyMini({ appName: "reachy-tales" });
let bridge: StoryBridge | null = null;

// On startup: check authentication
if (await robot.authenticate()) {
  setAppState("authenticated");
}

circleBtn.addEventListener("click", async () => {
  if (appState === "signed-out") {
    if (!initialSettings.hfClientId) {
      alert("Set your HF OAuth Client ID in settings first.");
      return;
    }
    robot.login(initialSettings.hfClientId);
    return;
  }
  if (appState === "authenticated") {
    setAppState("connecting");
    await robot.connect();
    setAppState("connected");
    // robotsChanged listener handles the picker
    return;
  }
  if (appState === "connected") {
    // robot picker not implemented in this minimal port; auto-pick the first robot.
    return;
  }
  if (appState === "error") {
    location.reload();
    return;
  }
});

robot.addEventListener("robotsChanged", async (e: any) => {
  const robots = e.detail.robots;
  if (robots.length === 0) return;
  const robotId = robots[0].id;
  setAppState("starting");
  await robot.startSession(robotId);

  // Set up body motion
  new AntennasOscillator({ onAntennas: (r, l) => robot.setAntennas(r, l) }).start();

  // Build and start the story bridge
  const settings = loadSettings();
  if (!settings.apiKey) {
    alert("Set your OpenAI API key in settings first.");
    setAppState("error");
    return;
  }
  bridge = new StoryBridge({
    content,
    robot,
    apiKey: settings.apiKey,
    realtimeModel: settings.realtimeModel,
    summaryModel: settings.summaryModel,
    defaultVoice: settings.defaultVoice,
    getRobotMicTrack: () => {
      // The reference app pulls the robot's mic from robot._pc.getReceivers().
      // Reuse that pattern here.
      const pc = (robot as any)._pc as RTCPeerConnection;
      const receiver = pc.getReceivers().find((r) => r.track?.kind === "audio");
      return receiver?.track ?? null;
    },
    onOpenAiOutputTrack: (track) => {
      const pc = (robot as any)._pc as RTCPeerConnection;
      const audioSender = pc.getSenders().find((s) => s.track?.kind === "audio");
      audioSender?.replaceTrack(track);

      // Wire head-wobbler to the OpenAI output track for speech-driven sway
      const wobbler = new HeadWobbler({
        onPose: (roll, pitch, yaw) => robot.setHeadPose(roll, pitch, yaw),
      });
      wobbler.attachTrack(track);
    },
    onAppStateChange: (s: BridgeAppState) => {
      setAppState(s as AppState);
    },
  });
  await bridge.start();
});
```

> **Important**: This is a sketch β€” the actual SDK URL needs to be hardcoded with the latest `v*` tag (per AGENTS.md), and many edge cases (mic mute, stop button, error paths, robot picker UI, OAuth callback timing) need to be ported faithfully from the reference app. The reference `main.ts` is ~2 kloc; the engineer should read it line by line, port the bones of it, and replace the simple instructions/tools wiring with the bridge as shown above.

- [ ] **Step 3: Resolve the latest Reachy Mini SDK tag and hardcode it**

```bash
git ls-remote --tags --refs --sort=-v:refname https://github.com/pollen-robotics/reachy_mini.git | head -1 | awk -F/ '{print $NF}'
```

Substitute the resulting tag in the import URL of `src/main.ts`:

```typescript
import { ReachyMini } from "https://cdn.jsdelivr.net/gh/pollen-robotics/reachy_mini@<TAG>/js/reachy-mini.js";
```

- [ ] **Step 4: Verify build + dev server starts**

```bash
npm run build
npm run dev
```

Open http://localhost:5173 β€” the orb UI should render and respond to settings clicks.

- [ ] **Step 5: Commit**

```bash
git add src/main.ts
git commit -m "feat(app): main.ts wiring β€” content load, settings, robot connect, story bridge"
```

---

## Phase 6 β€” Deployment

### Task 24: Dockerfile + nginx

**Files:**
- Create: `Dockerfile`
- Create: `nginx.conf`

- [ ] **Step 1: Write `Dockerfile`** β€” multistage build

```dockerfile
# ── Builder ─────────────────────────────────────────────────────────────
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json tsconfig.base.json tsconfig.app.json vite.config.ts ./
COPY packages ./packages
RUN npm ci
COPY index.html ./
COPY src ./src
COPY content ./content
RUN npm run build

# ── Runtime ─────────────────────────────────────────────────────────────
FROM nginx:alpine AS runtime
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 7860
CMD ["nginx", "-g", "daemon off;"]
```

- [ ] **Step 2: Write `nginx.conf`** β€” extends the reference app's

```nginx
server {
  listen 7860;
  server_name _;
  root /usr/share/nginx/html;

  # Static SPA β€” fall back to index.html for client-side routing
  location / {
    try_files $uri $uri/ /index.html;
  }

  # OpenAI Realtime WebRTC negotiation (browser β†’ /openai/v1/realtime β†’ api.openai.com)
  location /openai/v1/realtime {
    proxy_pass https://api.openai.com/v1/realtime;
    proxy_http_version 1.1;
    proxy_set_header Host api.openai.com;
    proxy_set_header Authorization $http_authorization;
    proxy_set_header Connection "";
    proxy_buffering off;
    proxy_request_buffering off;
    proxy_read_timeout 600;
    proxy_send_timeout 600;
  }

  # Summary LLM (chat completions)
  location /openai/v1/chat/completions {
    proxy_pass https://api.openai.com/v1/chat/completions;
    proxy_http_version 1.1;
    proxy_set_header Host api.openai.com;
    proxy_set_header Authorization $http_authorization;
    proxy_buffering off;
    proxy_read_timeout 60;
  }
}
```

- [ ] **Step 3: Local build test**

```bash
docker build -t reachy-tales-test .
docker run -p 7860:7860 reachy-tales-test
# Open http://localhost:7860 β€” should serve the orb UI.
# Ctrl-C to stop.
```

- [ ] **Step 4: Commit**

```bash
git add Dockerfile nginx.conf
git commit -m "feat(deploy): Dockerfile + nginx with OpenAI proxy routes"
```

---

### Task 25: HF Space frontmatter + README

**Files:**
- Modify: `README.md`

- [ ] **Step 1: Replace the minimal README with the HF Space-ready version**

```markdown
---
title: Reachy Tales
emoji: πŸ΄β€β˜ οΈ
colorFrom: indigo
colorTo: purple
sdk: docker
app_port: 7860
pinned: false
hf_oauth: true
hf_oauth_expiration_minutes: 480
short_description: Voice-driven story adventures, narrated by your Reachy Mini.
tags:
  - reachy_mini
  - reachy_mini_js_app
---

# Reachy Tales

Voice-driven story adventures for Reachy Mini. The robot becomes the narrator and characters; the user replies in natural language; story state is driven by a clean, testable engine.

## Quick start

1. Open the Space, sign in with Hugging Face.
2. Paste an OpenAI API key with Realtime API access into the settings panel.
3. Pick your robot.
4. Tap the orb. The narrator greets you and offers stories.

## Architecture

- **`packages/story-engine/`** β€” pure TypeScript library: data loading, scene graph, storyline DAG, flag rules, prompt builder. No DOM / robot / LLM dependencies. Independently testable.
- **`src/`** β€” JS HF Space app. Wires the engine into the OpenAI Realtime API (via WebRTC over the robot peer) and into the Reachy Mini JS SDK. Body motion (idle breathing, listening cues, speech-driven head sway, dance/emotion library) is ported from the [reference conversation app](https://huggingface.co/spaces/tfrere/reachy-mini-minimal-js-conversation-app).
- **`content/`** β€” story data (English).

See [design spec](docs/superpowers/specs/2026-04-29-reachy-tales-design.md).

## Local dev

```bash
npm install
npm test --workspace story-engine
npm run dev   # http://localhost:5173
```

Local dev requires:
- A Reachy Mini accessible (Lite via USB or Wireless on network)
- An OpenAI API key with Realtime + chat-completions access
- A registered HF OAuth app for `localhost:5173` (see settings panel for the client-id field)

## Deployment

Push to the HF Space remote β†’ auto-builds the Docker image and rolls out (~1-2 min). For dual-source-of-truth (GitHub + HF Space), see `.github/workflows/mirror-to-hf.yml`.
```

- [ ] **Step 2: Commit**

```bash
git add README.md
git commit -m "docs: HF Space frontmatter + project README"
```

---

### Task 26: GitHub β†’ HF Space mirror Action

**Files:**
- Create: `.github/workflows/mirror-to-hf.yml`

- [ ] **Step 1: Write the workflow**

```yaml
name: Mirror to Hugging Face Space

on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  mirror:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Push to Hugging Face Space
        env:
          HF_TOKEN: ${{ secrets.HF_TOKEN }}
          HF_USERNAME: ${{ secrets.HF_USERNAME }}
          HF_SPACE: reachy-tales
        run: |
          git config user.email "github-actions@users.noreply.github.com"
          git config user.name "GitHub Actions"
          git remote add hf "https://${HF_USERNAME}:${HF_TOKEN}@huggingface.co/spaces/${HF_USERNAME}/${HF_SPACE}"
          git push hf main --force
```

- [ ] **Step 2: Document required secrets in the workflow file** (already added inline as env)

In the GitHub repo settings β†’ Secrets, add:
- `HF_TOKEN` β€” a write-scoped HF access token (https://huggingface.co/settings/tokens)
- `HF_USERNAME` β€” your HF username

- [ ] **Step 3: Create the Space remote on Hugging Face manually**

```bash
# One-time, on your laptop:
hf auth login   # if not authenticated
hf repos create reachy-tales --repo-type space --space-sdk docker
```

This creates the empty Space β€” the GitHub Action's force-push then populates it.

- [ ] **Step 4: Commit**

```bash
git add .github/workflows/mirror-to-hf.yml
git commit -m "ci: GitHub→HF Space mirror workflow"
```

---

### Task 27: CI for tests + build

**Files:**
- Create: `.github/workflows/ci.yml`

- [ ] **Step 1: Write the CI workflow**

```yaml
name: CI

on:
  pull_request:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm test --workspace story-engine
      - run: npm run test:app
      - run: npm run build
```

- [ ] **Step 2: Commit**

```bash
git add .github/workflows/ci.yml
git commit -m "ci: tests + build on PR and main"
```

---

### Task 28: Manual playtest checklist

**Files:**
- Create: `docs/playtest.md`

- [ ] **Step 1: Write the checklist (lifted verbatim from spec Β§7.3)**

```markdown
# v1 Playtest Checklist

Walk through this before declaring v1 done. Each tick assumes physical robot + OpenAI key in settings.

## Boot & menu
- [ ] HF Space loads in under 5s
- [ ] OAuth login completes
- [ ] Robot picker shows my robot
- [ ] Tap orb β†’ narrator greets me, lists pirate story
- [ ] "Tell me about the pirate story" β†’ narrator describes it
- [ ] "Let's play it" β†’ triggers `select_story` β†’ swap to Sparrow's voice

## Voice swap
- [ ] Voice swap takes < 3s with brief "Changing voice…" caption
- [ ] New character (Sparrow) opens with paraphrased meet_sparrow line
- [ ] After swap, Sparrow voice clearly different from narrator voice

## Gameplay
- [ ] "I show him respect" advances to friendly_response
- [ ] "Screw you" advances to hostile_response
- [ ] "What can I do?" β†’ narrator/character recites options
- [ ] "I'm bored, exit" β†’ returns to menu, narrator's voice resumes

## Scene navigation
- [ ] Trying to go to docks before trust_sparrow β†’ character explains it's blocked
- [ ] After trust_sparrow set β†’ "Let's go to the docks" navigates

## Scene actions
- [ ] "I look at the memorabilia" β†’ atmospheric description spoken
- [ ] Atmospheric actions don't change story state (next utterance still at same node)

## Body motion
- [ ] Robot breathes when idle
- [ ] Antennas freeze when I speak, blend back when I stop
- [ ] Head wobbles in sync with speech
- [ ] LLM occasionally calls `play_move` for emotional beats

## Robustness
- [ ] WiFi blip < 5s recovers without losing session
- [ ] Pause for 30s β†’ app stays in listening state, no crash
- [ ] Refresh page mid-session β†’ restarts at menu (v1 = no persist)
```

- [ ] **Step 2: Commit**

```bash
git add docs/playtest.md
git commit -m "docs: manual playtest checklist for v1"
```

---

## Self-review note (informational)

After completing all tasks above, run a final review:

1. **`npm run test:all`** β€” every test green.
2. **`npm run build`** β€” Vite build succeeds with no errors.
3. **`docker build -t reachy-tales .`** β€” image builds.
4. **`docker run -p 7860:7860 reachy-tales`** β€” app loads at http://localhost:7860.
5. **Push to GitHub** β†’ CI passes β†’ Action mirrors to HF Space β†’ Space comes online.
6. **Walk the playtest checklist** with a real Reachy Mini.

---

## Phase summary

| Phase | Tasks | What's working at the end |
|---|---|---|
| 1 β€” Bootstrap | 1-2 | npm workspaces resolve; vitest runs (no tests). |
| 2 β€” Engine | 3-14 | All engine features implemented + tested with fixtures. |
| 3 β€” Content | 15-16 | English content present; engine playthrough test passes against real content. |
| 4 β€” App scaffold | 17-22 | Vite app boots, plumbing copied, bridge exists with unit tests. |
| 5 β€” Orchestration | 23 | Full app wires together β€” settings, OAuth, robot, bridge, story flow. |
| 6 β€” Deployment | 24-28 | Docker image, nginx proxy, HF frontmatter, GitHub mirror, CI, playtest doc. |