tina4 3.8.20

Tina4 — Unified CLI for Python, PHP, Ruby, and Node.js frameworks
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
//! Tina4 Agent — LLM-powered coding assistant with multi-agent orchestration.
//!
//! Reads agent configs from `.tina4/agents/*/config.json` + `system.md`.
//! Serves an HTTP+SSE endpoint for the dev admin frontend.
//! Handles supervisor routing, plan creation, code generation, and tool execution.

use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

use crate::console::{icon_info, icon_ok, icon_play, icon_warn};

// ── Agent config structures ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    pub model: String,          // "thinking", "vision", "image-gen" — maps to user settings
    pub temperature: f32,
    pub max_tokens: u32,
    pub tools: Vec<String>,
    pub max_iterations: u32,
}

#[derive(Debug, Clone)]
pub struct Agent {
    pub name: String,
    pub config: AgentConfig,
    pub system_prompt: String,
}

// ── Model settings (from dev admin) ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelSettings {
    pub provider: String,
    pub model: String,
    pub url: String,
    #[serde(alias = "apiKey", default)]
    pub api_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatSettings {
    pub thinking: ModelSettings,
    pub vision: ModelSettings,
    #[serde(rename = "imageGen")]
    pub image_gen: ModelSettings,
}

// ── Chat messages ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
    pub id: String,
    pub role: String,           // "user", "assistant", "system"
    pub content: String,
    pub timestamp: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thread_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent: Option<String>,  // which agent generated this
}

// ── Escalation tracking ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Escalation {
    pub id: String,
    pub category: String,       // "uncommitted", "untested", "security", "convention"
    pub level: u8,              // 0=silent, 1=gentle, 2=concerned, 3=action
    pub message: String,
    pub first_seen: String,
    pub last_prompted: String,
    pub dismissed: bool,
    pub acted_on: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Thought {
    pub id: String,
    pub timestamp: String,
    pub message: String,
    pub category: String,
    pub actions: Vec<ThoughtAction>,
    pub dismissed: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThoughtAction {
    pub label: String,
    pub action: String,         // "create_branch", "scaffold_tests", "show_fix", etc.
}

// ── Supervisor action (parsed from LLM JSON response) ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SupervisorAction {
    pub action: String,         // "plan", "code", "respond", "analyze_image", "generate_image", "debug"
    #[serde(default)]
    pub delegate_to: Option<String>,
    #[serde(default)]
    pub context: Option<String>,
    #[serde(default)]
    pub message: Option<String>,
    #[serde(default)]
    pub files: Option<Vec<String>>,
    #[serde(default)]
    pub prompt: Option<String>,
    #[serde(default)]
    pub error: Option<String>,
}

// ── LLM API types (OpenAI-compatible) ──

#[derive(Debug, Serialize)]
struct LlmRequest {
    model: String,
    messages: Vec<LlmMessage>,
    max_tokens: u32,
    temperature: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    options: Option<LlmOptions>,
}

#[derive(Debug, Serialize)]
struct LlmOptions {
    num_ctx: u32,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct LlmMessage {
    role: String,
    content: String,
}

#[derive(Debug, Deserialize)]
struct LlmResponse {
    choices: Vec<LlmChoice>,
}

#[derive(Debug, Deserialize)]
struct LlmChoice {
    message: LlmMessage,
}

// ── Default agent configs ──

const DEFAULT_AGENTS: &[(&str, &str, &str)] = &[
    ("supervisor", r#"{"model":"thinking","temperature":0.3,"max_tokens":2048,"tools":["list_routes","list_tables","project_info","file_list"],"max_iterations":1}"#,
     r#"You are Tina4, the AI coding assistant built into the Tina4 dev admin.

You are the supervisor. The developer chats with you directly. You understand their request, gather requirements, coordinate specialist agents, and steer the project from start to finish.

## Your Personality
You are direct, practical, and efficient. You ask only what matters. You never explain framework internals or list modules. You talk like a colleague who just gets things done.

## Communication Style
- Ask SHORT questions about what the USER needs, not technology choices
- Never list framework features or module names
- Focus on WHAT the user wants, not HOW you'll build it
- When executing a plan, give clear progress updates: "Step 2 of 5 done. Moving to the login page..."
- After completing work, summarize what was built in plain English

## CRITICAL: Gather Requirements First

When a developer says they want to build something, DO NOT immediately create a plan. Instead:
1. Ask clarifying questions to understand what they need
2. Keep asking until you have enough detail OR the developer says "just build it", "go ahead", "you decide"

## When to Stop Asking

Stop asking and act when:
- The developer says "go ahead", "build it", "just do it", "you decide"
- You have enough detail after 2-3 rounds of questions
- The request is simple enough (e.g. "add a health check endpoint")

## Steering the Project

You keep the big picture in mind:
- Remember what has been built so far in this conversation
- When executing a plan, work through it step by step — one task at a time
- After each task, briefly confirm what was done and what's next
- If something fails, handle it before moving on
- At the end of the plan, give a summary of everything that was built

## Rules
1. Gather requirements before planning
2. Always plan before coding — create plans in .tina4/plans/
3. Never reinvent what the framework provides
4. Keep questions concise — max 3-4 per round
5. If the developer provides a detailed spec upfront, skip questions and plan directly
6. NEVER show file paths, code, or technical jargon to the user

## Actions
Only respond with JSON when ready to delegate:
{"action": "plan", "delegate_to": "planner", "context": "detailed description with all gathered requirements"}
{"action": "code", "delegate_to": "coder", "context": "what to write", "files": ["path1", "path2"]}
{"action": "execute_plan", "delegate_to": "coder", "context": "plan file path to execute step by step"}
{"action": "analyze_image", "delegate_to": "vision"}
{"action": "generate_image", "delegate_to": "image-gen", "prompt": "what to generate"}
{"action": "debug", "delegate_to": "debug", "error": "the error message"}
{"action": "respond", "message": "your conversational response or questions"}

For questions and conversation, ALWAYS use:
{"action": "respond", "message": "your message here"}
"#),

    ("planner", r#"{"model":"thinking","temperature":0.2,"max_tokens":4096,"tools":["file_read","file_list","list_routes","list_tables"],"max_iterations":3}"#,
     r#"You are the Planner agent. You create simple plans that a non-technical person can understand.

## How to write a plan

Write a short numbered list of what will be built. Use plain English. No technical jargon.

Example:
1. Set up the database for storing contacts
2. Create a page where visitors fill in their name, email, and message
3. Save the submission to the database
4. Send an email notification to the site owner
5. Show a thank you message after submission

## RULES — follow these exactly

- NEVER mention file paths, file names, or directories
- NEVER mention code, classes, functions, methods, or APIs
- NEVER use tables or technical formatting
- NEVER say "Create migration", "Create ORM model", "Create route" — say what it DOES, not what it IS
- NEVER mention the framework by name
- NEVER say "ORM", "AutoCrud", "middleware", "endpoint", "schema", "migration"
- Write like you're explaining to someone who doesn't code
- Maximum 10 steps
- Each step is ONE simple sentence
- Start with an objective sentence before the numbered list
"#),

    ("coder", r#"{"model":"thinking","temperature":0.1,"max_tokens":4096,"tools":["file_read","file_write"],"max_iterations":10}"#,
     r#"You are the Coder agent for Tina4 projects. Write code that follows the plan exactly.

## CRITICAL: File Structure

All Tina4 projects use this structure — NEVER use Laravel, Django, Rails, or Express patterns:

```
project/
  app.py
  migrations/        ← SQL migration files (at project ROOT)
  src/
    routes/          ← route files (one per file)
    orm/             ← ORM model files (one per file)
    templates/       ← Frond HTML templates (.twig)
    seeds/           ← database seed files
```

NEVER create: app/, Controllers/, Models/, Views/, Database/, database/ folders.

## Python Route Example (src/routes/contact.py)

```python
from tina4_python import get, post
from tina4_python.core import response

@get("/contact")
async def get_contact(request, response):
    return response.html(template("contact.twig"))

@post("/contact")
async def post_contact(request, response):
    name = request.body.get("name", "")
    email = request.body.get("email", "")
    message = request.body.get("message", "")
    # save to database, send email, etc.
    return response.redirect("/contact?success=1")
```

## Python ORM Example (src/orm/Contact.py)

```python
from tina4_python.orm import fields, model

class Contact(model.Model):
    __table_name__ = "contacts"
    id = fields.AutoField(primary_key=True)
    name = fields.CharField(max_length=255)
    email = fields.CharField(max_length=255)
    message = fields.TextField()
    created_at = fields.DateTimeField(auto_now_add=True)
```

## Migration Example (migrations/001_create_contacts.sql)  ← at project ROOT

```sql
CREATE TABLE IF NOT EXISTS contacts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name VARCHAR(255),
    email VARCHAR(255),
    message TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
```

## Template Example (src/templates/contact.twig)

```html
<form method="post" action="/contact">
    <input name="name" placeholder="Name" required>
    <input name="email" type="email" placeholder="Email" required>
    <textarea name="message" placeholder="Message" required></textarea>
    <button type="submit">Send</button>
</form>
```

## Rules
- ALWAYS use the src/ structure shown above
- NEVER create app/, Controllers/, Models/, Views/, Database/ folders
- One route per file, one model per file
- Return each file as: ## FILE: path/to/file
"#),

    ("vision", r#"{"model":"vision","temperature":0.3,"max_tokens":2048,"tools":[],"max_iterations":1}"#,
     r#"You are the Vision agent for Tina4 projects.

Your job: analyze images (screenshots, mockups, diagrams) and describe what you see in detail.

Describe:
- UI elements (buttons, forms, tables, navigation)
- Layout and structure
- Colors and styling
- Text content
- Suggested Tina4 implementation approach
"#),

    ("image-gen", r#"{"model":"image-gen","temperature":0.7,"max_tokens":256,"tools":[],"max_iterations":1}"#,
     r#"Generate images based on user descriptions."#),

    ("debug", r#"{"model":"thinking","temperature":0.2,"max_tokens":4096,"tools":["file_read","database_query"],"max_iterations":5}"#,
     r#"You are the Debug agent for Tina4 projects.

Your job: analyze errors, read the relevant source files, and suggest fixes.

## Process
1. Parse the error type and traceback
2. Read the file where the error occurred
3. Identify the root cause
4. Suggest a specific fix with code
5. If the fix requires file changes, describe them precisely
"#),
];

// ── Public API ──

/// Scaffold default agent configs into `.tina4/agents/`.
pub fn scaffold_agents(project_dir: &Path) {
    let agents_dir = project_dir.join(".tina4").join("agents");

    for (name, config_json, system_prompt) in DEFAULT_AGENTS {
        let agent_dir = agents_dir.join(name);
        let config_path = agent_dir.join("config.json");
        let prompt_path = agent_dir.join("system.md");

        if config_path.exists() && prompt_path.exists() {
            continue; // Don't overwrite existing configs
        }

        if let Err(e) = fs::create_dir_all(&agent_dir) {
            eprintln!("  {} Failed to create {}: {}", icon_warn(), agent_dir.display(), e);
            continue;
        }

        if !config_path.exists() {
            if let Err(e) = fs::write(&config_path, config_json) {
                eprintln!("  {} Failed to write {}: {}", icon_warn(), config_path.display(), e);
            }
        }

        if !prompt_path.exists() {
            if let Err(e) = fs::write(&prompt_path, system_prompt) {
                eprintln!("  {} Failed to write {}: {}", icon_warn(), prompt_path.display(), e);
            }
        }
    }

    // Create plans and chat directories
    let _ = fs::create_dir_all(project_dir.join(".tina4").join("plans"));
    let _ = fs::create_dir_all(project_dir.join(".tina4").join("chat").join("threads"));

    println!("  {} Agent configs scaffolded in .tina4/agents/", icon_ok());
}

/// Load all agents from `.tina4/agents/`.
pub fn load_agents(project_dir: &Path) -> Vec<Agent> {
    let agents_dir = project_dir.join(".tina4").join("agents");
    let mut agents = Vec::new();

    if !agents_dir.exists() {
        return agents;
    }

    if let Ok(entries) = fs::read_dir(&agents_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() { continue; }

            let name = path.file_name().unwrap_or_default().to_string_lossy().to_string();
            let config_path = path.join("config.json");
            let prompt_path = path.join("system.md");

            let config: AgentConfig = match fs::read_to_string(&config_path) {
                Ok(s) => match serde_json::from_str(&s) {
                    Ok(c) => c,
                    Err(e) => {
                        eprintln!("  {} Bad config for agent '{}': {}", icon_warn(), name, e);
                        continue;
                    }
                },
                Err(_) => continue,
            };

            let system_prompt = fs::read_to_string(&prompt_path).unwrap_or_default();

            agents.push(Agent { name, config, system_prompt });
        }
    }

    agents
}

/// Load chat settings from `.tina4/chat/settings.json` or use defaults.
pub fn load_chat_settings(project_dir: &Path) -> ChatSettings {
    let path = project_dir.join(".tina4").join("chat").join("settings.json");
    if let Ok(s) = fs::read_to_string(&path) {
        if let Ok(settings) = serde_json::from_str(&s) {
            return settings;
        }
    }
    // Defaults — Tina4 Cloud (per-model-type endpoints, models fetched at runtime)
    ChatSettings {
        thinking: ModelSettings {
            provider: "tina4".into(),
            model: String::new(),
            url: "http://41.71.84.173:11437".into(),
            api_key: String::new(),
        },
        vision: ModelSettings {
            provider: "tina4".into(),
            model: String::new(),
            url: "http://41.71.84.173:11434".into(),
            api_key: String::new(),
        },
        image_gen: ModelSettings {
            provider: "tina4".into(),
            model: String::new(),
            url: "http://41.71.84.173:11436".into(),
            api_key: String::new(),
        },
    }
}

/// Save chat message to `.tina4/chat/history.json`.
pub fn save_message(project_dir: &Path, message: &ChatMessage) {
    let history_path = project_dir.join(".tina4").join("chat").join("history.json");
    let mut messages: Vec<ChatMessage> = if let Ok(s) = fs::read_to_string(&history_path) {
        serde_json::from_str(&s).unwrap_or_default()
    } else {
        Vec::new()
    };
    messages.push(message.clone());
    let _ = fs::write(&history_path, serde_json::to_string_pretty(&messages).unwrap_or_default());
}

/// Load chat history from `.tina4/chat/history.json`.
pub fn load_history(project_dir: &Path) -> Vec<ChatMessage> {
    let path = project_dir.join(".tina4").join("chat").join("history.json");
    if let Ok(s) = fs::read_to_string(&path) {
        serde_json::from_str(&s).unwrap_or_default()
    } else {
        Vec::new()
    }
}

/// Fetch the first available model from an Ollama-compatible server.
async fn fetch_first_model(base_url: &str) -> Option<String> {
    let client = reqwest::Client::new();
    // Try Ollama /api/tags first
    if let Ok(resp) = client.get(format!("{}/api/tags", base_url)).send().await {
        if let Ok(text) = resp.text().await {
            if let Ok(data) = serde_json::from_str::<serde_json::Value>(&text) {
                if let Some(models) = data["models"].as_array() {
                    if let Some(first) = models.first() {
                        let name = first["name"].as_str()
                            .or_else(|| first["model"].as_str())
                            .unwrap_or("");
                        if !name.is_empty() {
                            return Some(name.to_string());
                        }
                    }
                }
            }
        }
    }
    // Try OpenAI /v1/models
    if let Ok(resp) = client.get(format!("{}/v1/models", base_url)).send().await {
        if let Ok(text) = resp.text().await {
            if let Ok(data) = serde_json::from_str::<serde_json::Value>(&text) {
                if let Some(models) = data["data"].as_array() {
                    if let Some(first) = models.first() {
                        if let Some(id) = first["id"].as_str() {
                            return Some(id.to_string());
                        }
                    }
                }
            }
        }
    }
    None
}

/// Make an LLM call (blocking, non-streaming).
pub async fn llm_call(
    settings: &ModelSettings,
    system_prompt: &str,
    messages: &[LlmMessage],
    max_tokens: u32,
    temperature: f32,
) -> Result<String, String> {
    let client = reqwest::Client::new();

    // If model is empty, auto-detect from the server
    let model_name = if settings.model.is_empty() {
        let base = settings.url.trim_end_matches('/');
        match fetch_first_model(base).await {
            Some(m) => m,
            None => return Err("No models available on the server. Check the URL.".into()),
        }
    } else {
        settings.model.clone()
    };

    let mut all_messages = Vec::new();
    if !system_prompt.is_empty() {
        all_messages.push(LlmMessage {
            role: "system".into(),
            content: system_prompt.into(),
        });
    }
    all_messages.extend_from_slice(messages);

    // For Ollama/custom providers, request larger context window
    let options = if settings.provider == "custom" || settings.provider == "tina4" {
        Some(LlmOptions { num_ctx: 32768 })
    } else {
        None
    };

    let body = LlmRequest {
        model: model_name,
        messages: all_messages,
        max_tokens,
        temperature,
        stream: None,
        options,
    };

    // Build full API URL from base URL + provider-specific path
    let base_url = settings.url.trim_end_matches('/');
    let api_url = match settings.provider.as_str() {
        "anthropic" => format!("{}/v1/messages", base_url),
        "openai" => format!("{}/v1/chat/completions", base_url),
        "tina4" => format!("{}/v1/chat/completions", base_url),
        _ => {
            // Custom — auto-detect: if URL already has /v1/ path, use as-is, otherwise append
            if base_url.contains("/v1/") || base_url.contains("/api/") {
                base_url.to_string()
            } else {
                format!("{}/v1/chat/completions", base_url)
            }
        }
    };

    let mut req = client.post(&api_url)
        .header("Content-Type", "application/json")
        .json(&body);

    // Add auth header based on provider
    if !settings.api_key.is_empty() {
        if settings.provider == "anthropic" {
            req = req.header("x-api-key", &settings.api_key)
                     .header("anthropic-version", "2023-06-01");
        } else {
            req = req.header("Authorization", format!("Bearer {}", settings.api_key));
        }
    }

    let resp = req.send().await.map_err(|e| format!("Request failed: {}", e))?;
    let status = resp.status();
    let text = resp.text().await.map_err(|e| format!("Read failed: {}", e))?;

    if !status.is_success() {
        return Err(format!("LLM API error {}: {}", status, &text[..text.len().min(200)]));
    }

    // Parse OpenAI-compatible response
    let parsed: LlmResponse = serde_json::from_str(&text)
        .map_err(|e| format!("Parse failed: {} — body: {}", e, &text[..text.len().min(200)]))?;

    parsed.choices.first()
        .map(|c| c.message.content.clone())
        .ok_or_else(|| "No response content".into())
}

/// Parse supervisor LLM response into a structured action.
pub fn parse_supervisor_action(response: &str) -> Option<SupervisorAction> {
    // Try to extract JSON from the response (might be wrapped in markdown or text)
    let trimmed = response.trim();

    // Direct JSON
    if trimmed.starts_with('{') {
        return serde_json::from_str(trimmed).ok();
    }

    // JSON in code block
    if let Some(start) = trimmed.find("```json") {
        let json_start = start + 7;
        if let Some(end) = trimmed[json_start..].find("```") {
            let json_str = trimmed[json_start..json_start + end].trim();
            return serde_json::from_str(json_str).ok();
        }
    }

    // JSON anywhere in text
    if let Some(start) = trimmed.find('{') {
        if let Some(end) = trimmed.rfind('}') {
            let json_str = &trimmed[start..=end];
            return serde_json::from_str(json_str).ok();
        }
    }

    // Not a structured action — treat as direct response
    Some(SupervisorAction {
        action: "respond".into(),
        message: Some(response.to_string()),
        delegate_to: None,
        context: None,
        files: None,
        prompt: None,
        error: None,
    })
}

/// Load escalations from `.tina4/chat/escalations.json`.
pub fn load_escalations(project_dir: &Path) -> Vec<Escalation> {
    let path = project_dir.join(".tina4").join("chat").join("escalations.json");
    if let Ok(s) = fs::read_to_string(&path) {
        serde_json::from_str(&s).unwrap_or_default()
    } else {
        Vec::new()
    }
}

/// Save escalations to `.tina4/chat/escalations.json`.
pub fn save_escalations(project_dir: &Path, escalations: &[Escalation]) {
    let path = project_dir.join(".tina4").join("chat").join("escalations.json");
    let _ = fs::write(&path, serde_json::to_string_pretty(escalations).unwrap_or_default());
}

/// Load thoughts from `.tina4/chat/thoughts.json`.
pub fn load_thoughts(project_dir: &Path) -> Vec<Thought> {
    let path = project_dir.join(".tina4").join("chat").join("thoughts.json");
    if let Ok(s) = fs::read_to_string(&path) {
        serde_json::from_str(&s).unwrap_or_default()
    } else {
        Vec::new()
    }
}

/// Save a new thought.
pub fn save_thought(project_dir: &Path, thought: &Thought) {
    let path = project_dir.join(".tina4").join("chat").join("thoughts.json");
    let mut thoughts = load_thoughts(project_dir);
    thoughts.push(thought.clone());
    // Keep last 50 thoughts
    if thoughts.len() > 50 {
        thoughts = thoughts[thoughts.len() - 50..].to_vec();
    }
    let _ = fs::write(&path, serde_json::to_string_pretty(&thoughts).unwrap_or_default());
}

/// Short Tina4 framework cheat-sheet baked into the binary as a fallback.
/// Used when we can't find the full framework docs on disk. Keep it
/// dense — this is what gets prepended to every coder message.
const TINA4_FALLBACK_CONTEXT: &str = r#"# Tina4 framework cheat-sheet

You are working in a Tina4 project. Conventions:
- Routes: `from tina4_python.core.router import get, post, noauth, secured`. `@noauth` / `@secured` / `@description` go ABOVE `@get`/`@post`. Example: `@noauth()` then `@post("/api/x")` on the innermost decorator.
- Always `response({...})`. NEVER `response.json(...)`.
- Path params: `{id:int}`, `{price:float}`, `{rest:path}`.
- DB: `from tina4_python.database import Database`. `Database("sqlite:///app.db", ...)`. `db.fetch(sql,[...])` returns `DatabaseResult`; iterate `.records` (list of dicts). `fetch_one` returns dict-or-None. Dict access only: `row["name"]`, never `row.name`. Transactions: `db.start_transaction/commit/rollback` — NEVER `db.execute("COMMIT")`.
- ORM: one class per file in `src/orm/`. `IntegerField(primary_key=True, auto_increment=True)`, `StringField()`. `User.find(1)`, `User.where("age>?",[18])`, `user.save()`.
- Migrations: REQUIRED for schema. `tina4 generate migration "create x"` then `tina4 migrate`. Never raw DDL outside migrations. SQLite uses `INTEGER PRIMARY KEY AUTOINCREMENT`; PostgreSQL `SERIAL`; MySQL `AUTO_INCREMENT`.
- Templates (Frond/Jinja2): `{% extends "base.twig" %}`. `{% elif %}` not `{% elseif %}`. `{{ x|raw }}` for unescaped. `{{ "a " ~ b }}` for string concat (NOT `+`). Always include `{{ form_token() }}` in forms and `placeholder` on every input.
- .env: `DATABASE_URL=sqlite:///app.db`, `TINA4_DEBUG=true`, `SECRET=...`, `TINA4_TOKEN_LIMIT=60`.
- Built-ins — never reinvent: `Queue(topic="x").push({...})` for background work, `Api(base_url, auth_header)` for HTTP, `Auth.hash_password/check_password` for passwords, `get_token/valid_token` for JWT, `@cached(True, max_age=120)` for response caching, `background(fn, interval)` for periodic tasks.
- Project layout: `src/routes/*.py` (auto-discovered), `src/orm/*.py` (models), `src/app/` (helpers), `src/templates/` (Twig), `src/scss/` (auto-compiled), `migrations/NNNNNN_description.sql`.
"#;

/// Try to locate the installed framework's CLAUDE.md so the coder
/// gets version-matched context. Falls back to the embedded
/// cheat-sheet above when we can't find anything. Always returns a
/// ready-to-prepend string (with trailing blank line) or empty when
/// we genuinely can't help.
pub fn load_framework_context(project_dir: &Path) -> String {
    // Candidate locations, in preference order. First hit wins.
    // The venv path depends on Python minor version — glob it.
    let mut candidates: Vec<std::path::PathBuf> = Vec::new();

    // Python projects: look in the active venv's site-packages
    for venv in &[".venv", "venv"] {
        let lib = project_dir.join(venv).join("lib");
        if let Ok(entries) = fs::read_dir(&lib) {
            for e in entries.flatten() {
                let site = e.path().join("site-packages/tina4_python");
                candidates.push(site.join("CLAUDE.md"));
            }
        }
    }
    // PHP: vendor path
    candidates.push(project_dir.join("vendor/tina4stack/tina4php/CLAUDE.md"));
    // Ruby: bundle path — approximate
    candidates.push(project_dir.join("vendor/bundle/ruby").join("tina4/CLAUDE.md"));
    // Node.js
    candidates.push(project_dir.join("node_modules/tina4-nodejs/CLAUDE.md"));
    // Project-local override (user can drop their own)
    candidates.push(project_dir.join(".tina4/framework-context.md"));

    for p in candidates {
        if p.is_file() {
            if let Ok(text) = fs::read_to_string(&p) {
                if text.len() > 100 {
                    return format!("## Framework Reference\nSource: {}\n\n{}\n\n", p.display(), text);
                }
            }
        }
    }
    // Fallback — embedded short reference.
    format!("## Framework Reference (embedded fallback)\n\n{}\n\n", TINA4_FALLBACK_CONTEXT)
}

/// Scan project and build context string for the coder agent.
pub fn build_project_context(project_dir: &Path) -> String {
    let mut ctx = String::new();

    // Detect language
    let lang = if project_dir.join("app.py").exists() { "python" }
        else if project_dir.join("index.php").exists() || project_dir.join("composer.json").exists() { "php" }
        else if project_dir.join("app.rb").exists() || project_dir.join("Gemfile").exists() { "ruby" }
        else if project_dir.join("app.ts").exists() || project_dir.join("package.json").exists() { "nodejs" }
        else { "python" };
    ctx.push_str(&format!("Language: {}\n", lang));
    ctx.push_str(&format!("Project root: {}\n\n", project_dir.display()));

    // List existing route files with their first few lines
    let routes_dir = project_dir.join("src").join("routes");
    if routes_dir.exists() {
        ctx.push_str("## Existing route files:\n");
        if let Ok(entries) = fs::read_dir(&routes_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    let name = path.file_name().unwrap_or_default().to_string_lossy().to_string();
                    ctx.push_str(&format!("- src/routes/{}", name));
                    // Read first 5 lines to show the pattern
                    if let Ok(content) = fs::read_to_string(&path) {
                        let preview: String = content.lines().take(5).collect::<Vec<_>>().join("\n");
                        ctx.push_str(&format!("\n```\n{}\n```\n", preview));
                    } else {
                        ctx.push('\n');
                    }
                }
            }
        }
        ctx.push('\n');
    }

    // List existing ORM models
    let orm_dir = project_dir.join("src").join("orm");
    if orm_dir.exists() {
        ctx.push_str("## Existing ORM models:\n");
        if let Ok(entries) = fs::read_dir(&orm_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    let name = path.file_name().unwrap_or_default().to_string_lossy().to_string();
                    ctx.push_str(&format!("- src/orm/{}", name));
                    if let Ok(content) = fs::read_to_string(&path) {
                        let preview: String = content.lines().take(10).collect::<Vec<_>>().join("\n");
                        ctx.push_str(&format!("\n```\n{}\n```\n", preview));
                    } else {
                        ctx.push('\n');
                    }
                }
            }
        }
        ctx.push('\n');
    }

    // List existing templates
    let tmpl_dir = project_dir.join("src").join("templates");
    if tmpl_dir.exists() {
        ctx.push_str("## Existing templates:\n");
        if let Ok(entries) = fs::read_dir(&tmpl_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() {
                    let name = path.file_name().unwrap_or_default().to_string_lossy().to_string();
                    ctx.push_str(&format!("- src/templates/{}\n", name));
                }
            }
        }
        ctx.push('\n');
    }

    // List existing migrations
    let mig_dir = project_dir.join("migrations");
    if mig_dir.exists() {
        ctx.push_str("## Existing migrations (at project root):\n");
        if let Ok(entries) = fs::read_dir(&mig_dir) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();
                ctx.push_str(&format!("- migrations/{}\n", name));
            }
        }
        ctx.push('\n');
    }

    // Read app.py to understand the entry point
    let app_file = match lang {
        "python" => "app.py",
        "php" => "index.php",
        "ruby" => "app.rb",
        _ => "app.ts",
    };
    if let Ok(content) = fs::read_to_string(project_dir.join(app_file)) {
        ctx.push_str(&format!("## {} (entry point):\n```\n{}\n```\n\n", app_file, content));
    }

    // .env for database config awareness
    if let Ok(content) = fs::read_to_string(project_dir.join(".env")) {
        // Only include non-secret lines (keys, not values)
        let safe: String = content.lines()
            .map(|line| {
                if let Some(pos) = line.find('=') {
                    format!("{}=***", &line[..pos])
                } else {
                    line.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("\n");
        ctx.push_str(&format!("## .env keys:\n{}\n\n", safe));
    }

    ctx
}

/// Scan project for issues (called by background thinking loop).
pub fn scan_project(project_dir: &Path) -> Vec<(String, String, String)> {
    // Returns: [(category, id, description)]
    let mut issues = Vec::new();

    // Check for uncommitted changes
    if let Ok(output) = std::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(project_dir)
        .output()
    {
        let status = String::from_utf8_lossy(&output.stdout);
        let changed_files: Vec<&str> = status.lines().collect();
        if changed_files.len() > 3 {
            issues.push((
                "uncommitted".into(),
                "uncommitted_files".into(),
                format!("{} uncommitted files in the project", changed_files.len()),
            ));
        }
    }

    // Check for routes without tests
    let routes_dir = project_dir.join("src").join("routes");
    let tests_dir_a = project_dir.join("tests");
    let tests_dir_b = project_dir.join("spec");
    if routes_dir.exists() {
        let route_count = fs::read_dir(&routes_dir)
            .map(|entries| entries.filter_map(|e| e.ok())
                .filter(|e| e.path().extension().map_or(false, |ext| ext == "py" || ext == "php" || ext == "rb" || ext == "ts"))
                .count())
            .unwrap_or(0);

        let test_count = [&tests_dir_a, &tests_dir_b].iter()
            .filter_map(|d| fs::read_dir(d).ok())
            .flat_map(|entries| entries.filter_map(|e| e.ok()))
            .filter(|e| {
                let name = e.file_name().to_string_lossy().to_string();
                name.starts_with("test_") || name.ends_with("_test.") || name.ends_with("_spec.")
            })
            .count();

        if route_count > 0 && test_count == 0 {
            issues.push((
                "untested".into(),
                "no_tests".into(),
                format!("{} routes with no test files at all", route_count),
            ));
        } else if route_count > test_count + 2 {
            issues.push((
                "untested".into(),
                "low_coverage".into(),
                format!("{} routes but only {} test files", route_count, test_count),
            ));
        }
    }

    // Check for missing .env.example
    if project_dir.join(".env").exists() && !project_dir.join(".env.example").exists() {
        issues.push((
            "convention".into(),
            "no_env_example".into(),
            "Project has .env but no .env.example — other developers won't know what vars are needed".into(),
        ));
    }

    issues
}

/// Re-verify an escalation's underlying claim against the filesystem
/// right before emitting it as a thought. This catches:
///   1. Stale escalations: the file got added after the issue was
///      first logged and before the engine's next full scan.
///   2. Race conditions: scan ran, user fixed it, loop still about to
///      emit the stale escalation.
///   3. Future hallucination-resistant claim types as they're added.
///
/// Returning `false` means "claim no longer applies, skip this thought."
/// Unknown ids return `true` so we don't accidentally silence new
/// escalation categories that haven't been wired through here yet.
fn verify_escalation_claim(project_dir: &Path, id: &str) -> bool {
    match id {
        // "Project has .env but no .env.example" — true iff .env exists
        // *and* .env.example doesn't. If either of those isn't the
        // case, drop the thought.
        "no_env_example" => {
            project_dir.join(".env").exists() && !project_dir.join(".env.example").exists()
        }
        // "Routes but no tests" — true iff at least one route file
        // exists *and* tests directory has no test files. Re-scan
        // rather than trust the cached escalation message.
        "no_tests" | "low_coverage" => {
            let routes = project_dir.join("src").join("routes");
            if !routes.exists() { return false; }
            let route_count = fs::read_dir(&routes)
                .map(|it| it.filter_map(|e| e.ok())
                    .filter(|e| e.path().extension().map_or(false, |ext|
                        ext == "py" || ext == "php" || ext == "rb" || ext == "ts"))
                    .count())
                .unwrap_or(0);
            if route_count == 0 { return false; }
            let tests = [project_dir.join("tests"), project_dir.join("spec")];
            let test_count: usize = tests.iter()
                .filter_map(|d| fs::read_dir(d).ok())
                .flat_map(|it| it.filter_map(|e| e.ok()))
                .filter(|e| {
                    let n = e.file_name().to_string_lossy().to_string();
                    n.starts_with("test_") || n.ends_with("_test.py")
                        || n.ends_with("_spec.rb") || n.ends_with(".test.ts")
                })
                .count();
            if id == "no_tests" { test_count == 0 } else { route_count > test_count + 2 }
        }
        // "Lots of uncommitted changes" — re-run git status.
        "uncommitted_files" => {
            match std::process::Command::new("git")
                .args(["status", "--porcelain"])
                .current_dir(project_dir)
                .output()
            {
                Ok(out) => String::from_utf8_lossy(&out.stdout).lines().count() > 3,
                Err(_) => false,
            }
        }
        // Unknown id — let it through. New escalation types added to
        // scan_project should extend this match so they're verified.
        _ => true,
    }
}

/// Background thinking loop — runs as a tokio task.
pub async fn background_thinking_loop(
    project_dir: PathBuf,
    settings: ChatSettings,
    thought_tx: tokio::sync::broadcast::Sender<String>,
) {
    let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(300)); // every 5 minutes
    // Skip the first tick (fires immediately)
    interval.tick().await;

    loop {
        interval.tick().await;

        let issues = scan_project(&project_dir);
        if issues.is_empty() {
            continue;
        }

        let mut escalations = load_escalations(&project_dir);
        let now = chrono_now();

        // Auto-resolve escalations whose issue no longer appears in the
        // current scan. Without this, the engine keeps pushing a thought
        // for "missing .env.example" long after the user added the file.
        // Mark acted_on rather than removing — preserves the history so
        // we can audit what the engine flagged + when it got fixed.
        let live_ids: std::collections::HashSet<String> = issues.iter().map(|(_, id, _)| id.clone()).collect();
        for esc in escalations.iter_mut() {
            if !esc.dismissed && !esc.acted_on && !live_ids.contains(&esc.id) {
                esc.acted_on = true;
                // Note the resolution time via last_prompted so an audit
                // of escalations.json shows when the issue disappeared.
                esc.last_prompted = now.clone();
            }
        }

        // Track new issues
        for (category, id, description) in &issues {
            let existing = escalations.iter_mut().find(|e| e.id == *id);
            if let Some(esc) = existing {
                if esc.dismissed || esc.acted_on { continue; }
                if esc.level < 3 {
                    esc.level += 1;
                    esc.last_prompted = now.clone();
                    esc.message = description.clone();
                }
            } else {
                escalations.push(Escalation {
                    id: id.clone(), category: category.clone(), level: 1,
                    message: description.clone(), first_seen: now.clone(),
                    last_prompted: now.clone(), dismissed: false, acted_on: false,
                });
            }
        }
        save_escalations(&project_dir, &escalations);

        // Pick the most important un-dismissed issue, *and* re-verify
        // its claim against the filesystem right before emitting. Belt
        // and braces — even if auto-resolution above misses an edge
        // case, the claim has to still be true at emit time.
        let active: Vec<&Escalation> = escalations.iter()
            .filter(|e| !e.dismissed && !e.acted_on && e.level >= 1)
            .filter(|e| verify_escalation_claim(&project_dir, &e.id))
            .collect();

        if let Some(top) = active.first() {
            // Ask the LLM to phrase it like a thoughtful colleague
            let reflection_prompt = format!(
                "You noticed this about the developer's project: {}\n\
                Escalation level: {} (1=gentle, 2=concerned, 3=urgent)\n\
                Category: {}\n\n\
                Write a single short message (2-3 sentences max) as if you're a friendly senior developer \
                who genuinely cares about the project. Be conversational, not robotic. \
                Show you understand WHY this matters, not just WHAT the issue is. \
                If level 3, express real concern about risk. \
                Don't use bullet points. Don't use headers. Just talk naturally.",
                top.message, top.level, top.category
            );

            let human_message = match llm_call(
                &settings.thinking, "",
                &[LlmMessage { role: "user".into(), content: reflection_prompt }],
                256, 0.7
            ).await {
                Ok(msg) => {
                    // Clean up — remove any JSON wrapping the LLM might add
                    let cleaned = msg.trim().trim_matches('"').to_string();
                    cleaned
                }
                Err(_) => top.message.clone(), // Fallback to raw message
            };

            let actions = match top.category.as_str() {
                "uncommitted" if top.level >= 3 => vec![
                    ThoughtAction { label: "Create backup branch".into(), action: "create_branch".into() },
                    ThoughtAction { label: "Not now".into(), action: "dismiss".into() },
                ],
                "uncommitted" => vec![
                    ThoughtAction { label: "Let's commit".into(), action: "commit".into() },
                    ThoughtAction { label: "I'm on it".into(), action: "dismiss".into() },
                ],
                "untested" if top.level >= 2 => vec![
                    ThoughtAction { label: "Help me write tests".into(), action: "scaffold_tests".into() },
                    ThoughtAction { label: "I'll handle it".into(), action: "dismiss".into() },
                ],
                "untested" => vec![
                    ThoughtAction { label: "Good idea, draft some".into(), action: "draft_tests".into() },
                    ThoughtAction { label: "Later".into(), action: "dismiss".into() },
                ],
                _ => vec![
                    ThoughtAction { label: "Tell me more".into(), action: "act".into() },
                    ThoughtAction { label: "Got it".into(), action: "dismiss".into() },
                ],
            };

            let thought = Thought {
                id: format!("{:x}", std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                timestamp: now.clone(),
                message: human_message,
                category: top.category.clone(),
                actions,
                dismissed: false,
            };

            save_thought(&project_dir, &thought);
            let thought_json = serde_json::to_string(&thought).unwrap_or_default();
            let _ = thought_tx.send(format!("event: thought\ndata: {}\n\n", thought_json));
        }
    }
}

/// Start the agent HTTP server (called by `tina4 serve` or `tina4 agent`).
pub fn run(port: u16) {
    println!("  {} Starting agent server on port {}", icon_play(), port);

    let project_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    // Scaffold agents if not present
    if !project_dir.join(".tina4").join("agents").exists() {
        scaffold_agents(&project_dir);
    }

    let agents = load_agents(&project_dir);
    println!("  {} Loaded {} agents: {}", icon_info(),
        agents.len(),
        agents.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "));

    // Start async runtime for the HTTP server + background thinking
    let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime");
    rt.block_on(async move {
        let settings = load_chat_settings(&project_dir);
        let (thought_tx, _) = tokio::sync::broadcast::channel::<String>(32);

        // Spawn background thinking loop
        let bg_dir = project_dir.clone();
        let bg_settings = settings.clone();
        let bg_tx = thought_tx.clone();
        tokio::spawn(async move {
            background_thinking_loop(bg_dir, bg_settings, bg_tx).await;
        });

        println!("  {} Background thinking loop started (every 5 min)", icon_info());

        serve_agent_http(port, &project_dir, &agents, thought_tx).await;
    });
}

/// Tiny HTTP server for agent endpoints.
async fn serve_agent_http(port: u16, project_dir: &Path, agents: &[Agent], thought_tx: tokio::sync::broadcast::Sender<String>) {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener as AsyncTcpListener;

    let listener = AsyncTcpListener::bind(format!("127.0.0.1:{}", port))
        .await
        .expect("Failed to bind agent port");

    println!("  {} Agent server listening on http://127.0.0.1:{}", icon_ok(), port);

    loop {
        let (mut stream, _addr) = match listener.accept().await {
            Ok(s) => s,
            Err(_) => continue,
        };

        let project_dir = project_dir.to_path_buf();
        let agents = agents.to_vec();

        tokio::spawn(async move {
            let mut buf = vec![0u8; 65536];
            let n = match stream.read(&mut buf).await {
                Ok(n) if n > 0 => n,
                _ => return,
            };

            let request = String::from_utf8_lossy(&buf[..n]);
            let first_line = request.lines().next().unwrap_or("");

            if first_line.starts_with("GET /health") {
                let body = r#"{"status":"ok"}"#;
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                    body.len(), body
                );
                let _ = stream.write_all(resp.as_bytes()).await;
            } else if first_line.starts_with("GET /agents") {
                let names: Vec<&str> = agents.iter().map(|a| a.name.as_str()).collect();
                let body = serde_json::to_string(&names).unwrap_or_default();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                    body.len(), body
                );
                let _ = stream.write_all(resp.as_bytes()).await;
            } else if first_line.starts_with("GET /history") {
                let history = load_history(&project_dir);
                let body = serde_json::to_string(&history).unwrap_or_default();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                    body.len(), body
                );
                let _ = stream.write_all(resp.as_bytes()).await;
            } else if first_line.starts_with("GET /thoughts") {
                let thoughts = load_thoughts(&project_dir);
                let body = serde_json::to_string(&thoughts).unwrap_or_default();
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                    body.len(), body
                );
                let _ = stream.write_all(resp.as_bytes()).await;
            } else if first_line.starts_with("POST /thoughts/dismiss") {
                // Dismiss a thought by ID
                let body_start = request.find("\r\n\r\n").unwrap_or(n) + 4;
                let body_str = &request[body_start..];
                #[derive(Deserialize)]
                struct DismissReq { id: String }
                if let Ok(req) = serde_json::from_str::<DismissReq>(body_str) {
                    let mut thoughts = load_thoughts(&project_dir);
                    if let Some(t) = thoughts.iter_mut().find(|t| t.id == req.id) {
                        t.dismissed = true;
                    }
                    let path = project_dir.join(".tina4").join("chat").join("thoughts.json");
                    let _ = fs::write(&path, serde_json::to_string_pretty(&thoughts).unwrap_or_default());

                    // Also dismiss the matching escalation
                    let mut escalations = load_escalations(&project_dir);
                    if let Some(e) = escalations.iter_mut().find(|e| !e.dismissed) {
                        e.dismissed = true;
                    }
                    save_escalations(&project_dir, &escalations);
                }
                let body = r#"{"ok":true}"#;
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                    body.len(), body
                );
                let _ = stream.write_all(resp.as_bytes()).await;
            } else if first_line.starts_with("POST /chat") {
                // Extract body from HTTP request
                let body_start = request.find("\r\n\r\n").unwrap_or(n) + 4;
                let body_str = &request[body_start..];

                // Parse request
                #[derive(Deserialize)]
                struct ChatRequest {
                    message: String,
                    #[serde(default)]
                    thread_id: Option<String>,
                    #[serde(default)]
                    settings: Option<ChatSettings>,
                }

                let chat_req: ChatRequest = match serde_json::from_str(body_str) {
                    Ok(r) => r,
                    Err(e) => {
                        let err_body = format!(r#"{{"error":"Invalid request: {}"}}"#, e);
                        let resp = format!(
                            "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            err_body.len(), err_body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                        return;
                    }
                };

                let settings = chat_req.settings.unwrap_or_else(|| load_chat_settings(&project_dir));

                // Resolve model settings for the agent
                let supervisor = agents.iter().find(|a| a.name == "supervisor");
                let model_settings = &settings.thinking;

                // Save user message
                let user_msg = ChatMessage {
                    id: format!("{:x}", std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                    role: "user".into(),
                    content: chat_req.message.clone(),
                    timestamp: chrono_now(),
                    thread_id: chat_req.thread_id.clone(),
                    agent: None,
                };
                save_message(&project_dir, &user_msg);

                // SSE response headers
                let headers = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\nAccess-Control-Allow-Origin: *\r\nX-Accel-Buffering: no\r\n\r\n";
                let _ = stream.write_all(headers.as_bytes()).await;

                // Status: thinking
                let _ = stream.write_all(
                    format!("event: status\ndata: {{\"text\":\"Analyzing request...\",\"agent\":\"supervisor\"}}\n\n").as_bytes()
                ).await;
                let _ = stream.flush().await;

                // Helper: send SSE event
                async fn sse_event(stream: &mut tokio::net::TcpStream, event: &str, data: &str) {
                    use tokio::io::AsyncWriteExt;
                    let _ = stream.write_all(format!("event: {}\ndata: {}\n\n", event, data).as_bytes()).await;
                    let _ = stream.flush().await;
                }

                fn sse_json(obj: &serde_json::Value) -> String {
                    serde_json::to_string(obj).unwrap_or_default()
                }

                // Resolve model for an agent by its config.model field
                fn resolve_model<'a>(agent_name: &str, agents: &[Agent], settings: &'a ChatSettings) -> &'a ModelSettings {
                    let model_type = agents.iter()
                        .find(|a| a.name == agent_name)
                        .map(|a| a.config.model.as_str())
                        .unwrap_or("thinking");
                    match model_type {
                        "vision" => &settings.vision,
                        "image-gen" => &settings.image_gen,
                        _ => &settings.thinking,
                    }
                }

                // Step 1: Call supervisor with conversation history + project context
                let supervisor_prompt = supervisor.map(|s| s.system_prompt.as_str()).unwrap_or("");

                // Build message history — last 20 messages for context
                let history = load_history(&project_dir);
                let recent: Vec<&ChatMessage> = history.iter()
                    .filter(|m| m.thread_id == chat_req.thread_id)
                    .rev().take(20).collect::<Vec<_>>().into_iter().rev().collect();

                let mut msgs: Vec<LlmMessage> = Vec::new();

                // Add project context as first system-like message
                let plans_dir = project_dir.join(".tina4").join("plans");
                let latest_plan = if plans_dir.exists() {
                    fs::read_dir(&plans_dir).ok()
                        .and_then(|entries| entries
                            .filter_map(|e| e.ok())
                            .filter(|e| e.path().extension().map_or(false, |ext| ext == "md"))
                            .max_by_key(|e| e.metadata().ok().and_then(|m| m.modified().ok())))
                        .and_then(|entry| fs::read_to_string(entry.path()).ok())
                } else {
                    None
                };

                if let Some(ref plan) = latest_plan {
                    // Give supervisor awareness of the current plan
                    let plan_summary = if plan.len() > 800 { format!("{}...", &plan[..800]) } else { plan.clone() };
                    msgs.push(LlmMessage {
                        role: "system".into(),
                        content: format!("Current project plan:\n{}", plan_summary),
                    });
                }

                // Add conversation history
                for m in &recent {
                    let mut content = m.content.clone();
                    // Truncate long messages to save tokens
                    if content.len() > 600 {
                        content = format!("{}...(truncated)", &content[..600]);
                    }
                    msgs.push(LlmMessage {
                        role: if m.role == "user" { "user".into() } else { "assistant".into() },
                        content,
                    });
                }
                msgs.push(LlmMessage { role: "user".into(), content: chat_req.message.clone() });

                let supervisor_reply = match llm_call(model_settings, supervisor_prompt, &msgs, 2048, 0.3).await {
                    Ok(r) => r,
                    Err(e) => {
                        let escaped = e.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                        sse_event(&mut stream, "error", &format!("{{\"message\":\"{}\"}}", escaped)).await;
                        return;
                    }
                };

                // Step 2: Parse the supervisor's action
                let action = parse_supervisor_action(&supervisor_reply);

                match action {
                    Some(SupervisorAction { action: ref a, .. }) if a == "plan" => {
                        let ctx = action.as_ref().and_then(|a| a.context.clone()).unwrap_or_default();
                        sse_event(&mut stream, "status", &sse_json(&serde_json::json!({"text": "→ Planner: creating plan...", "agent": "planner"}))).await;

                        // Call planner agent
                        let planner = agents.iter().find(|a| a.name == "planner");
                        let planner_prompt = planner.map(|p| p.system_prompt.as_str()).unwrap_or("");
                        let planner_model = resolve_model("planner", &agents, &settings);

                        // Build planner context — no paths or tech details
                        let planner_msg = format!(
                            "Create an implementation plan for the following request:\n\n{}",
                            ctx
                        );
                        let planner_msgs = vec![LlmMessage { role: "user".into(), content: planner_msg }];

                        match llm_call(planner_model, planner_prompt, &planner_msgs, 4096, 0.2).await {
                            Ok(plan_content) => {
                                // Save plan to .tina4/plans/
                                let plan_name = format!("{}-plan.md", chrono_now().replace("Z", ""));
                                let plan_path = project_dir.join(".tina4").join("plans").join(&plan_name);
                                let _ = fs::write(&plan_path, &plan_content);

                                sse_event(&mut stream, "status", &sse_json(&serde_json::json!({
                                    "text": format!("Plan created: .tina4/plans/{}", plan_name),
                                    "agent": "planner"
                                }))).await;

                                // Send plan content + approval buttons as a single event
                                let plan_escaped = plan_content.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                                sse_event(&mut stream, "plan", &format!(
                                    "{{\"content\":\"{}\",\"agent\":\"planner\",\"file\":\".tina4/plans/{}\",\"approve\":true}}",
                                    plan_escaped, plan_name
                                )).await;

                                // Save assistant message
                                save_message(&project_dir, &ChatMessage {
                                    id: format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                                    role: "assistant".into(),
                                    content: plan_content,
                                    timestamp: chrono_now(),
                                    thread_id: chat_req.thread_id.clone(),
                                    agent: Some("planner".into()),
                                });
                            }
                            Err(e) => {
                                let escaped = e.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                                sse_event(&mut stream, "error", &format!("{{\"message\":\"Planner failed: {}\"}}", escaped)).await;
                            }
                        }
                    }

                    Some(SupervisorAction { action: ref a, .. }) if a == "code" => {
                        let ctx = action.as_ref().and_then(|a| a.context.clone()).unwrap_or_default();
                        let files = action.as_ref().and_then(|a| a.files.clone()).unwrap_or_default();
                        sse_event(&mut stream, "status", &sse_json(&serde_json::json!({"text": "→ Grounding against tina4-rag…", "agent": "coder"}))).await;

                        let coder = agents.iter().find(|a| a.name == "coder");
                        let coder_prompt = coder.map(|c| c.system_prompt.as_str()).unwrap_or("");
                        let coder_model = resolve_model("coder", &agents, &settings);

                        let base_msg = format!(
                            "Write the following code:\n\n{}\n\nFiles to create/modify: {:?}\n\nReturn each file as:\n## FILE: path/to/file\n```\ncontent\n```",
                            ctx, files
                        );
                        // Prepend RAG-retrieved framework patterns + a
                        // machine-checkable grounding requirement so the
                        // coder cites or explicitly diverges from the
                        // examples. One retry if the first attempt skips
                        // the citation.
                        let (coder_msg, hits) = ground_coder_msg(&base_msg, &ctx, &files).await;
                        sse_event(&mut stream, "status", &sse_json(&serde_json::json!({"text": "→ Coder: writing code…", "agent": "coder"}))).await;
                        let coder_msgs = vec![LlmMessage { role: "user".into(), content: coder_msg }];

                        match llm_call_with_grounding_retry(coder_model, coder_prompt, coder_msgs, 4096, 0.1, &hits).await {
                            Ok(code_output) => {
                                // Parse file outputs and write them
                                let mut files_written = Vec::new();
                                for section in code_output.split("## FILE:") {
                                    let section = section.trim();
                                    if section.is_empty() { continue; }
                                    let mut lines = section.lines();
                                    if let Some(file_path) = lines.next() {
                                        let file_path = file_path.trim();
                                        // Extract content between ``` markers
                                        let remaining: String = lines.collect::<Vec<&str>>().join("\n");
                                        let content = if let Some(start) = remaining.find("```") {
                                            let after = &remaining[start + 3..];
                                            // Skip language identifier on first line
                                            let after = if let Some(nl) = after.find('\n') { &after[nl+1..] } else { after };
                                            if let Some(end) = after.find("```") { &after[..end] } else { after }
                                        } else {
                                            remaining.as_str()
                                        };

                                        let full_path = project_dir.join(file_path);
                                        if let Some(parent) = full_path.parent() {
                                            let _ = fs::create_dir_all(parent);
                                        }
                                        if fs::write(&full_path, content.trim()).is_ok() {
                                            files_written.push(file_path.to_string());
                                            sse_event(&mut stream, "status", &sse_json(&serde_json::json!({
                                                "text": format!("Written: {}", file_path),
                                                "agent": "coder"
                                            }))).await;
                                        }
                                    }
                                }

                                let msg = if files_written.is_empty() {
                                    code_output.clone()
                                } else {
                                    format!("Created {} files:\n{}", files_written.len(), files_written.iter().map(|f| format!("- {}", f)).collect::<Vec<_>>().join("\n"))
                                };

                                let escaped = msg.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                                sse_event(&mut stream, "message", &format!(
                                    "{{\"content\":\"{}\",\"agent\":\"coder\",\"files_changed\":{}}}", escaped,
                                    serde_json::to_string(&files_written).unwrap_or_default()
                                )).await;

                                save_message(&project_dir, &ChatMessage {
                                    id: format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                                    role: "assistant".into(),
                                    content: msg,
                                    timestamp: chrono_now(),
                                    thread_id: chat_req.thread_id.clone(),
                                    agent: Some("coder".into()),
                                });
                            }
                            Err(e) => {
                                let escaped = e.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                                sse_event(&mut stream, "error", &format!("{{\"message\":\"Coder failed: {}\"}}", escaped)).await;
                            }
                        }
                    }

                    Some(SupervisorAction { action: ref a, .. }) if a == "execute_plan" => {
                        // Execute plan step by step
                        let plan_file = action.as_ref().and_then(|a| a.context.clone()).unwrap_or_default();
                        let plan_path = project_dir.join(&plan_file);
                        let plan_content = fs::read_to_string(&plan_path).unwrap_or_default();

                        if plan_content.is_empty() {
                            sse_event(&mut stream, "message", &format!(
                                "{{\"content\":\"I couldn't find the plan. Let me create a new one.\",\"agent\":\"supervisor\"}}"
                            )).await;
                        } else {
                            // Parse numbered steps from plan
                            let steps: Vec<String> = plan_content.lines()
                                .filter(|line| {
                                    let trimmed = line.trim();
                                    // Match lines starting with a number followed by . or )
                                    trimmed.len() > 2 && trimmed.chars().next().map_or(false, |c| c.is_ascii_digit())
                                        && (trimmed.contains(". ") || trimmed.contains(") "))
                                })
                                .map(|line| {
                                    let trimmed = line.trim();
                                    // Strip the number prefix
                                    if let Some(pos) = trimmed.find(". ") {
                                        trimmed[pos + 2..].to_string()
                                    } else if let Some(pos) = trimmed.find(") ") {
                                        trimmed[pos + 2..].to_string()
                                    } else {
                                        trimmed.to_string()
                                    }
                                })
                                .collect();

                            let total_steps = steps.len();
                            sse_event(&mut stream, "status", &sse_json(&serde_json::json!({
                                "text": format!("Executing plan — {} steps", total_steps),
                                "agent": "supervisor"
                            }))).await;

                            let coder = agents.iter().find(|a| a.name == "coder");
                            let coder_prompt = coder.map(|c| c.system_prompt.as_str()).unwrap_or("");
                            let coder_model = resolve_model("coder", &agents, &settings);

                            let mut all_files_written: Vec<String> = Vec::new();
                            let mut step_summaries: Vec<String> = Vec::new();

                            for (i, step) in steps.iter().enumerate() {
                                let step_num = i + 1;

                                // Tell the user what we're working on
                                let progress_msg = format!("Step {} of {}: {}", step_num, total_steps, step);
                                sse_event(&mut stream, "status", &sse_json(&serde_json::json!({
                                    "text": progress_msg.clone(),
                                    "agent": "coder"
                                }))).await;
                                sse_event(&mut stream, "message", &format!(
                                    "{{\"content\":\"**Step {} of {}:** {}\\n\\nWorking on this now...\",\"agent\":\"supervisor\"}}",
                                    step_num, total_steps, step.replace('\\', "\\\\").replace('"', "\\\"")
                                )).await;

                                // Send step to coder — RAG-grounded so the
                                // model writes off actual Tina4 examples.
                                // Files list inferred from the step text
                                // is sparse here, but the step + language
                                // tag in the query is still enough to
                                // retrieve useful convention chunks.
                                let base_msg = format!(
                                    "Implement this single step from the project plan:\n\n**Step {}:** {}\n\n\
                                    Full plan context:\n{}\n\n\
                                    Project directory: {}\n\n\
                                    Return each file as:\n## FILE: path/to/file\n```\ncontent\n```",
                                    step_num, step, plan_content, project_dir.display()
                                );
                                let (coder_msg, hits) = ground_coder_msg(&base_msg, step, &[]).await;
                                let coder_msgs = vec![LlmMessage { role: "user".into(), content: coder_msg }];

                                match llm_call_with_grounding_retry(coder_model, coder_prompt, coder_msgs, 4096, 0.1, &hits).await {
                                    Ok(code_output) => {
                                        // Parse and write files
                                        let mut step_files = Vec::new();
                                        for section in code_output.split("## FILE:") {
                                            let section = section.trim();
                                            if section.is_empty() { continue; }
                                            let mut lines = section.lines();
                                            if let Some(file_path) = lines.next() {
                                                let file_path = file_path.trim();
                                                let remaining: String = lines.collect::<Vec<&str>>().join("\n");
                                                let content = if let Some(start) = remaining.find("```") {
                                                    let after = &remaining[start + 3..];
                                                    let after = if let Some(nl) = after.find('\n') { &after[nl+1..] } else { after };
                                                    if let Some(end) = after.find("```") { &after[..end] } else { after }
                                                } else {
                                                    remaining.as_str()
                                                };

                                                let full_path = project_dir.join(file_path);
                                                if let Some(parent) = full_path.parent() {
                                                    let _ = fs::create_dir_all(parent);
                                                }
                                                if fs::write(&full_path, content.trim()).is_ok() {
                                                    step_files.push(file_path.to_string());
                                                    all_files_written.push(file_path.to_string());
                                                }
                                            }
                                        }

                                        // Report step completion
                                        let done_msg = if step_files.is_empty() {
                                            format!("Step {} complete.", step_num)
                                        } else {
                                            format!("Step {} complete — {} files updated.", step_num, step_files.len())
                                        };
                                        step_summaries.push(format!("{}. {}", step_num, step));

                                        sse_event(&mut stream, "status", &sse_json(&serde_json::json!({
                                            "text": done_msg,
                                            "agent": "coder"
                                        }))).await;
                                    }
                                    Err(e) => {
                                        step_summaries.push(format!("{}. {} ✗ (failed)", step_num, step));
                                        let err_escaped = e.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                                        sse_event(&mut stream, "message", &format!(
                                            "{{\"content\":\"Step {} had an issue: {}. Moving on...\",\"agent\":\"supervisor\"}}",
                                            step_num, err_escaped
                                        )).await;
                                    }
                                }
                            }

                            // Final summary
                            let summary = format!(
                                "All done! Here's what I built:\\n\\n{}\\n\\n{} files were created or updated.",
                                step_summaries.iter().map(|s| format!("- {}", s.replace('\\', "\\\\").replace('"', "\\\""))).collect::<Vec<_>>().join("\\n"),
                                all_files_written.len()
                            );
                            sse_event(&mut stream, "message", &format!(
                                "{{\"content\":\"{}\",\"agent\":\"supervisor\",\"files_changed\":{}}}",
                                summary, serde_json::to_string(&all_files_written).unwrap_or_default()
                            )).await;

                            // Save summary as message
                            save_message(&project_dir, &ChatMessage {
                                id: format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                                role: "assistant".into(),
                                content: format!("Plan executed: {} steps, {} files written", step_summaries.len(), all_files_written.len()),
                                timestamp: chrono_now(),
                                thread_id: chat_req.thread_id.clone(),
                                agent: Some("supervisor".into()),
                            });
                        }
                    }

                    Some(SupervisorAction { action: ref a, .. }) if a == "debug" => {
                        let err_msg = action.as_ref().and_then(|a| a.error.clone()).unwrap_or_default();
                        sse_event(&mut stream, "status", &sse_json(&serde_json::json!({"text": "→ Debug: analyzing error...", "agent": "debug"}))).await;

                        let debug_agent = agents.iter().find(|a| a.name == "debug");
                        let debug_prompt = debug_agent.map(|d| d.system_prompt.as_str()).unwrap_or("");
                        let debug_model = resolve_model("debug", &agents, &settings);
                        let debug_msgs = vec![LlmMessage { role: "user".into(), content: format!("Analyze this error and suggest a fix:\n\n{}", err_msg) }];

                        match llm_call(debug_model, debug_prompt, &debug_msgs, 4096, 0.2).await {
                            Ok(analysis) => {
                                let escaped = analysis.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                                sse_event(&mut stream, "message", &format!("{{\"content\":\"{}\",\"agent\":\"debug\"}}", escaped)).await;
                                save_message(&project_dir, &ChatMessage {
                                    id: format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                                    role: "assistant".into(), content: analysis, timestamp: chrono_now(),
                                    thread_id: chat_req.thread_id.clone(), agent: Some("debug".into()),
                                });
                            }
                            Err(e) => {
                                let escaped = e.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                                sse_event(&mut stream, "error", &format!("{{\"message\":\"Debug failed: {}\"}}", escaped)).await;
                            }
                        }
                    }

                    Some(SupervisorAction { action: ref a, message: Some(ref msg), .. }) if a == "respond" => {
                        // Direct response — no delegation needed
                        let escaped = msg.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                        sse_event(&mut stream, "status", &sse_json(&serde_json::json!({"text": "Responding...", "agent": "supervisor"}))).await;
                        sse_event(&mut stream, "message", &format!("{{\"content\":\"{}\",\"agent\":\"supervisor\"}}", escaped)).await;

                        save_message(&project_dir, &ChatMessage {
                            id: format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                            role: "assistant".into(), content: msg.clone(), timestamp: chrono_now(),
                            thread_id: chat_req.thread_id.clone(), agent: Some("supervisor".into()),
                        });
                    }

                    Some(SupervisorAction { action: ref a, .. }) if a == "generate_image" => {
                        let img_prompt = action.as_ref().and_then(|a| a.prompt.clone()).unwrap_or_default();
                        sse_event(&mut stream, "status", &sse_json(&serde_json::json!({"text": "→ Image Gen: generating image...", "agent": "image-gen"}))).await;

                        // Call image generation endpoint
                        let img_settings = &settings.image_gen;
                        let base_url = img_settings.url.trim_end_matches('/');
                        let img_url = if base_url.contains("/v1/") { base_url.to_string() } else { format!("{}/v1/images/generations", base_url) };

                        let client = reqwest::Client::new();
                        let img_body = serde_json::json!({
                            "model": img_settings.model,
                            "prompt": img_prompt,
                            "n": 1,
                            "size": "512x512"
                        });

                        let mut req = client.post(&img_url).header("Content-Type", "application/json").json(&img_body);
                        if !img_settings.api_key.is_empty() {
                            req = req.header("Authorization", format!("Bearer {}", img_settings.api_key));
                        }

                        match req.send().await {
                            Ok(resp) => {
                                let text = resp.text().await.unwrap_or_default();
                                match serde_json::from_str::<serde_json::Value>(&text) {
                                    Ok(data) => {
                                        // Extract image URL or base64 from response
                                        let img_data = data["data"][0]["url"].as_str()
                                            .or_else(|| data["data"][0]["b64_json"].as_str())
                                            .unwrap_or("");
                                        let is_b64 = data["data"][0]["b64_json"].is_string();

                                        let img_html = if is_b64 {
                                            format!("Generated image for: {}\\n\\n<img src=\\\"data:image/png;base64,{}\\\" style=\\\"max-width:100%;border-radius:8px\\\">", img_prompt.replace('"', "\\\""), img_data.replace('"', "\\\""))
                                        } else if !img_data.is_empty() {
                                            format!("Generated image for: {}\\n\\n<img src=\\\"{}\\\" style=\\\"max-width:100%;border-radius:8px\\\">", img_prompt.replace('"', "\\\""), img_data.replace('"', "\\\""))
                                        } else {
                                            format!("Image generated for: {}", img_prompt.replace('"', "\\\""))
                                        };

                                        sse_event(&mut stream, "message", &format!("{{\"content\":\"{}\",\"agent\":\"image-gen\"}}", img_html)).await;
                                    }
                                    Err(_) => {
                                        let escaped = format!("Image generation returned unexpected response").replace('"', "\\\"");
                                        sse_event(&mut stream, "message", &format!("{{\"content\":\"{}\",\"agent\":\"image-gen\"}}", escaped)).await;
                                    }
                                }
                            }
                            Err(e) => {
                                let escaped = format!("Image generation failed: {}", e).replace('"', "\\\"").replace('\n', "\\n");
                                sse_event(&mut stream, "error", &format!("{{\"message\":\"{}\"}}", escaped)).await;
                            }
                        }

                        save_message(&project_dir, &ChatMessage {
                            id: format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                            role: "assistant".into(), content: format!("Generated image: {}", img_prompt), timestamp: chrono_now(),
                            thread_id: chat_req.thread_id.clone(), agent: Some("image-gen".into()),
                        });
                    }

                    Some(SupervisorAction { action: ref a, .. }) if a == "analyze_image" => {
                        sse_event(&mut stream, "status", &sse_json(&serde_json::json!({"text": "→ Vision: analyzing image...", "agent": "vision"}))).await;
                        // Vision requires image data — for now respond with a message
                        let msg = "I can see you want me to analyze an image. Please attach an image and I'll describe what I see.";
                        let escaped = msg.replace('"', "\\\"");
                        sse_event(&mut stream, "message", &format!("{{\"content\":\"{}\",\"agent\":\"vision\"}}", escaped)).await;

                        save_message(&project_dir, &ChatMessage {
                            id: format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                            role: "assistant".into(), content: msg.to_string(), timestamp: chrono_now(),
                            thread_id: chat_req.thread_id.clone(), agent: Some("vision".into()),
                        });
                    }

                    _ => {
                        // Fallback — try to extract a message from the JSON, never show raw JSON
                        let display_msg = if let Some(ref act) = action {
                            act.message.clone()
                                .or_else(|| act.context.clone())
                                .or_else(|| act.prompt.clone())
                                .unwrap_or_else(|| "I'm processing your request...".to_string())
                        } else {
                            "I'm processing your request...".to_string()
                        };
                        let escaped = display_msg.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                        sse_event(&mut stream, "message", &format!("{{\"content\":\"{}\",\"agent\":\"supervisor\"}}", escaped)).await;

                        save_message(&project_dir, &ChatMessage {
                            id: format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis()),
                            role: "assistant".into(), content: display_msg, timestamp: chrono_now(),
                            thread_id: chat_req.thread_id.clone(), agent: Some("supervisor".into()),
                        });
                    }
                }

                // Done
                sse_event(&mut stream, "status", &sse_json(&serde_json::json!({"text": "Done", "agent": "supervisor"}))).await;
                sse_event(&mut stream, "done", "{}").await;
            } else if first_line.starts_with("POST /execute") {
                // Direct plan execution — bypasses supervisor, goes straight to coder
                let body_start = request.find("\r\n\r\n").unwrap_or(n) + 4;
                let body_str = &request[body_start..];

                #[derive(Deserialize)]
                struct ExecRequest {
                    plan_file: String,
                    #[serde(default)]
                    settings: Option<ChatSettings>,
                    #[serde(default)]
                    resume: bool,
                }

                #[derive(Debug, Clone, Serialize, Deserialize, Default)]
                struct PlanState {
                    completed: Vec<usize>,
                    files: Vec<String>,
                }

                let exec_req: ExecRequest = match serde_json::from_str(body_str) {
                    Ok(r) => r,
                    Err(e) => {
                        let err_body = format!(r#"{{"error":"Invalid request: {}"}}"#, e);
                        let resp = format!(
                            "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            err_body.len(), err_body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                        return;
                    }
                };

                let settings = exec_req.settings.unwrap_or_else(|| load_chat_settings(&project_dir));

                // SSE headers
                let headers = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\nAccess-Control-Allow-Origin: *\r\nX-Accel-Buffering: no\r\n\r\n";
                let _ = stream.write_all(headers.as_bytes()).await;

                async fn sse_ev(stream: &mut tokio::net::TcpStream, event: &str, data: &str) {
                    use tokio::io::AsyncWriteExt;
                    let _ = stream.write_all(format!("event: {}\ndata: {}\n\n", event, data).as_bytes()).await;
                    let _ = stream.flush().await;
                }

                fn sse_j(obj: &serde_json::Value) -> String {
                    serde_json::to_string(obj).unwrap_or_default()
                }

                // Read the plan
                let plan_path = project_dir.join(&exec_req.plan_file);
                let plan_content = fs::read_to_string(&plan_path).unwrap_or_default();

                if plan_content.is_empty() {
                    sse_ev(&mut stream, "error", &sse_j(&serde_json::json!({"message":"Plan file not found"}))).await;
                    sse_ev(&mut stream, "done", "{}").await;
                    return;
                }

                // Parse steps. We accept TWO plan formats — numbered lists
                // AND GitHub-style markdown checkboxes ("- [ ] step",
                // "* [x] step"). The dev-admin UI writes checkboxes
                // because it renders checkbox progress natively; hand-
                // written plans usually use numbered lists. Either way
                // we end up with a {text, done} struct per step so we
                // can skip already-completed work without needing a
                // separate state.json.
                #[derive(Clone)]
                struct Step { text: String, done: bool }

                let mut steps: Vec<Step> = Vec::new();
                for line in plan_content.lines() {
                    let trimmed = line.trim();
                    if trimmed.len() < 3 { continue; }

                    // Checkbox: `- [ ] X`, `* [ ] X`, `- [x] X` (case-insensitive x)
                    if (trimmed.starts_with("- ") || trimmed.starts_with("* "))
                        && trimmed.len() > 5 && trimmed.as_bytes()[2] == b'['
                        && trimmed.as_bytes()[4] == b']'
                    {
                        let box_char = trimmed.as_bytes()[3];
                        let done = box_char == b'x' || box_char == b'X';
                        let text = trimmed[5..].trim().to_string();
                        if !text.is_empty() { steps.push(Step { text, done }); }
                        continue;
                    }

                    // Numbered: `1. X` or `1) X`
                    let first = trimmed.chars().next().unwrap_or(' ');
                    if first.is_ascii_digit() && (trimmed.contains(". ") || trimmed.contains(") ")) {
                        let text = if let Some(pos) = trimmed.find(". ") {
                            trimmed[pos + 2..].to_string()
                        } else if let Some(pos) = trimmed.find(") ") {
                            trimmed[pos + 2..].to_string()
                        } else {
                            trimmed.to_string()
                        };
                        if !text.is_empty() { steps.push(Step { text, done: false }); }
                    }
                }

                let total = steps.len();

                // Load existing state for resume
                let state_path = plan_path.with_extension("state.json");
                let mut state: PlanState = if exec_req.resume {
                    fs::read_to_string(&state_path).ok()
                        .and_then(|s| serde_json::from_str(&s).ok())
                        .unwrap_or_default()
                } else {
                    PlanState::default()
                };

                let skip_count = state.completed.len();
                if skip_count > 0 {
                    sse_ev(&mut stream, "message", &format!(
                        "{{\"content\":\"Resuming from step {}{} steps already done.\",\"agent\":\"supervisor\"}}",
                        skip_count + 1, skip_count
                    )).await;
                }

                sse_ev(&mut stream, "status", &sse_j(&serde_json::json!({"text": format!("Building — {} steps ({} remaining)", total, total - skip_count), "agent": "supervisor"}))).await;

                let coder = agents.iter().find(|a| a.name == "coder");
                let coder_prompt = coder.map(|c| c.system_prompt.as_str()).unwrap_or("");
                let coder_model_type = coder.map(|a| a.config.model.as_str()).unwrap_or("thinking");
                let coder_model = match coder_model_type { "vision" => &settings.vision, "image-gen" => &settings.image_gen, _ => &settings.thinking };

                let mut summaries: Vec<String> = Vec::new();
                let mut failed = false;

                for (i, step) in steps.iter().enumerate() {
                    let num = i + 1;
                    let step_text = step.text.clone();

                    // Skip completed steps — either marked in state.json
                    // (from an earlier run that was interrupted) OR
                    // already ticked in the markdown itself (the AI
                    // chat calls plan_complete_step which sets `[x]`).
                    if step.done || state.completed.contains(&num) {
                        summaries.push(format!("{}. {} ✓ (done earlier)", num, step_text));
                        if !state.completed.contains(&num) { state.completed.push(num); }
                        continue;
                    }

                    // Progress update
                    let step_escaped = step_text.replace('\\', "\\\\").replace('"', "\\\"");
                    sse_ev(&mut stream, "message", &format!(
                        "{{\"content\":\"**Step {} of {}:** {}\",\"agent\":\"supervisor\"}}",
                        num, total, step_escaped
                    )).await;
                    sse_ev(&mut stream, "status", &sse_j(&serde_json::json!({"text": format!("Step {}/{}: {}", num, total, step_text), "agent": "coder"}))).await;

                    // Build real project context by scanning files
                    let project_ctx = build_project_context(&project_dir);
                    let framework_ctx = load_framework_context(&project_dir);

                    // Call coder with full project + framework context.
                    // The framework cheat-sheet teaches it tina4 idioms
                    // (response() not response.json(), DatabaseResult.records,
                    // @noauth import path, etc.) so first-turn code is correct
                    // for the specific tina4 flavour in use.
                    //
                    // RAG grounding is layered on top of the static
                    // cheat-sheet: the cheat-sheet covers the universal
                    // idioms, RAG pulls chunks specific to *this* step's
                    // intent. Together they beat either on its own.
                    let base_msg = format!(
                        "{}## Project Context\n{}\n\n\
                        ## Task\nImplement step {} of {}:\n**{}**\n\n\
                        ## Full Plan\n{}\n\n\
                        Return each file as:\n## FILE: path/to/file\n```\ncontent\n```",
                        framework_ctx, project_ctx, num, total, step_text, plan_content
                    );
                    let (coder_msg, hits) = ground_coder_msg(&base_msg, &step_text, &[]).await;
                    let coder_msgs = vec![LlmMessage { role: "user".into(), content: coder_msg }];

                    match llm_call_with_grounding_retry(coder_model, coder_prompt, coder_msgs, 4096, 0.1, &hits).await {
                        Ok(code_output) => {
                            let mut step_files = Vec::new();
                            for section in code_output.split("## FILE:") {
                                let section = section.trim();
                                if section.is_empty() { continue; }
                                let mut lines = section.lines();
                                if let Some(file_path) = lines.next() {
                                    let file_path = file_path.trim();
                                    let remaining: String = lines.collect::<Vec<&str>>().join("\n");
                                    let content = if let Some(start) = remaining.find("```") {
                                        let after = &remaining[start + 3..];
                                        let after = if let Some(nl) = after.find('\n') { &after[nl+1..] } else { after };
                                        if let Some(end) = after.find("```") { &after[..end] } else { after }
                                    } else { remaining.as_str() };

                                    let full_path = project_dir.join(file_path);
                                    if let Some(parent) = full_path.parent() { let _ = fs::create_dir_all(parent); }
                                    if fs::write(&full_path, content.trim()).is_ok() {
                                        step_files.push(file_path.to_string());
                                        state.files.push(file_path.to_string());
                                    }
                                }
                            }

                            // Mark step complete and save state immediately
                            state.completed.push(num);
                            let _ = fs::write(&state_path, serde_json::to_string_pretty(&state).unwrap_or_default());

                            summaries.push(format!("{}. {}", num, step_text));
                            sse_ev(&mut stream, "status", &sse_j(&serde_json::json!({"text": format!("Step {} done — {} files", num, step_files.len()), "agent": "coder"}))).await;
                        }
                        Err(e) => {
                            summaries.push(format!("{}. {}", num, step_text));
                            failed = true;

                            // Save state so we can resume from here
                            let _ = fs::write(&state_path, serde_json::to_string_pretty(&state).unwrap_or_default());

                            let err_esc = e.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
                            sse_ev(&mut stream, "message", &format!(
                                "{{\"content\":\"Step {} failed: {}\\n\\nYou can resume from here.\",\"agent\":\"supervisor\"}}",
                                num, err_esc
                            )).await;

                            // Send resume event so frontend can show Resume button
                            sse_ev(&mut stream, "plan_failed", &format!(
                                "{{\"file\":\"{}\",\"completed\":{},\"total\":{},\"failed_step\":{}}}",
                                exec_req.plan_file.replace('\\', "\\\\").replace('"', "\\\""),
                                state.completed.len(), total, num
                            )).await;
                            break; // Stop on first failure
                        }
                    }
                }

                // Final summary
                let summary_lines = summaries.iter().map(|s| format!("- {}", s.replace('\\', "\\\\").replace('"', "\\\""))).collect::<Vec<_>>().join("\\n");
                if failed {
                    sse_ev(&mut stream, "message", &format!(
                        "{{\"content\":\"Progress so far:\\n\\n{}\\n\\n{} files created. Resume when ready.\",\"agent\":\"supervisor\",\"files_changed\":{}}}",
                        summary_lines, state.files.len(), serde_json::to_string(&state.files).unwrap_or_default()
                    )).await;
                } else {
                    // All done — clean up state file
                    let _ = fs::remove_file(&state_path);
                    sse_ev(&mut stream, "message", &format!(
                        "{{\"content\":\"All done!\\n\\n{}\\n\\n{} files created or updated.\",\"agent\":\"supervisor\",\"files_changed\":{}}}",
                        summary_lines, state.files.len(), serde_json::to_string(&state.files).unwrap_or_default()
                    )).await;
                }
                sse_ev(&mut stream, "done", "{}").await;

            } else if first_line.starts_with("GET /supervise/sessions") {
                // List active supervisor sessions. Used by dev-admin to
                // rehydrate state after a reload — each returned session
                // has a branch + worktree that can be diffed/committed.
                let sessions = crate::session::list_sessions(&project_dir);
                let body = serde_json::to_string(&sessions).unwrap_or_else(|_| "[]".into());
                let resp = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                    body.len(), body
                );
                let _ = stream.write_all(resp.as_bytes()).await;
            } else if first_line.starts_with("POST /supervise/create") {
                // Create a new session: git worktree + branch off HEAD.
                // Body: {"title": "...", "plan": "..."} — both optional.
                let body_start = request.find("\r\n\r\n").unwrap_or(n) + 4;
                let body_str = &request[body_start..];
                #[derive(Deserialize, Default)]
                struct CreateReq {
                    #[serde(default)]
                    title: String,
                    #[serde(default)]
                    plan: String,
                }
                let req: CreateReq = serde_json::from_str(body_str).unwrap_or_default();
                match crate::session::create_session(&project_dir, &req.title, &req.plan) {
                    Ok(meta) => {
                        let body = serde_json::to_string(&meta).unwrap_or_default();
                        let resp = format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            body.len(), body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                    }
                    Err(e) => {
                        let body = format!(r#"{{"error":{}}}"#, serde_json::to_string(&e).unwrap_or_default());
                        let resp = format!(
                            "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            body.len(), body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                    }
                }
            } else if first_line.starts_with("GET /supervise/diff") {
                // Dev-admin renders the Diff tab from this payload. The
                // session id comes in the query string (?id=abc) so the
                // browser can just fetch it without a POST body.
                //
                // After computing the raw git diff, we decorate it with
                // RAG-backed convention warnings (slice 3). The session
                // worktree is the right place to look at file content
                // from — that's the branch version the user is about to
                // apply. Async path is kept off the hot sync diff so a
                // slow RAG doesn't block the git work.
                let id = extract_query_param(first_line, "id").unwrap_or_default();
                if id.is_empty() {
                    let body = r#"{"error":"missing id"}"#;
                    let resp = format!(
                        "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                        body.len(), body
                    );
                    let _ = stream.write_all(resp.as_bytes()).await;
                } else {
                    match crate::session::diff_session(&project_dir, &id) {
                        Ok(mut diff) => {
                            // Find the session worktree so we can read
                            // the branch-version of each changed file
                            // (which may differ from main-tree contents).
                            let worktree = crate::session::list_sessions(&project_dir)
                                .into_iter()
                                .find(|s| s.id == diff.id)
                                .map(|s| s.worktree);
                            if let Some(worktree) = worktree {
                                let files: Vec<(String, String)> = diff.files.iter()
                                    .filter(|f| f.status != "D") // can't verify a deleted file
                                    .map(|f| (f.path.clone(), detect_language_from_path(&f.path)))
                                    .collect();
                                if !files.is_empty() {
                                    let warnings = crate::rag::verify_files(&worktree, &files).await;
                                    diff.warnings = warnings;
                                }
                            }
                            let body = serde_json::to_string(&diff).unwrap_or_default();
                            let resp = format!(
                                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                                body.len(), body
                            );
                            let _ = stream.write_all(resp.as_bytes()).await;
                        }
                        Err(e) => {
                            let body = format!(r#"{{"error":{}}}"#, serde_json::to_string(&e).unwrap_or_default());
                            let resp = format!(
                                "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                                body.len(), body
                            );
                            let _ = stream.write_all(resp.as_bytes()).await;
                        }
                    }
                }
            } else if first_line.starts_with("POST /supervise/rag/search") {
                // Expose raw RAG search so agents (and humans poking the
                // server) can retrieve framework snippets without
                // speaking tina4-rag's wire format directly. Mostly
                // used during the coder prompt assembly where a single
                // query fans out into the system prompt.
                let body_start = request.find("\r\n\r\n").unwrap_or(n) + 4;
                let body_str = &request[body_start..];
                #[derive(Deserialize, Default)]
                struct SearchReq {
                    query: String,
                    #[serde(default = "default_top_k")]
                    top_k: usize,
                }
                fn default_top_k() -> usize { 5 }
                let req: SearchReq = serde_json::from_str(body_str).unwrap_or_default();
                if req.query.is_empty() {
                    let body = r#"{"error":"missing query"}"#;
                    let resp = format!(
                        "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                        body.len(), body
                    );
                    let _ = stream.write_all(resp.as_bytes()).await;
                } else {
                    let hits = crate::rag::search(&req.query, req.top_k).await;
                    let body = serde_json::to_string(&serde_json::json!({
                        "query": req.query,
                        "hits": hits,
                    })).unwrap_or_default();
                    let resp = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                        body.len(), body
                    );
                    let _ = stream.write_all(resp.as_bytes()).await;
                }
            } else if first_line.starts_with("POST /supervise/commit") {
                // Apply the session's diff to the user's working tree.
                // Body: {"id": "...", "accept": ["path1", ...]} — empty
                // accept means "apply all."
                let body_start = request.find("\r\n\r\n").unwrap_or(n) + 4;
                let body_str = &request[body_start..];
                #[derive(Deserialize, Default)]
                struct CommitReq {
                    id: String,
                    #[serde(default)]
                    accept: Vec<String>,
                }
                let req: CommitReq = match serde_json::from_str(body_str) {
                    Ok(r) => r,
                    Err(e) => {
                        let body = format!(r#"{{"error":"invalid body: {}"}}"#, e);
                        let resp = format!(
                            "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            body.len(), body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                        return;
                    }
                };
                match crate::session::commit_session(&project_dir, &req.id, &req.accept) {
                    Ok(result) => {
                        let body = serde_json::to_string(&result).unwrap_or_default();
                        let resp = format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            body.len(), body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                    }
                    Err(e) => {
                        let body = format!(r#"{{"error":{}}}"#, serde_json::to_string(&e).unwrap_or_default());
                        let resp = format!(
                            "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            body.len(), body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                    }
                }
            } else if first_line.starts_with("POST /supervise/cancel") {
                // Drop the session's worktree + branch. Idempotent.
                // Body: {"id": "..."}
                let body_start = request.find("\r\n\r\n").unwrap_or(n) + 4;
                let body_str = &request[body_start..];
                #[derive(Deserialize)]
                struct CancelReq { id: String }
                let req: CancelReq = match serde_json::from_str(body_str) {
                    Ok(r) => r,
                    Err(e) => {
                        let body = format!(r#"{{"error":"invalid body: {}"}}"#, e);
                        let resp = format!(
                            "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            body.len(), body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                        return;
                    }
                };
                match crate::session::cancel_session(&project_dir, &req.id) {
                    Ok(()) => {
                        let body = r#"{"ok":true}"#;
                        let resp = format!(
                            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            body.len(), body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                    }
                    Err(e) => {
                        let body = format!(r#"{{"error":{}}}"#, serde_json::to_string(&e).unwrap_or_default());
                        let resp = format!(
                            "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccess-Control-Allow-Origin: *\r\n\r\n{}",
                            body.len(), body
                        );
                        let _ = stream.write_all(resp.as_bytes()).await;
                    }
                }
            } else if first_line.starts_with("OPTIONS") {
                // CORS preflight
                let resp = "HTTP/1.1 204 No Content\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\nAccess-Control-Allow-Headers: Content-Type, Authorization\r\nAccess-Control-Max-Age: 86400\r\n\r\n";
                let _ = stream.write_all(resp.as_bytes()).await;
            } else {
                let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
                let _ = stream.write_all(resp.as_bytes()).await;
            }
        });
    }
}

/// Decorate a coder user-message with retrieved framework patterns
/// AND mandate a machine-checkable citation comment on each emitted
/// file. `verify_coder_grounding` parses the response for these
/// citations; writes without them get bounced back as a retry.
///
/// Degrades gracefully: if RAG is unreachable or returns no hits, the
/// base message goes through unchanged and the verifier is a no-op.
/// A down RAG should never block writes — that'd be worse than
/// un-grounded writes.
///
/// Returns (enriched_message, hits). Caller passes hits into
/// `verify_coder_grounding` so verification only runs when we actually
/// had RAG context to cite.
async fn ground_coder_msg(base_msg: &str, task: &str, files: &[String])
    -> (String, Vec<crate::rag::RagHit>)
{
    let query = build_rag_query(task, files);
    if query.is_empty() {
        return (base_msg.to_string(), Vec::new());
    }
    let hits = crate::rag::search(&query, 4).await;
    let context = crate::rag::format_hits_for_prompt(&hits, 500);
    if context.is_empty() {
        return (base_msg.to_string(), hits);
    }

    // MANDATORY citation: every emitted file must start with a
    // comment naming the RAG hit it was grounded in (or explicitly
    // flagging a deliberate divergence). The verifier checks for this
    // and bounces missing citations back for a retry.
    //
    // Why this matters: slice 4 retrieved RAG context, slice 3
    // verifies files post-commit. The gap was "the coder read the
    // chunks but ignored them." A machine-checkable citation
    // requirement closes that gap — either the coder follows a
    // pattern it cites, or it explicitly says which pattern it's
    // breaking and why. Anything else fails the verifier.
    let grounding_rule = "\n\nGROUNDING (mandatory):\n\
        Every file you emit MUST start with exactly one comment line:\n\
        - `# grounded-by: [N]` where N is the index of the RAG example \
           you followed (e.g. `# grounded-by: [0]`).\n\
        - `# diverging-from-rag: <one-line reason>` if you deliberately \
           chose a pattern not in the retrieved examples.\n\
        Use the language's line-comment syntax (# for python/ruby, // \
        for js/ts/php, -- for sql, {# … #} for twig). The comment is \
        the FIRST non-blank line of the file. Files without this comment \
        will be rejected and you'll be asked to rewrite.";

    let enriched = format!(
        "{context}{grounding_rule}\n\n--- TASK ---\n\n{base_msg}"
    );
    (enriched, hits)
}

/// Verify that the coder's response cited the RAG grounding as
/// instructed. Returns Ok(()) if every file block starts with a
/// grounding comment, or Err(explanation) with a message suitable
/// for feeding back as a retry prompt.
///
/// Called only when hits were non-empty — if RAG returned nothing,
/// there's nothing to cite, and we accept the response as-is.
fn verify_coder_grounding(response: &str, hits: &[crate::rag::RagHit]) -> Result<(), String> {
    if hits.is_empty() {
        return Ok(()); // no grounding context was injected → nothing to cite
    }
    let mut offending: Vec<String> = Vec::new();
    for section in response.split("## FILE:") {
        let section = section.trim();
        if section.is_empty() { continue; }
        let mut lines = section.lines();
        let path = lines.next().unwrap_or("").trim();
        if path.is_empty() { continue; }
        // Find the first content line after the opening ``` fence.
        // Skip empty lines + the ``` marker + optional language tag.
        let mut saw_open_fence = false;
        let mut first_line_of_code: Option<&str> = None;
        for line in lines {
            let trimmed = line.trim();
            if !saw_open_fence {
                if trimmed.starts_with("```") { saw_open_fence = true; }
                continue;
            }
            if trimmed.is_empty() { continue; }
            if trimmed.starts_with("```") { break; } // empty file block
            first_line_of_code = Some(trimmed);
            break;
        }
        let first = first_line_of_code.unwrap_or("").to_lowercase();
        // Accept any of the comment styles, since the coder picks the
        // right one for the language. Require "grounded-by" or
        // "diverging-from-rag" in the first line of code.
        let ok = first.contains("grounded-by") || first.contains("diverging-from-rag");
        if !ok {
            offending.push(path.to_string());
        }
    }
    if offending.is_empty() {
        Ok(())
    } else {
        Err(format!(
            "These files are missing the mandatory grounding citation on line 1: {}.\n\
            Rewrite every file to start with `# grounded-by: [N]` (citing a retrieved example) \
            or `# diverging-from-rag: <reason>`. Use the language's comment syntax.",
            offending.join(", ")
        ))
    }
}

/// Call the coder LLM with a single retry when grounding verification
/// fails. Sequence:
///   1. First attempt with the original prompt.
///   2. Run `verify_coder_grounding` on the response.
///   3. If it fails, feed the error message back as an additional
///      assistant/user turn and retry ONCE more.
///   4. Return the final response regardless of whether retry passed
///      — better a best-effort write than a hard block when the model
///      just can't comply.
///
/// The retry is bounded at one attempt because two failures usually
/// means the model is confused about the format, not genuinely
/// un-grounded, and further retries waste tokens + latency.
async fn llm_call_with_grounding_retry(
    model: &ModelSettings,
    system_prompt: &str,
    mut messages: Vec<LlmMessage>,
    max_tokens: u32,
    temperature: f32,
    hits: &[crate::rag::RagHit],
) -> Result<String, String> {
    let first = llm_call(model, system_prompt, &messages, max_tokens, temperature).await?;
    match verify_coder_grounding(&first, hits) {
        Ok(()) => Ok(first),
        Err(reason) => {
            eprintln!("[grounding] first attempt failed verification, retrying once: {reason}");
            // Feed the first response back so the model sees what it
            // emitted, then append the correction. qwen responds well
            // to seeing its own output + a specific correction.
            messages.push(LlmMessage { role: "assistant".into(), content: first });
            messages.push(LlmMessage {
                role: "user".into(),
                content: format!(
                    "Your response missed the mandatory grounding citation. {reason}\n\n\
                    Rewrite the files with the required comment as the first line. Emit ONLY the corrected `## FILE:` blocks."
                ),
            });
            llm_call(model, system_prompt, &messages, max_tokens, temperature).await
        }
    }
}

/// Build the query string we hand to tina4-rag for coder grounding.
/// Combines (a) the detected language from the first target file with
/// (b) the first 120 chars of the task description. That's usually
/// enough signal for semantic retrieval to surface the right chunks.
fn build_rag_query(task: &str, files: &[String]) -> String {
    let lang = files
        .iter()
        .map(|f| detect_language_from_path(f))
        .find(|l| l != "general")
        .unwrap_or_default();
    let short_task: String = task.chars().take(120).collect();
    let combined = if lang.is_empty() {
        short_task.trim().to_string()
    } else {
        format!("{lang} {}", short_task.trim())
    };
    combined.trim().to_string()
}

/// Map a file extension / path shape to the language name RAG
/// verification expects ("python", "javascript", "typescript",
/// "php", "ruby", "sql"). Falls back to "general" for anything the
/// corpus doesn't specifically tag — still lets retrieval work off
/// the query text alone.
fn detect_language_from_path(path: &str) -> String {
    let lower = path.to_lowercase();
    if lower.ends_with(".py") { return "python".into(); }
    if lower.ends_with(".ts") || lower.ends_with(".tsx") { return "typescript".into(); }
    if lower.ends_with(".js") || lower.ends_with(".jsx") || lower.ends_with(".mjs") { return "javascript".into(); }
    if lower.ends_with(".php") { return "php".into(); }
    if lower.ends_with(".rb") { return "ruby".into(); }
    if lower.ends_with(".sql") { return "sql".into(); }
    if lower.ends_with(".twig") || lower.ends_with(".jinja") { return "twig".into(); }
    if lower.ends_with(".html") || lower.ends_with(".htm") { return "html".into(); }
    "general".into()
}

/// Pull a query-string parameter out of an HTTP request line like
/// `GET /supervise/diff?id=abc123 HTTP/1.1`. Returns None if the
/// parameter isn't present. Minimal URL-decoding — we only emit
/// session ids (hex) and plain slugs, so percent-decoding is not
/// needed here. If richer params start flowing through the query
/// string, swap this for a proper decoder.
fn extract_query_param(request_line: &str, key: &str) -> Option<String> {
    // Format: METHOD /path[?q=v&...] HTTP/X.Y
    let path = request_line.split_whitespace().nth(1)?;
    let q = path.split_once('?')?.1;
    for pair in q.split('&') {
        if let Some((k, v)) = pair.split_once('=') {
            if k == key {
                return Some(v.to_string());
            }
        }
    }
    None
}

fn chrono_now() -> String {
    // Simple ISO 8601 timestamp without chrono dep
    let d = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let secs = d.as_secs();
    // Good enough for now — proper chrono can be added later
    format!("{}Z", secs)
}

// ── Tests ─────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rag::{RagHit, RagMetadata};

    fn hit(title: &str) -> RagHit {
        RagHit {
            text: "from tina4_python.core.router import get\n@get('/x')\nasync def x(req, res): pass".into(),
            metadata: RagMetadata { title: title.into(), ..Default::default() },
            distance: 0.3,
        }
    }

    #[test]
    fn grounding_ok_when_no_hits_even_if_missing_citation() {
        // If RAG was unreachable or empty, we have nothing to cite —
        // don't block writes.
        let response = "## FILE: src/x.py\n```\nprint('hi')\n```";
        assert!(verify_coder_grounding(response, &[]).is_ok());
    }

    #[test]
    fn grounding_ok_with_grounded_by_comment() {
        let response = "\
## FILE: src/x.py
```
# grounded-by: [0]
from tina4_python.core.router import get
```";
        assert!(verify_coder_grounding(response, &[hit("Ch 2")]).is_ok());
    }

    #[test]
    fn grounding_ok_with_diverging_comment() {
        let response = "\
## FILE: src/x.py
```
# diverging-from-rag: using Flask here because the project is hybrid
from flask import Blueprint
```";
        assert!(verify_coder_grounding(response, &[hit("Ch 2")]).is_ok());
    }

    #[test]
    fn grounding_rejects_missing_citation() {
        let response = "\
## FILE: src/x.py
```
from tina4_python.core.router import get
async def x(req, res): pass
```";
        let r = verify_coder_grounding(response, &[hit("Ch 2")]);
        assert!(r.is_err());
        assert!(r.unwrap_err().contains("src/x.py"));
    }

    #[test]
    fn grounding_rejects_only_offending_files_named() {
        // Mixed response — one cited, one not. Error message should
        // name only the bad file so the retry prompt is focused.
        let response = "\
## FILE: src/good.py
```
# grounded-by: [1]
x = 1
```

## FILE: src/bad.py
```
y = 2
```";
        let r = verify_coder_grounding(response, &[hit("Ch 2")]);
        assert!(r.is_err());
        let msg = r.unwrap_err();
        assert!(msg.contains("src/bad.py"));
        assert!(!msg.contains("src/good.py"));
    }

    #[test]
    fn grounding_accepts_slash_slash_comment_for_js() {
        let response = "\
## FILE: src/x.ts
```
// grounded-by: [0]
export function x() {}
```";
        assert!(verify_coder_grounding(response, &[hit("Ch 2")]).is_ok());
    }

    #[test]
    fn grounding_accepts_dash_dash_comment_for_sql() {
        let response = "\
## FILE: migrations/0001.sql
```
-- grounded-by: [3]
CREATE TABLE x (id INT);
```";
        assert!(verify_coder_grounding(response, &[hit("Ch 2")]).is_ok());
    }

    #[test]
    fn grounding_skips_blank_lines_before_citation() {
        // Fenced blocks sometimes open with a blank line; the verifier
        // should treat the first non-blank line as "line 1 of code."
        let response = "\
## FILE: src/x.py
```

# grounded-by: [0]
print('hi')
```";
        assert!(verify_coder_grounding(response, &[hit("Ch 2")]).is_ok());
    }

    // ── verify_escalation_claim ─────────────────────────────

    #[test]
    fn escalation_claim_no_env_example_drops_when_file_exists() {
        let tmp = std::env::temp_dir().join(format!("tina4-esc-{}", std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join(".env"), "X=1").unwrap();
        // No .env.example → claim applies
        assert!(verify_escalation_claim(&tmp, "no_env_example"));
        // Add .env.example → claim no longer applies
        std::fs::write(tmp.join(".env.example"), "X=").unwrap();
        assert!(!verify_escalation_claim(&tmp, "no_env_example"));
        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn escalation_claim_unknown_id_passes_through() {
        // Unknown escalation ids haven't been wired into the verifier
        // yet; they should fall through rather than silently drop.
        let tmp = std::env::temp_dir();
        assert!(verify_escalation_claim(&tmp, "new_category_future"));
    }
}