anda_brain 0.13.1

🧠 Anda Brain (大脑) — Autonomous Graph Memory for AI Agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
use anda_core::{
    Agent, AgentContext, AgentOutput, BoxError, CompletionRequest, Document, Documents, Message,
    Resource, StateFeatures, Tool, estimate_tokens,
};
use anda_db::{
    collection::Collection,
    schema::{DocumentId, Json, Map},
};
use anda_engine::{
    context::{AgentCtx, CompletionRunner},
    extension::note::NoteTool,
    local_date_hour,
    memory::{Conversation, ConversationRef, ConversationStatus, MemoryManagement},
    unix_ms,
};
use parking_lot::RwLock;
use serde::Deserialize;
use serde_json::json;
use std::{
    collections::VecDeque,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
};

use super::{BrainHook, PERSON_BY_KEY, RunnerFlow, RunnerHost, drive_runner_loop, first_row};
use crate::types::FormationInput;

const REVIEW_INSTRUCTIONS: &str = include_str!("../../assets/BrainFormationReview.md");

/// The conversation `extra` member counting its failed processing rounds.
const FAILED_ROUNDS_KEY: &str = "formation_failed_rounds";
/// Failed rounds (an attempt and its retry each) before Formation stops
/// retrying a conversation and lets the queue move past it.
const MAX_FAILED_ROUNDS: u64 = 3;
/// The least time those failures must span, so a short provider outage does
/// not discard the conversations queued through it.
const GIVE_UP_AFTER_MS: u64 = 30 * 60 * 1000;

/// How often, and since when, a conversation has failed a whole round.
#[derive(Debug, Default, PartialEq, Eq, serde::Serialize, Deserialize)]
struct FailedRounds {
    rounds: u64,
    first_failed_at: u64,
}

// A cost heuristic for one semantic omission check, not a completeness guarantee.
// KIP validates writes, but cannot tell which source facts the model overlooked.
const REVIEW_MIN_INPUT_TOKENS: usize = 10_000;

fn review_prompt(conversation_id: DocumentId, message_count: usize) -> String {
    let captured = message_count.min(crate::kip::MAX_INGESTED_MESSAGES);
    let bindings = if captured == 0 {
        "No input-message Evidence bindings are available.".to_string()
    } else {
        format!(
            "Host write-time Evidence bindings :msg1 through :msg{captured} refer to input messages {} through {message_count} (1-based). Earlier messages have no automatic Evidence binding. Read committed Evidence by ids from write receipts or Assertion/Activity links; :msgN is not a read parameter.",
            message_count - captured + 1
        )
    };
    format!(
        "{REVIEW_INSTRUCTIONS}\n\nHost review scope: formation conversation {conversation_id}, {message_count} input messages. {bindings}"
    )
}

// The runner guardrails are shared with maintenance; see
// `RUNNER_MAX_MODEL_TURNS` in agents.rs. Tests keep the historical name.
#[cfg(test)]
use super::RUNNER_MAX_MODEL_TURNS as FORMATION_MAX_MODEL_TURNS;

/// Resets the AtomicU64 to 0 on drop (panic guard for processing_conversation).
struct ProcessingGuard(Option<Arc<AtomicU64>>);
impl ProcessingGuard {
    fn disarm(mut self) {
        self.0.take();
    }
}
impl Drop for ProcessingGuard {
    fn drop(&mut self) {
        if let Some(value) = &self.0 {
            value.store(0, Ordering::SeqCst);
        }
    }
}

#[derive(Clone)]
pub struct FormationAgent {
    product_control: Option<Arc<crate::product::control::Control>>,
    prompt: Arc<str>,
    memory: Arc<MemoryManagement>,
    /// The collection backing `memory`'s conversations. `MemoryManagement`
    /// wraps document access only, so the `brain_processed` watermark — a
    /// collection extension — is read and written through this handle.
    conversations: Arc<Collection>,
    processing_conversation: Arc<AtomicU64>,
    processing_gate: Arc<super::ProcessingGate>,
    hook: Arc<dyn BrainHook>,
    history: Arc<RwLock<VecDeque<Document>>>,
    max_input_tokens: usize,
    clock: Arc<crate::runtime::BusinessClock>,
    tasks: crate::runtime::RuntimeTasks,
}

impl FormationAgent {
    pub(crate) fn with_product_control(
        mut self,
        control: Arc<crate::product::control::Control>,
    ) -> Self {
        self.product_control = Some(control);
        self
    }
    pub const NAME: &'static str = "formation_memory";
    pub fn new(
        memory: Arc<MemoryManagement>,
        conversations: Arc<Collection>,
        hook: Arc<dyn BrainHook>,
        max_input_tokens: usize,
    ) -> Self {
        Self {
            product_control: None,
            prompt: super::prompts::active_prompt(super::prompts::PromptTarget::Formation),
            clock: Arc::new(crate::runtime::BusinessClock::default()),
            tasks: crate::runtime::RuntimeTasks::default(),
            max_input_tokens,
            memory,
            conversations,
            processing_conversation: Arc::new(AtomicU64::new(0)),
            processing_gate: Arc::new(super::ProcessingGate::default()),
            history: Arc::new(RwLock::new(VecDeque::new())),
            hook,
        }
    }

    pub(crate) fn with_prompt(mut self, prompt: Arc<str>) -> Self {
        self.prompt = prompt;
        self
    }

    pub(crate) fn with_clock(mut self, clock: Arc<crate::runtime::BusinessClock>) -> Self {
        self.clock = clock;
        self
    }

    pub(crate) fn with_tasks(mut self, tasks: crate::runtime::RuntimeTasks) -> Self {
        self.tasks = tasks;
        self
    }

    pub(crate) fn with_processing_gate(mut self, gate: Arc<super::ProcessingGate>) -> Self {
        self.processing_conversation = gate.formation.clone();
        self.processing_gate = gate;
        self
    }

    #[cfg(feature = "experiments")]
    pub(crate) fn clear_history(&self) {
        self.history.write().clear();
    }

    /// Backfills the completed-conversation ring after a restart, mirroring
    /// recall/maintenance `init` — without it the `history_formation` context
    /// block stays empty until the next conversation completes. Formation
    /// conversations live in the shared memory store under their ingesting
    /// user, so there is no single-user list to query; walk backwards from
    /// the newest conversation and keep the latest completed formation ones.
    /// The scan is bounded: this is best-effort context, not recovery state.
    pub async fn init(&self) -> Result<(), BoxError> {
        // Matches the `push_completed_history` cap in `drive_runner_loop`.
        const HISTORY_LEN: usize = 2;
        const SCAN_LIMIT: u64 = 32;

        let boundary = self
            .conversations
            .get_extension_as::<u64>("history_boundary")
            .unwrap_or(0);
        // Collected newest-first; the runtime ring runs oldest -> newest.
        let mut newest: Vec<Document> = Vec::with_capacity(HISTORY_LEN);
        let mut id = self.memory.max_conversation_id();
        let mut scanned = 0u64;
        while id > 0 && scanned < SCAN_LIMIT && newest.len() < HISTORY_LEN {
            scanned += 1;
            if let Ok(conv) = self.memory.get_conversation(id).await
                && conv._id > boundary
                && conv.status == ConversationStatus::Completed
                && conv
                    .label
                    .as_deref()
                    .is_none_or(|label| label == "formation")
            {
                newest.push(Document::from(conv));
            }
            id -= 1;
        }
        newest.reverse();
        *self.history.write() = newest.into();
        Ok(())
    }

    pub fn is_processing(&self) -> bool {
        self.processing_conversation.load(Ordering::SeqCst) != 0
    }

    pub(crate) fn processing_id(&self) -> u64 {
        self.processing_conversation.load(Ordering::SeqCst)
    }

    pub fn get_processed(&self) -> Option<DocumentId> {
        self.conversations
            .get_extension_as::<DocumentId>("brain_processed")
    }

    /// Sets the formation watermark without processing anything, so a test can
    /// stage "this Space has formed memory" without an LLM turn.
    #[cfg(test)]
    pub(crate) async fn set_processed_for_test(&self, id: DocumentId) {
        self.conversations
            .save_extension("brain_processed".to_string(), id.into())
            .await
            .unwrap();
    }

    /// Resolves the Person Concept for a counterparty, creating it once.
    ///
    /// The counterparty handle is the Concept's `key` — immutable Space-local
    /// identity — while `name` is a mutable display label. Matching on the key
    /// is what makes this idempotent: a name-only match would mint a second
    /// Person for anyone who renamed themselves, and a `key` is identity within
    /// its type, so `type` is not optional decoration here.
    ///
    /// A Person is semantic cognition. It is not a Principal and cannot
    /// authenticate as one — which is why nothing about this write says
    /// anything about what the counterparty may do.
    pub async fn get_or_init_counterparty(
        &self,
        counterparty: String,
        name: Option<String>,
    ) -> Result<Json, BoxError> {
        let preserve_name = name.is_none();
        if preserve_name {
            let existing = first_row(
                self.memory
                    .query(
                        PERSON_BY_KEY,
                        Some(crate::kip::param("key", counterparty.clone())),
                    )
                    .await?,
            );
            if !existing.is_null() {
                return Ok(existing);
            }
        }
        let parameters = Map::from_iter([
            ("key".to_string(), Json::from(counterparty.clone())),
            (
                "name".to_string(),
                Json::from(name.unwrap_or_else(|| counterparty.clone())),
            ),
        ]);
        let command = if preserve_name {
            // Creation can race another caller. A key collision is read back
            // below; an UPSERT would overwrite the winner's display name.
            r#"CREATE CONCEPT ?person { TYPE "Person" NAME :name SET FIELDS { key: :key } }"#
        } else {
            r#"UPSERT CONCEPT ?person {
  MATCH { type: "Person", key: :key }
  SET FIELDS { name: :name }
}"#
        };
        if let Err(error) = self.memory.execute(command, Some(parameters)).await
            && !(preserve_name && error.code == anda_kip::KipErrorCode::IdentityConflict)
        {
            return Err(error.into());
        }

        // Read back rather than returning the write receipt: callers want the
        // Person as it now stands, which on a match is not what this call sent.
        Ok(first_row(
            self.memory
                .query(
                    PERSON_BY_KEY,
                    Some(Map::from_iter([(
                        "key".to_string(),
                        Json::from(counterparty),
                    )])),
                )
                .await?,
        ))
    }

    pub async fn start_process(
        &self,
        ctx: AgentCtx,
        conversation: DocumentId,
    ) -> Result<(), BoxError> {
        let current = self.processing_conversation.load(Ordering::SeqCst);
        if current != 0 {
            return Err(format!(
                "FormationAgent is already processing conversation {}",
                current
            )
            .into());
        }
        if self.hook.is_maintenance_processing() {
            return Err(
                "MaintenanceAgent is processing, formation will resume when maintenance completes"
                    .into(),
            );
        }

        // Find the next valid pending conversation starting from the given ID (inclusive)
        let conv = self
            .find_next_submitted(conversation.saturating_sub(1))
            .await?
            .ok_or_else(|| {
                format!(
                    "No pending formation conversation found starting from {}",
                    conversation
                )
            })?;

        self.try_process(ctx, conv);
        Ok(())
    }

    pub fn try_process(&self, ctx: AgentCtx, conversation: Conversation) {
        let admission = self.processing_gate.admission.lock();
        if self.processing_gate.maintenance.load(Ordering::SeqCst)
            || self.hook.is_maintenance_processing()
        {
            return;
        }
        if self
            .processing_conversation
            .compare_exchange(0, conversation._id, Ordering::SeqCst, Ordering::SeqCst)
            .is_err()
        {
            log::info!(
                target: "brain",
                "FormationAgent is already processing conversation {}, cannot process conversation {}",
                self.processing_conversation.load(Ordering::SeqCst),
                conversation._id
            );
            return;
        }

        let agent = self.clone();
        let pc = self.processing_conversation.clone();
        let guard = ProcessingGuard(Some(pc));
        drop(admission);
        self.tasks.spawn(async move {
            // Guard is captured before spawn so cancellation before polling also releases the slot.
            agent.process_loop(ctx, conversation).await;
            // Normal exit: process_loop already manages the atomic properly,
            // so defuse the guard to avoid clobbering a valid value.
            guard.disarm();
        });
    }

    async fn process_loop(&self, ctx: AgentCtx, mut conversation: Conversation) {
        loop {
            let conv_id = conversation._id;

            self.process_one(&ctx, &mut conversation).await;
            self.hook
                .on_conversation_end(Self::NAME, &conversation)
                .await;
            if conversation.status == ConversationStatus::Failed {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await; // 避免快速失败循环
                // 重试一次
                self.process_one(&ctx, &mut conversation).await;
                // Counted before the hook, so a conversation given up on
                // settles its receipt with this same callback.
                if conversation.status == ConversationStatus::Failed {
                    self.record_failed_round(&mut conversation).await;
                }
                self.hook
                    .on_conversation_end(Self::NAME, &conversation)
                    .await;
            }

            if !matches!(
                conversation.status,
                ConversationStatus::Completed | ConversationStatus::Cancelled
            ) {
                log::error!(
                    target: "brain",
                    "Conversation {} ended with status {:?}, not marking as processed",
                    conv_id,
                    conversation.status
                );
                // 上游异常,重置 processing 状态以允许外部干预或后续请求自动触发
                self.processing_conversation.store(0, Ordering::SeqCst);
                break;
            }

            // The marker is a high-water mark: reprocessing an older
            // conversation (e.g. via restart_formation) must not rewind it.
            let processed = self.get_processed().unwrap_or_default().max(conv_id);
            self.conversations
                .save_extension("brain_processed".to_string(), processed.into())
                .await
                .ok();

            if let Some(id) = self.hook.try_start_maintenance(conv_id).await {
                log::info!(
                    target: "brain",
                    "Triggered maintenance for conversation {}, new maintenance conversation {}",
                    conv_id,
                    id
                );

                // The maintenance claim transferred the writer slot before
                // spawning its worker. Do not clear a newer formation owner.
                break; // 交由 maintenance agent 处理后续流程,退出循环
            }

            // 查找下一个待处理的 conversation
            match self.find_next_submitted(conv_id).await {
                Ok(Some(next_conv)) => {
                    if self
                        .processing_conversation
                        .compare_exchange(
                            conv_id,
                            next_conv._id,
                            Ordering::SeqCst,
                            Ordering::SeqCst,
                        )
                        .is_ok()
                    {
                        conversation = next_conv;
                        continue;
                    }
                    // CAS 失败说明其他线程已接管,退出
                    break;
                }
                Ok(None) => {
                    self.processing_conversation.store(0, Ordering::SeqCst);
                    // 双重检查:store(0) 前可能有新 conversation 到达但 try_process CAS 失败
                    if let Ok(Some(next_conv)) = self.find_next_submitted(conv_id).await
                        && {
                            let _admission = self.processing_gate.admission.lock();
                            !self.processing_gate.maintenance.load(Ordering::SeqCst)
                                && !self.hook.is_maintenance_processing()
                                && self
                                    .processing_conversation
                                    .compare_exchange(
                                        0,
                                        next_conv._id,
                                        Ordering::SeqCst,
                                        Ordering::SeqCst,
                                    )
                                    .is_ok()
                        }
                    {
                        conversation = next_conv;
                        continue;
                    }
                    break;
                }
                Err(error) => {
                    log::error!(target: "brain", "formation queue read failed: {error}");
                    self.processing_conversation.store(0, Ordering::SeqCst);
                    break;
                }
            }
        }
    }

    async fn find_next_submitted(&self, after_id: u64) -> Result<Option<Conversation>, BoxError> {
        use anda_db::query::{Filter, Fv, RangeQuery};
        let mut cursor = after_id;
        loop {
            let ids = self
                .conversations
                .query_ids(
                    Filter::And(vec![
                        Box::new(Filter::Field((
                            "_id".into(),
                            RangeQuery::Gt(Fv::U64(cursor)),
                        ))),
                        Box::new(Filter::Field((
                            "status".into(),
                            RangeQuery::Include(
                                [
                                    ConversationStatus::Submitted,
                                    ConversationStatus::Working,
                                    ConversationStatus::Idle,
                                    ConversationStatus::Failed,
                                ]
                                .into_iter()
                                .map(|status| Fv::Text(status.to_string()))
                                .collect(),
                            ),
                        ))),
                    ]),
                    Some(64),
                )
                .await?;
            if ids.is_empty() {
                return Ok(None);
            }
            for id in ids {
                cursor = id;
                let conv = self.memory.get_conversation(id).await?;
                if !matches!(
                    conv.status,
                    ConversationStatus::Completed | ConversationStatus::Cancelled
                ) && conv
                    .label
                    .as_deref()
                    .is_none_or(|label| label == "formation")
                {
                    return Ok(Some(conv));
                }
            }
        }
    }

    /// Records one failed round (an attempt and its retry) on the conversation.
    ///
    /// A conversation that fails every time — a provider refusal, an input
    /// over the model's context, a missing prompt — would otherwise stay the
    /// first pending id forever: the watermark cannot move past it, so every
    /// later conversation waits behind it. After [`MAX_FAILED_ROUNDS`] rounds
    /// spanning at least [`GIVE_UP_AFTER_MS`] it is cancelled with the last
    /// failure as its reason, which its receipt reports as failed, and the
    /// queue moves on.
    async fn record_failed_round(&self, conversation: &mut Conversation) {
        let now_ms = unix_ms();
        let extra = conversation.extra.get_or_insert_with(|| json!({}));
        let Some(extra) = extra.as_object_mut() else {
            return;
        };
        let mut failed: FailedRounds = extra
            .get(FAILED_ROUNDS_KEY)
            .and_then(|value| FailedRounds::deserialize(value).ok())
            .unwrap_or_default();
        failed.rounds += 1;
        if failed.first_failed_at == 0 {
            failed.first_failed_at = now_ms;
        }
        let give_up = failed.rounds >= MAX_FAILED_ROUNDS
            && now_ms.saturating_sub(failed.first_failed_at) >= GIVE_UP_AFTER_MS;
        extra.insert(FAILED_ROUNDS_KEY.into(), json!(failed));
        if give_up {
            let reason = format!(
                "formation_failed: gave up after {} failed rounds; last failure: {}",
                failed.rounds,
                conversation
                    .failed_reason
                    .as_deref()
                    .unwrap_or("unknown failure")
            );
            log::error!(
                target: "brain",
                "formation conversation {} cancelled: {reason}",
                conversation._id
            );
            conversation.status = ConversationStatus::Cancelled;
            conversation.failed_reason = Some(reason);
            conversation.updated_at = now_ms;
        }
        self.persist_conversation_snapshot(conversation).await;
    }

    async fn mark_conversation_failed(&self, conversation: &mut Conversation, reason: String) {
        super::mark_conversation_failed(
            |id, changes| self.memory.update_conversation(id, changes),
            "formation",
            conversation,
            reason,
        )
        .await;
    }

    /// Persists the current full conversation snapshot. A formation is
    /// retried, so a stale `failed_reason` is cleared on the way through.
    async fn persist_conversation_snapshot(&self, conversation: &Conversation) {
        super::persist_conversation_snapshot(
            |id, changes| self.memory.update_conversation(id, changes),
            "formation",
            conversation,
            true,
        )
        .await;
    }

    async fn process_one(&self, ctx: &AgentCtx, conversation: &mut Conversation) {
        if let Some(control) = &self.product_control {
            use crate::product::{SourceAdmissionError, SourceIdentity};
            let admission = SourceIdentity::for_conversation(conversation)
                .map_err(|_| SourceAdmissionError::Suppressed)
                .and_then(|source| control.admit_source(&source));
            match admission {
                Ok(epoch) => {
                    ctx.base.set_state(epoch);
                }
                Err(error) => {
                    conversation.status = match error {
                        SourceAdmissionError::Busy => ConversationStatus::Submitted,
                        SourceAdmissionError::Suppressed => ConversationStatus::Cancelled,
                    };
                    conversation.failed_reason = Some(error.to_string());
                    self.persist_conversation_snapshot(conversation).await;
                    return;
                }
            }
        }
        // A Memory Interface revision waits for its predecessors; one that
        // failed blocks it for good, and that is reported, not skipped
        // (MI §5.1).
        let intent = crate::memory_interface::MemoryIntent::of(conversation).map(Arc::new);
        if let Some(intent) = &intent
            && let Some(blocker) = self.hook.memory_predecessor_failed(intent).await
        {
            conversation.status = ConversationStatus::Cancelled;
            conversation.failed_reason = Some(format!("predecessor_failed:{blocker}"));
            self.persist_conversation_snapshot(conversation).await;
            return;
        }
        let trace = crate::memory_interface::FormationTrace::resume(conversation);
        ctx.base
            .set_state(crate::memory_interface::IntentState(intent.clone()));
        ctx.base.set_state(trace.clone());
        let prompt = match conversation
            .messages
            .first()
            .and_then(|v| Message::deserialize(v).ok())
            .and_then(|v| v.text())
        {
            Some(p) => p,
            None => {
                self.mark_conversation_failed(conversation, "No prompt found".to_string())
                    .await;
                return;
            }
        };

        // Markdown/raw-text submissions use the same host-owned Evidence path
        // as structured conversations. Keep their exact text as one message.
        let input =
            serde_json::from_str::<FormationInput>(&prompt).unwrap_or_else(|_| FormationInput {
                messages: vec![Message {
                    role: "user".into(),
                    content: vec![prompt.clone().into()],
                    ..Default::default()
                }],
                context: None,
                timestamp: None,
            });
        let counterparty = input
            .context
            .as_ref()
            .and_then(|input_ctx| input_ctx.counterparty.clone());

        let now_ms = unix_ms();
        // The context sources are independent; fetch them concurrently (same
        // pattern as recall's context assembly).
        let (counterparty_info, primer) = tokio::join!(
            async {
                match counterparty {
                    Some(counterparty) => {
                        self.get_or_init_counterparty(counterparty, None).await.ok()
                    }
                    None => None,
                }
            },
            async { self.memory.describe_primer().await.unwrap_or_default() },
        );

        // The observation this pass was called on, for the runtime to mint as
        // Evidence (Spec §71.1). Set unconditionally — see [`Observation`] —
        // and before the completion, so every `execute_kip` the model makes
        // inherits it.
        //
        // A thread/channel is provenance, not the identity of an observation.
        // Each durable conversation has its own key, stable across retries,
        // so a later submission from the same source cannot cite old bytes.
        let observation = crate::kip::observation_ingest(
            &input.messages,
            &crate::kip::observation_timestamp(input.timestamp.as_deref(), conversation.created_at),
            &format!("formation:conversation:{}", conversation._id),
            counterparty_info
                .as_ref()
                .and_then(|person| person.get("id"))
                .and_then(Json::as_str),
        )
        .map(|mut ingest| {
            // A scoped observation's Evidence carries its scope too, so the
            // raw source stays in its task (Profile §20.3).
            if let Some(intent) = &intent {
                intent.scope_evidence(&mut ingest);
            }
            ingest
        })
        .map(Arc::new);
        // Each claim's `at` is when its source said it (Spec §13.2), so the
        // model reads the captured times rather than guessing them.
        let captured = observation
            .as_deref()
            .map(crate::kip::observation_manifest)
            .unwrap_or_else(|| "none".into());
        ctx.base.set_state(super::Observation(observation));

        // add history conversations to provide more context for recall
        let chat_history: Vec<Document> = if self
            .product_control
            .as_ref()
            .is_some_and(|control| control.epoch() > 0)
        {
            vec![]
        } else {
            self.history.read().iter().cloned().collect()
        };

        let chat_history = if chat_history.is_empty() {
            vec![]
        } else {
            vec![Message {
                role: "user".into(),
                content: vec![
                    Documents::new("history_formation".to_string(), chat_history)
                        .to_string()
                        .into(),
                ],
                name: Some("$system".into()),
                timestamp: Some(now_ms),
                ..Default::default()
            }]
        };
        let review_prompt = (estimate_tokens(&prompt) >= REVIEW_MIN_INPUT_TOKENS)
            .then(|| review_prompt(conversation._id, input.messages.len()));
        super::install_note_index(ctx);
        let mut runner = ctx.clone().completion_iter(
            CompletionRequest {
                instructions: format!(
                    "{}\n\n---\n\n# `DESCRIBE PRIMER` Result:\n{}\n\n---\n\n# Counterparty Profile:\n{}\n\n# Captured Evidence:\n{}\n\n# Memory Interface Intent:\n{}\n\n# Current Datetime: {}",
                    super::prompts::system_prompt(super::prompts::PromptTarget::Formation, &self.prompt),
                    primer,
                    serde_json::to_string(&counterparty_info).unwrap_or_default(),
                    captured,
                    intent
                        .as_deref()
                        .map(crate::memory_interface::MemoryIntent::directive)
                        .unwrap_or_else(|| "none (an ordinary Formation submission)".into()),
                    local_date_hour(self.clock.now_ms()).unwrap_or_default()
                ),
                prompt,
                chat_history,
                tools: ctx.tool_definitions(Some(&self.tool_dependencies())),
                tool_choice_required: true,
                ..Default::default()
            },
            vec![],
        );
        runner.set_unbound(true);

        let mut host = FormationRunnerHost {
            agent: self,
            review_prompt,
            trace,
        };
        drive_runner_loop(&mut host, &mut runner, conversation).await;
    }
}

/// Formation's seams of the shared runner loop (`drive_runner_loop`): the
/// review pass for large inputs and the Failed-retry `failed_reason` reset.
struct FormationRunnerHost<'a> {
    agent: &'a FormationAgent,
    /// Taken once at the first successful idle boundary. The follow-up shares
    /// the runner's turn/time budgets and survives a compaction handoff.
    review_prompt: Option<String>,
    /// What the pass has committed, persisted with each snapshot so a
    /// receipt's disposition survives a restart.
    trace: crate::memory_interface::FormationTrace,
}

impl RunnerHost for FormationRunnerHost<'_> {
    fn label(&self) -> &'static str {
        "formation"
    }

    fn history(&self) -> &RwLock<VecDeque<Document>> {
        &self.agent.history
    }

    async fn persist_snapshot(&self, conversation: &Conversation) {
        self.agent.persist_conversation_snapshot(conversation).await;
    }

    async fn mark_failed(&self, conversation: &mut Conversation, reason: String) {
        self.agent
            .mark_conversation_failed(conversation, reason)
            .await;
    }

    fn turn_is_done(&self, runner: &CompletionRunner) -> bool {
        runner.is_done() || runner.is_idle() && self.review_prompt.is_none()
    }

    fn on_turn_success(&self, conversation: &mut Conversation) {
        // Clears a previous attempt's failure so the process_loop Failed
        // retry converges to a clean Completed snapshot.
        conversation.failed_reason = None;
        self.trace.persist_into(conversation);
    }

    fn after_turn(&mut self, runner: &mut CompletionRunner, is_done: bool) -> RunnerFlow {
        if runner.is_idle()
            && let Some(prompt) = self.review_prompt.take()
        {
            // Keep the write receipts, bound ids and readbacks the review needs.
            // The shared loop compacts when necessary; pruning all tool results
            // here would discard the very evidence this follow-up must inspect.
            runner.follow_up(prompt);
            return RunnerFlow::Continue;
        }

        if is_done {
            RunnerFlow::Break
        } else {
            RunnerFlow::Continue
        }
    }
}

impl Agent<AgentCtx> for FormationAgent {
    fn name(&self) -> String {
        Self::NAME.to_string()
    }

    fn description(&self) -> String {
        "Receives conversation messages and encodes them into structured memory within the Cognitive Nexus via KIP.".to_string()
    }

    fn tool_dependencies(&self) -> Vec<String> {
        vec![
            self.memory.name(),
            NoteTool::NAME.to_string(),
            crate::vocabulary::DeclareSymbolsTool::NAME.to_string(),
            crate::cognitive::MemoryRuntimeTool::NAME.to_string(),
            crate::kip_reference::KipReferenceTool::NAME.to_string(),
        ]
    }

    // 接收来自外部的 FormationInput,创建一个新的 Conversation,并启动处理流程。
    async fn run(
        &self,
        ctx: AgentCtx,
        prompt: String, // FormationInput serialized as JSON string
        _resources: Vec<Resource>,
    ) -> Result<AgentOutput, BoxError> {
        let caller = ctx.caller();
        let now_ms = unix_ms();
        let token_count = estimate_tokens(&prompt);
        if token_count > self.max_input_tokens {
            return Err(format!(
                "Input too large: {} tokens (estimated), max allowed is {} tokens",
                token_count, self.max_input_tokens
            )
            .into());
        }

        let mut conversation = Conversation {
            user: *caller,
            messages: vec![json!(Message {
                role: "user".into(),
                content: vec![prompt.into()],
                ..Default::default()
            })],
            period: now_ms / 3600 / 1000,
            created_at: now_ms,
            updated_at: now_ms,
            label: Some("formation".to_string()),
            extra: Some(json!(ctx.meta().extra)),
            ..Default::default()
        };

        let id = self
            .memory
            .add_conversation(ConversationRef::from(&conversation))
            .await?;
        conversation._id = id;
        let res = AgentOutput {
            conversation: Some(id),
            ..Default::default()
        };

        let is_idle = self.processing_conversation.load(Ordering::SeqCst) == 0;
        if is_idle {
            if self.hook.is_maintenance_processing() {
                log::info!(
                    target: "brain",
                    conversation = id;
                    "Formation queued while maintenance is processing"
                );
            } else {
                // A missing marker means nothing was processed yet; resume from
                // the beginning to catch conversations queued before this one.
                let prev_id = self.get_processed().unwrap_or_default();
                if prev_id + 1 < id {
                    // Resume from the last processed conversation to catch any missed ones
                    if let Some(conv) = self.find_next_submitted(prev_id).await? {
                        self.try_process(ctx, conv);
                    }
                } else {
                    self.try_process(ctx, conversation);
                }
            }
        }

        Ok(res)
    }
}

#[cfg(test)]
mod tests {
    use super::{FormationAgent, ProcessingGuard};
    use crate::{
        agents::SELF_USER_ID,
        space::AppState,
        testkit::{
            app_state_core, create_loaded_space, models_with_completer,
            models_with_configured_completer,
        },
        types::{FormationInput, InputContext, MaintenanceInput, MaintenanceScope},
    };
    use anda_core::{
        Agent, AgentContext, AgentOutput, BoxError, BoxPinFut, CompletionRequest, ContentPart,
        Message, ToolCall, ToolInput, Usage,
    };
    use anda_engine::{
        context::{AgentCtx, COMPACTION_PROMPT},
        memory::{Conversation, ConversationRef, ConversationStatus},
        model::{CompletionFeaturesDyn, Models},
        unix_ms,
    };
    use serde_json::json;
    use std::sync::Mutex;
    use std::sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    };
    use tokio::time::{Duration, sleep};

    #[derive(Debug)]
    struct SuccessCompleter;

    impl CompletionFeaturesDyn for SuccessCompleter {
        fn model_name(&self) -> String {
            "success-test-model".to_string()
        }

        fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            Box::pin(async move {
                Ok(AgentOutput {
                    content: "formation done".to_string(),
                    chat_history: vec![Message {
                        role: "assistant".to_string(),
                        content: vec![format!("processed: {}", req.prompt).into()],
                        ..Default::default()
                    }],
                    ..Default::default()
                })
            })
        }
    }

    #[derive(Debug)]
    struct FailedReasonCompleter;

    impl CompletionFeaturesDyn for FailedReasonCompleter {
        fn model_name(&self) -> String {
            "failed-reason-test-model".to_string()
        }

        fn completion(&self, _req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            Box::pin(async move {
                Ok(AgentOutput {
                    failed_reason: Some("formation failed".to_string()),
                    chat_history: vec![Message {
                        role: "assistant".to_string(),
                        content: vec!["formation failure".to_string().into()],
                        ..Default::default()
                    }],
                    ..Default::default()
                })
            })
        }
    }

    #[derive(Debug)]
    struct RetryCompleter {
        calls: Arc<AtomicU64>,
    }

    impl CompletionFeaturesDyn for RetryCompleter {
        fn model_name(&self) -> String {
            "retry-test-model".to_string()
        }

        fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            let calls = self.calls.clone();
            Box::pin(async move {
                let call = calls.fetch_add(1, Ordering::SeqCst);
                if call == 0 {
                    Ok(AgentOutput {
                        failed_reason: Some("transient formation failure".to_string()),
                        chat_history: vec![Message {
                            role: "assistant".to_string(),
                            content: vec!["retry later".to_string().into()],
                            ..Default::default()
                        }],
                        ..Default::default()
                    })
                } else {
                    Ok(AgentOutput {
                        content: "formation retried".to_string(),
                        chat_history: vec![Message {
                            role: "assistant".to_string(),
                            content: vec![format!("recovered: {}", req.prompt).into()],
                            ..Default::default()
                        }],
                        ..Default::default()
                    })
                }
            })
        }
    }

    #[derive(Debug)]
    struct ErrorCompleter;

    impl CompletionFeaturesDyn for ErrorCompleter {
        fn model_name(&self) -> String {
            "error-test-model".to_string()
        }

        fn completion(&self, _req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            Box::pin(async move { Err("model error".into()) })
        }
    }

    /// Emits an endless stream of tool calls (a non-converging model), and a
    /// summary for compaction handoff requests so the runner keeps looping.
    #[derive(Debug)]
    struct ToolLoopCompleter;

    impl CompletionFeaturesDyn for ToolLoopCompleter {
        fn model_name(&self) -> String {
            "formation-tool-loop-test-model".to_string()
        }

        fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            Box::pin(async move {
                let usage = Usage {
                    input_tokens: 10,
                    output_tokens: 1,
                    requests: 1,
                    ..Default::default()
                };
                if req.tools.is_empty() {
                    // Compaction handoff turn: tools are cleared for the
                    // summarization request.
                    return Ok(AgentOutput {
                        content: "handoff summary".to_string(),
                        usage,
                        ..Default::default()
                    });
                }
                Ok(AgentOutput {
                    tool_calls: vec![ToolCall {
                        name: "execute_kip".to_string(),
                        // A command the engine refuses, so the tool answers with
                        // an error and the model is asked again: the point of
                        // this fixture is a loop that never converges.
                        args: serde_json::json!({"command": "NOT A VALID KIP COMMAND"}),
                        result: None,
                        call_id: Some("loop".to_string()),
                        remote_id: None,
                    }],
                    usage,
                    ..Default::default()
                })
            })
        }
    }

    /// Emits `tool_turns` tool-call turns, then a final content turn.
    #[derive(Debug)]
    struct CountedToolThenDoneCompleter {
        calls: Arc<AtomicU64>,
        tool_turns: u64,
    }

    impl CompletionFeaturesDyn for CountedToolThenDoneCompleter {
        fn model_name(&self) -> String {
            "formation-counted-tool-test-model".to_string()
        }

        fn completion(&self, _req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            let calls = self.calls.clone();
            let tool_turns = self.tool_turns;
            Box::pin(async move {
                let call = calls.fetch_add(1, Ordering::SeqCst);
                let usage = Usage {
                    input_tokens: 10,
                    output_tokens: 1,
                    requests: 1,
                    ..Default::default()
                };
                if call < tool_turns {
                    return Ok(AgentOutput {
                        tool_calls: vec![ToolCall {
                            name: "execute_kip".to_string(),
                            args: serde_json::json!({"command": "DESCRIBE PRIMER"}),
                            result: None,
                            call_id: Some(format!("call-{call}")),
                            remote_id: None,
                        }],
                        usage,
                        ..Default::default()
                    });
                }
                Ok(AgentOutput {
                    content: "formation done".to_string(),
                    chat_history: vec![Message {
                        role: "assistant".to_string(),
                        content: vec!["formation done".to_string().into()],
                        ..Default::default()
                    }],
                    usage,
                    ..Default::default()
                })
            })
        }
    }

    #[derive(Debug)]
    struct SlowCompleter;

    impl CompletionFeaturesDyn for SlowCompleter {
        fn model_name(&self) -> String {
            "slow-test-model".to_string()
        }

        fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            Box::pin(async move {
                sleep(Duration::from_millis(150)).await;
                Ok(AgentOutput {
                    content: "done".to_string(),
                    chat_history: vec![Message {
                        role: "assistant".to_string(),
                        content: vec![format!("processed: {}", req.prompt).into()],
                        ..Default::default()
                    }],
                    ..Default::default()
                })
            })
        }
    }

    /// Models provider history around a real write and a review readback, so
    /// removing tool receipts cannot silently turn the review into guesswork.
    #[derive(Debug)]
    struct ReviewCompleter {
        requests: Arc<Mutex<Vec<CompletionRequest>>>,
        fail_on_call: Option<usize>,
    }

    impl CompletionFeaturesDyn for ReviewCompleter {
        fn model_name(&self) -> String {
            "formation-review-test-model".into()
        }

        fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            let call = {
                let mut requests = self.requests.lock().unwrap();
                let call = requests.len();
                requests.push(req.clone());
                call
            };
            let fail = self.fail_on_call == Some(call);
            Box::pin(async move {
                let usage = Usage {
                    input_tokens: 10,
                    output_tokens: 1,
                    requests: 1,
                    ..Default::default()
                };
                if fail {
                    return Ok(AgentOutput {
                        failed_reason: Some("review fixture failure".into()),
                        usage,
                        ..Default::default()
                    });
                }

                let command = if call == 0 {
                    Some(
                        r#"CREATE ACTIVITY ?receipt {
                        SET FIELDS {activity_class: "extraction", status: "completed"}
                        SET STRUCTURAL {("inputs", :msg1)}
                    }"#
                        .to_string(),
                    )
                } else if request_text(&req).contains(super::REVIEW_INSTRUCTIONS) {
                    let evidence_id = req
                        .raw_history
                        .iter()
                        .filter_map(|item| item["content"].as_str())
                        .filter_map(|text| serde_json::from_str::<serde_json::Value>(text).ok())
                        .find_map(|receipt| {
                            receipt["results"][0]["result"]["changes"]
                                .as_array()?
                                .iter()
                                .filter_map(|change| change["id"].as_str())
                                .find(|id| id.starts_with("E-"))
                                .map(str::to_string)
                        })
                        .expect("review needs the preserved write receipt's Evidence id");
                    Some(format!(
                        "FIND(?e) WHERE {{ ?e EVIDENCE {{id: \"{evidence_id}\"}} }} LIMIT 1"
                    ))
                } else {
                    None
                };
                let tool_calls: Vec<ToolCall> = command
                    .map(|command| ToolCall {
                        name: "execute_kip".into(),
                        args: json!({"command": command}),
                        call_id: Some(format!("review-{call}")),
                        result: None,
                        remote_id: None,
                    })
                    .into_iter()
                    .collect();
                let content = if call < 2 {
                    "formation done"
                } else {
                    "review done"
                };
                let mut chat_history = Vec::new();
                let mut raw_history = Vec::new();
                if !req.prompt.is_empty() {
                    chat_history.push(Message {
                        role: "user".into(),
                        content: vec![req.prompt.clone().into()],
                        ..Default::default()
                    });
                    raw_history.push(json!({"role": "user", "content": req.prompt}));
                }
                for part in &req.content {
                    if let ContentPart::ToolOutput {
                        output, call_id, ..
                    } = part
                    {
                        raw_history.push(json!({
                            "role": "tool", "tool_call_id": call_id,
                            "content": output.to_string()
                        }));
                    }
                }
                if !req.content.is_empty() {
                    chat_history.push(Message {
                        role: req.role.clone().unwrap_or_else(|| "tool".into()),
                        content: req.content,
                        ..Default::default()
                    });
                }
                let assistant = Message {
                    role: "assistant".into(),
                    content: if tool_calls.is_empty() {
                        vec![content.to_string().into()]
                    } else {
                        tool_calls
                            .iter()
                            .map(|tool| ContentPart::ToolCall {
                                name: tool.name.clone(),
                                args: tool.args.clone(),
                                call_id: tool.call_id.clone(),
                            })
                            .collect()
                    },
                    ..Default::default()
                };
                raw_history.push(if let Some(tool) = tool_calls.first() {
                    json!({"role": "assistant", "tool_calls": [{
                        "id": tool.call_id, "type": "function",
                        "function": {"name": tool.name, "arguments": tool.args.to_string()}
                    }]})
                } else {
                    json!({"role": "assistant", "content": content})
                });
                chat_history.push(assistant);
                Ok(AgentOutput {
                    content: content.into(),
                    tool_calls,
                    chat_history,
                    raw_history,
                    usage,
                    ..Default::default()
                })
            })
        }
    }

    #[derive(Debug)]
    struct CompactionCompleter {
        requests: Arc<Mutex<Vec<String>>>,
    }

    impl CompletionFeaturesDyn for CompactionCompleter {
        fn model_name(&self) -> String {
            "formation-compaction-test-model".to_string()
        }

        fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            let requests = self.requests.clone();
            Box::pin(async move {
                let text = request_text(&req);
                requests.lock().unwrap().push(text.clone());
                if text.contains(COMPACTION_PROMPT.trim()) {
                    return Ok(AgentOutput {
                        content: "handoff summary".to_string(),
                        chat_history: vec![Message {
                            role: "assistant".to_string(),
                            content: vec!["summary turn".to_string().into()],
                            ..Default::default()
                        }],
                        usage: Usage {
                            input_tokens: 8,
                            output_tokens: 2,
                            requests: 1,
                            ..Default::default()
                        },
                        ..Default::default()
                    });
                }

                if text.contains("handoff summary") {
                    return Ok(AgentOutput {
                        content: "review complete".to_string(),
                        chat_history: vec![Message {
                            role: "assistant".to_string(),
                            content: vec!["reviewed after compaction".to_string().into()],
                            ..Default::default()
                        }],
                        usage: Usage {
                            input_tokens: 16,
                            output_tokens: 4,
                            requests: 1,
                            ..Default::default()
                        },
                        ..Default::default()
                    });
                }

                Ok(AgentOutput {
                    content: "formation draft".to_string(),
                    chat_history: vec![Message {
                        role: "assistant".to_string(),
                        content: vec!["draft before compaction".to_string().into()],
                        ..Default::default()
                    }],
                    usage: Usage {
                        input_tokens: 900,
                        output_tokens: 4,
                        requests: 1,
                        ..Default::default()
                    },
                    ..Default::default()
                })
            })
        }
    }

    fn part_text(part: &ContentPart) -> Option<String> {
        match part {
            ContentPart::Text { text } | ContentPart::Reasoning { text } => Some(text.clone()),
            ContentPart::ToolOutput { output, .. } | ContentPart::ToolCall { args: output, .. } => {
                Some(output.to_string())
            }
            _ => None,
        }
    }

    fn request_text(req: &CompletionRequest) -> String {
        let mut text = Vec::new();
        if !req.prompt.is_empty() {
            text.push(req.prompt.clone());
        }
        text.extend(req.content.iter().filter_map(part_text));
        for message in &req.chat_history {
            text.extend(message.content.iter().filter_map(part_text));
        }
        text.join("\n")
    }

    fn test_app_state(name: &str) -> AppState {
        app_state_core(name, Arc::new(Models::default()), vec![], "test", 0)
    }

    /// Saves one note through the registered, product-gated note tool.
    async fn save_note(ctx: &AgentCtx, id: &str, content: &str) {
        let (output, _) = ctx
            .tool_call(ToolInput {
                name: "note".into(),
                args: json!({"op": "upsert", "items": [{"id": id, "content": content}]}),
                resources: vec![],
                meta: None,
            })
            .await
            .unwrap();
        assert_ne!(output.is_error, Some(true), "{:?}", output.output);
    }

    fn test_app_state_with_completer<C>(name: &str, completer: C) -> AppState
    where
        C: CompletionFeaturesDyn,
    {
        app_state_core(name, models_with_completer(completer), vec![], "test", 0)
    }

    fn formation_prompt(counterparty: Option<&str>) -> String {
        formation_prompt_with_text("remember this preference", counterparty)
    }

    fn formation_prompt_with_text(text: &str, counterparty: Option<&str>) -> String {
        serde_json::to_string(&FormationInput {
            messages: vec![Message {
                role: "user".to_string(),
                content: vec![text.to_string().into()],
                ..Default::default()
            }],
            context: counterparty.map(|counterparty| InputContext {
                counterparty: Some(counterparty.to_string()),
                ..Default::default()
            }),
            timestamp: None,
        })
        .unwrap()
    }

    #[derive(Debug, Default)]
    struct EvidenceCompleter {
        calls: AtomicU64,
        results: Arc<Mutex<Vec<serde_json::Value>>>,
    }

    impl CompletionFeaturesDyn for EvidenceCompleter {
        fn model_name(&self) -> String {
            "formation-evidence-regression".into()
        }

        fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            let write = self.calls.fetch_add(1, Ordering::SeqCst).is_multiple_of(2);
            let results = self.results.clone();
            Box::pin(async move {
                if write {
                    return Ok(AgentOutput {
                        tool_calls: vec![ToolCall {
                            name: "execute_kip".into(),
                            args: json!({"command": r#"CREATE ACTIVITY ?receipt {
                                SET FIELDS {activity_class: "extraction", status: "completed"}
                                SET STRUCTURAL {("inputs", :msg1)}
                            }"#}),
                            result: None,
                            call_id: Some("capture".into()),
                            remote_id: None,
                        }],
                        ..Default::default()
                    });
                }
                for part in req.content {
                    if let ContentPart::ToolOutput { output, .. } = part {
                        results.lock().unwrap().push(output);
                    }
                }
                Ok(AgentOutput {
                    content: "captured".into(),
                    ..Default::default()
                })
            })
        }
    }

    #[tokio::test]
    async fn formation_captures_compatible_timestamps_and_raw_text_with_stable_retry_evidence() {
        let received_at = 1_789_862_400_123;
        let said = "  Keep this original text.\n原文不变。  ";
        for (index, timestamp, expected, raw) in [
            (
                0,
                Some("2026-09-20T00:00:00Z"),
                "2026-09-20T00:00:00.000Z".to_string(),
                false,
            ),
            (
                1,
                Some(" 2026-09-20T08:00:00.123456+08:00 "),
                "2026-09-20T00:00:00.123Z".to_string(),
                false,
            ),
            (
                2,
                Some("not a timestamp"),
                crate::kip::timestamp(received_at),
                false,
            ),
            (3, None, crate::kip::timestamp(received_at), false),
            (4, None, crate::kip::timestamp(received_at), true),
        ] {
            let model = EvidenceCompleter::default();
            let results = model.results.clone();
            let name = format!("formation_capture_{index}");
            let app = test_app_state_with_completer(&name, model);
            let space = create_loaded_space(&app, &name).await;
            let prompt = if raw {
                said.to_string()
            } else {
                serde_json::to_string(&FormationInput {
                    messages: vec![Message {
                        role: "user".into(),
                        content: vec![said.to_string().into()],
                        ..Default::default()
                    }],
                    context: None,
                    timestamp: timestamp.map(str::to_string),
                })
                .unwrap()
            };
            let mut original = stored_conversation(
                &space,
                vec![json!(Message {
                    role: "user".into(),
                    content: vec![prompt.into()],
                    ..Default::default()
                })],
            )
            .await;
            original.created_at = received_at;
            let ctx = space
                .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
                .unwrap();
            for _ in 0..2 {
                let mut conversation = original.clone();
                space.formation.process_one(&ctx, &mut conversation).await;
                assert_eq!(conversation.status, ConversationStatus::Completed);
            }
            let results = results.lock().unwrap().clone();
            assert_eq!(results.len(), 2);
            assert!(
                results.iter().all(|r| r["status"] == "succeeded"),
                "{results:?}"
            );
            let evidence = space
                .memory
                .query("FIND(?e) WHERE {?e EVIDENCE {}} LIMIT 10", None)
                .await
                .unwrap();
            let rows = evidence.as_array().unwrap();
            assert_eq!(rows.len(), 1, "a retry must retain the original Evidence");
            assert_eq!(rows[0]["observed_at"], expected);
            assert_eq!(rows[0]["payload"]["inline"]["content"][0]["text"], said);
            space.close().await.unwrap();
        }
    }

    #[tokio::test]
    async fn counterparty_lookup_preserves_display_name_and_explicit_updates_still_work() {
        let app = test_app_state("counterparty_name");
        let space = create_loaded_space(&app, "counterparty_name").await;
        let agent = &space.formation;
        let initial = agent
            .get_or_init_counterparty("alice".into(), Some("Alice Smith".into()))
            .await
            .unwrap();
        let found = agent
            .get_or_init_counterparty("alice".into(), None)
            .await
            .unwrap();
        assert_eq!(found, initial, "lookup must not mutate the existing Person");
        let renamed = agent
            .get_or_init_counterparty("alice".into(), Some("Alice Jones".into()))
            .await
            .unwrap();
        assert_eq!(renamed["id"], initial["id"]);
        assert_eq!(renamed["name"], "Alice Jones");
        let (a, b) = tokio::join!(
            agent.get_or_init_counterparty("new_person".into(), None),
            agent.get_or_init_counterparty("new_person".into(), None),
        );
        assert_eq!(a.unwrap()["id"], b.unwrap()["id"]);
        space.close().await.unwrap();
    }

    async fn stored_conversation(
        space: &crate::space::Space,
        messages: Vec<serde_json::Value>,
    ) -> Conversation {
        let now = unix_ms();
        let mut conversation = Conversation {
            user: SELF_USER_ID,
            status: ConversationStatus::Submitted,
            messages,
            label: Some("formation".to_string()),
            created_at: now,
            updated_at: now,
            ..Default::default()
        };
        let id = space
            .memory
            .add_conversation(ConversationRef::from(&conversation))
            .await
            .unwrap();
        conversation._id = id;
        conversation
    }

    #[test]
    fn processing_guard_resets_conversation_id_on_drop() {
        let processing = Arc::new(AtomicU64::new(42));

        {
            let _guard = ProcessingGuard(Some(processing.clone()));
            assert_eq!(processing.load(Ordering::SeqCst), 42);
        }

        assert_eq!(processing.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn formation_agent_name_matches_registered_agent_name() {
        assert_eq!(FormationAgent::NAME, "formation_memory");
    }

    #[tokio::test]
    async fn formation_agent_trait_metadata_matches_runtime_registration() {
        let app = test_app_state("formation_trait_metadata");
        let space = create_loaded_space(&app, "formation_trait_metadata").await;

        assert_eq!(
            Agent::<AgentCtx>::name(space.formation.as_ref()),
            FormationAgent::NAME
        );
        assert!(
            Agent::<AgentCtx>::description(space.formation.as_ref()).contains("structured memory")
        );
        let tools = Agent::<AgentCtx>::tool_dependencies(space.formation.as_ref());
        assert!(tools.iter().any(|name| name == "execute_kip"));
        assert!(tools.iter().any(|name| name == "kip_reference"));
        assert!(tools.iter().any(|name| name == "note"));
    }

    #[tokio::test]
    async fn find_next_submitted_skips_terminal_and_non_formation_conversations() {
        let app = test_app_state("formation_find_next");
        let space = create_loaded_space(&app, "formation_find_next").await;
        let now = unix_ms();

        for conversation in [
            Conversation {
                user: SELF_USER_ID,
                status: ConversationStatus::Completed,
                label: Some("formation".to_string()),
                created_at: now,
                updated_at: now,
                ..Default::default()
            },
            Conversation {
                user: SELF_USER_ID,
                status: ConversationStatus::Submitted,
                label: Some("recall".to_string()),
                created_at: now + 1,
                updated_at: now + 1,
                ..Default::default()
            },
            Conversation {
                user: SELF_USER_ID,
                status: ConversationStatus::Cancelled,
                label: Some("formation".to_string()),
                created_at: now + 2,
                updated_at: now + 2,
                ..Default::default()
            },
        ] {
            space
                .memory
                .add_conversation(ConversationRef::from(&conversation))
                .await
                .unwrap();
        }

        let pending = Conversation {
            user: SELF_USER_ID,
            status: ConversationStatus::Submitted,
            label: Some("formation".to_string()),
            created_at: now + 3,
            updated_at: now + 3,
            ..Default::default()
        };
        let pending_id = space
            .memory
            .add_conversation(ConversationRef::from(&pending))
            .await
            .unwrap();

        let found = space
            .formation
            .find_next_submitted(0)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(found._id, pending_id);
        assert!(
            space
                .formation
                .find_next_submitted(pending_id)
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn mark_conversation_failed_persists_status_and_reason() {
        let app = test_app_state("formation_mark_failed");
        let space = create_loaded_space(&app, "formation_mark_failed").await;
        let now = unix_ms();
        let mut conversation = Conversation {
            user: SELF_USER_ID,
            status: ConversationStatus::Submitted,
            label: Some("formation".to_string()),
            created_at: now,
            updated_at: now,
            ..Default::default()
        };
        let id = space
            .memory
            .add_conversation(ConversationRef::from(&conversation))
            .await
            .unwrap();
        conversation._id = id;

        space
            .formation
            .mark_conversation_failed(&mut conversation, "boom".to_string())
            .await;

        assert_eq!(conversation.status, ConversationStatus::Failed);
        assert_eq!(conversation.failed_reason.as_deref(), Some("boom"));
        let stored = space.memory.get_conversation(id).await.unwrap();
        assert_eq!(stored.status, ConversationStatus::Failed);
        assert_eq!(stored.failed_reason.as_deref(), Some("boom"));
    }

    #[tokio::test]
    async fn start_process_rejects_busy_and_maintenance_states() {
        let app = test_app_state("formation_start_guards");
        let space = create_loaded_space(&app, "formation_start_guards").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();

        space
            .formation
            .processing_conversation
            .store(42, Ordering::SeqCst);
        let err = space
            .formation
            .start_process(ctx.clone(), 1)
            .await
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("already processing conversation 42")
        );
        space
            .formation
            .processing_conversation
            .store(0, Ordering::SeqCst);

        let app = test_app_state_with_completer("formation_maintenance_guard", SlowCompleter);
        let space = create_loaded_space(&app, "formation_maintenance_guard").await;
        let maintenance = space
            .maintenance(
                SELF_USER_ID,
                MaintenanceInput {
                    scope: MaintenanceScope::Quick,
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert!(maintenance.conversation.is_some());

        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let err = space.formation.start_process(ctx, 1).await.unwrap_err();
        assert!(err.to_string().contains("MaintenanceAgent is processing"));

        for _ in 0..100 {
            if !space.is_processing() {
                return;
            }
            sleep(Duration::from_millis(10)).await;
        }
        panic!("maintenance did not finish");
    }

    #[tokio::test]
    async fn start_process_finds_pending_conversation_and_dispatches_worker() {
        let app = test_app_state_with_completer("formation_start_success", SuccessCompleter);
        let space = create_loaded_space(&app, "formation_start_success").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let pending = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;

        space
            .formation
            .start_process(ctx, pending._id)
            .await
            .unwrap();
        for _ in 0..100 {
            if !space.formation.is_processing() {
                break;
            }
            sleep(Duration::from_millis(10)).await;
        }

        assert_eq!(space.formation.get_processed(), Some(pending._id));
        assert_eq!(
            space
                .memory
                .get_conversation(pending._id)
                .await
                .unwrap()
                .status,
            ConversationStatus::Completed
        );
    }

    #[tokio::test]
    async fn run_queues_while_maintenance_runs_and_resumes_from_processed_gap() {
        let app = test_app_state_with_completer("formation_run_resume_gap", SuccessCompleter);
        let space = create_loaded_space(&app, "formation_run_resume_gap").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        space
            .conversations
            .save_extension("brain_processed".to_string(), 0_u64.into())
            .await
            .unwrap();
        let missed = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;

        let output = Agent::<AgentCtx>::run(
            space.formation.as_ref(),
            ctx,
            formation_prompt(Some("resume-gap-user")),
            vec![],
        )
        .await
        .unwrap();
        let queued_id = output.conversation.unwrap();

        for _ in 0..100 {
            if !space.formation.is_processing() {
                break;
            }
            sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(space.formation.get_processed(), Some(queued_id));
        assert_eq!(
            space
                .memory
                .get_conversation(missed._id)
                .await
                .unwrap()
                .status,
            ConversationStatus::Completed
        );

        let app = test_app_state_with_completer("formation_run_maintenance_queue", SlowCompleter);
        let space = create_loaded_space(&app, "formation_run_maintenance_queue").await;
        let maintenance = space
            .maintenance(
                SELF_USER_ID,
                MaintenanceInput {
                    scope: MaintenanceScope::Quick,
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert!(maintenance.conversation.is_some());
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let output = Agent::<AgentCtx>::run(
            space.formation.as_ref(),
            ctx,
            formation_prompt(None),
            vec![],
        )
        .await
        .unwrap();
        assert!(output.conversation.is_some());
        assert!(!space.formation.is_processing());

        for _ in 0..100 {
            if !space.is_processing() {
                return;
            }
            sleep(Duration::from_millis(10)).await;
        }
        panic!("maintenance did not finish");
    }

    #[tokio::test]
    async fn try_process_returns_when_another_conversation_owns_the_guard() {
        let app = test_app_state("formation_try_process_guard");
        let space = create_loaded_space(&app, "formation_try_process_guard").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let conversation = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;

        space
            .formation
            .processing_conversation
            .store(conversation._id + 10, Ordering::SeqCst);
        space.formation.try_process(ctx, conversation.clone());

        assert_eq!(
            space
                .formation
                .processing_conversation
                .load(Ordering::SeqCst),
            conversation._id + 10
        );
    }

    #[tokio::test]
    async fn process_one_marks_missing_prompt_and_completion_errors() {
        let app = test_app_state("formation_no_prompt");
        let space = create_loaded_space(&app, "formation_no_prompt").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let mut no_prompt = stored_conversation(&space, vec![]).await;

        space.formation.process_one(&ctx, &mut no_prompt).await;

        assert_eq!(no_prompt.status, ConversationStatus::Failed);
        assert_eq!(no_prompt.failed_reason.as_deref(), Some("No prompt found"));

        let app = test_app_state_with_completer("formation_model_error", ErrorCompleter);
        let space = create_loaded_space(&app, "formation_model_error").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let mut conversation = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(Some("counterparty-error")).into()],
                ..Default::default()
            })],
        )
        .await;

        space.formation.process_one(&ctx, &mut conversation).await;

        assert_eq!(conversation.status, ConversationStatus::Failed);
        assert!(
            conversation
                .failed_reason
                .as_deref()
                .unwrap_or_default()
                .contains("CompletionRunner error")
        );
    }

    #[tokio::test]
    async fn process_one_persists_model_failed_reason() {
        let app = test_app_state_with_completer("formation_failed_reason", FailedReasonCompleter);
        let space = create_loaded_space(&app, "formation_failed_reason").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let mut conversation = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;

        space.formation.process_one(&ctx, &mut conversation).await;

        assert_eq!(conversation.status, ConversationStatus::Failed);
        assert_eq!(
            conversation.failed_reason.as_deref(),
            Some("formation failed")
        );
        let stored = space
            .memory
            .get_conversation(conversation._id)
            .await
            .unwrap();
        assert_eq!(stored.status, ConversationStatus::Failed);
        assert_eq!(stored.failed_reason.as_deref(), Some("formation failed"));
    }

    #[tokio::test]
    async fn process_one_fails_tool_loop_at_model_turn_limit() {
        let app = test_app_state_with_completer("formation_turn_limit", ToolLoopCompleter);
        let space = create_loaded_space(&app, "formation_turn_limit").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let mut conversation = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;

        space.formation.process_one(&ctx, &mut conversation).await;

        assert_eq!(conversation.status, ConversationStatus::Failed);
        assert!(
            conversation
                .failed_reason
                .as_deref()
                .unwrap_or_default()
                .contains(&format!(
                    "exceeded model turn limit of {}",
                    super::FORMATION_MAX_MODEL_TURNS
                )),
            "failed_reason: {:?}",
            conversation.failed_reason
        );
        assert_eq!(
            stored_status(&space, conversation._id).await,
            ConversationStatus::Failed
        );
    }

    /// The persisted status of one conversation, allowing the write to become
    /// visible.
    ///
    /// A conversation this long is rewritten on every throttled snapshot, and a
    /// read issued in the same instant as the final write can still see the
    /// previous one. The assertion is about what the agent persisted, not about
    /// how fast the store settles.
    async fn stored_status(space: &crate::space::Space, id: u64) -> ConversationStatus {
        for _ in 0..50 {
            let stored = space.memory.get_conversation(id).await.unwrap();
            if stored.status != ConversationStatus::Working {
                return stored.status;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        space.memory.get_conversation(id).await.unwrap().status
    }

    #[tokio::test]
    async fn process_one_throttles_intermediate_persistence_until_terminal() {
        let app = test_app_state_with_completer(
            "formation_persist_throttle",
            CountedToolThenDoneCompleter {
                calls: Arc::new(AtomicU64::new(0)),
                // Fewer working turns than PERSIST_EVERY_N_TURNS, so only the
                // terminal turn triggers a write.
                tool_turns: 3,
            },
        );
        let space = create_loaded_space(&app, "formation_persist_throttle").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let mut conversation = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;

        let updates_before = space.conversations.stats().update_count;
        space.formation.process_one(&ctx, &mut conversation).await;
        let updates_after = space.conversations.stats().update_count;

        assert_eq!(conversation.status, ConversationStatus::Completed);
        // 4 model turns total: 3 intermediate Working turns are throttled and
        // only the terminal Completed turn is written.
        assert_eq!(updates_after - updates_before, 1);
        let stored = space
            .memory
            .get_conversation(conversation._id)
            .await
            .unwrap();
        assert_eq!(stored.status, ConversationStatus::Completed);
        // The terminal write carries the full accumulated usage (4 model
        // turns x 10 input tokens; `requests` also counts tool executions),
        // so throttled turns are not lost from the stored snapshot.
        assert_eq!(stored.usage.input_tokens, 40);
    }

    #[tokio::test]
    async fn run_rejects_oversized_formation_input_before_persisting() {
        let app = test_app_state("formation_input_too_large");
        let space = create_loaded_space(&app, "formation_input_too_large").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let prompt = "x ".repeat(1_000_000);

        let err = Agent::<AgentCtx>::run(space.formation.as_ref(), ctx, prompt, vec![])
            .await
            .unwrap_err();

        assert!(err.to_string().contains("Input too large"));
        assert_eq!(space.conversations.len(), 0);
    }

    #[tokio::test]
    async fn process_loop_processes_submitted_formation_queue_sequentially() {
        let app = test_app_state_with_completer("formation_process_loop_queue", SuccessCompleter);
        let space = create_loaded_space(&app, "formation_process_loop_queue").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let first = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;
        let second = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(Some("queue-user")).into()],
                ..Default::default()
            })],
        )
        .await;

        space
            .formation
            .processing_conversation
            .store(first._id, Ordering::SeqCst);
        space.formation.process_loop(ctx, first).await;

        assert_eq!(
            space
                .formation
                .processing_conversation
                .load(Ordering::SeqCst),
            0
        );
        assert_eq!(space.formation.get_processed(), Some(second._id));
        assert_eq!(
            space
                .memory
                .get_conversation(second._id)
                .await
                .unwrap()
                .status,
            ConversationStatus::Completed
        );
    }

    #[tokio::test(start_paused = true)]
    async fn process_loop_retries_failed_conversation_once_and_clears_failure_reason() {
        let calls = Arc::new(AtomicU64::new(0));
        let app = test_app_state_with_completer(
            "formation_process_loop_retry",
            RetryCompleter {
                calls: calls.clone(),
            },
        );
        let space = create_loaded_space(&app, "formation_process_loop_retry").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let pending = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;

        space
            .formation
            .processing_conversation
            .store(pending._id, Ordering::SeqCst);
        space.formation.process_loop(ctx, pending.clone()).await;

        assert_eq!(calls.load(Ordering::SeqCst), 2);
        assert_eq!(
            space
                .formation
                .processing_conversation
                .load(Ordering::SeqCst),
            0
        );
        assert_eq!(space.formation.get_processed(), Some(pending._id));
        let stored = space.memory.get_conversation(pending._id).await.unwrap();
        assert_eq!(stored.status, ConversationStatus::Completed);
        assert_eq!(stored.failed_reason, None);
    }

    /// Fails every pass whose input mentions "poison" and completes the rest.
    #[derive(Debug)]
    struct PoisonCompleter {
        calls: Arc<AtomicU64>,
    }

    impl CompletionFeaturesDyn for PoisonCompleter {
        fn model_name(&self) -> String {
            "poison-test-model".to_string()
        }

        fn completion(&self, req: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            let poisoned = req.prompt.contains("poison pill");
            Box::pin(async move {
                Ok(AgentOutput {
                    content: if poisoned { "" } else { "formation done" }.to_string(),
                    failed_reason: poisoned.then(|| "provider refused the input".to_string()),
                    // Like a provider, the history returned opens with the
                    // input, which a retry reads its prompt from.
                    chat_history: vec![
                        Message {
                            role: "user".to_string(),
                            content: vec![req.prompt.into()],
                            ..Default::default()
                        },
                        Message {
                            role: "assistant".to_string(),
                            content: vec!["done".to_string().into()],
                            ..Default::default()
                        },
                    ],
                    ..Default::default()
                })
            })
        }
    }

    #[tokio::test(start_paused = true)]
    async fn a_conversation_that_keeps_failing_stops_blocking_the_queue() {
        let calls = Arc::new(AtomicU64::new(0));
        let app = test_app_state_with_completer(
            "formation_poison",
            PoisonCompleter {
                calls: calls.clone(),
            },
        );
        let space = create_loaded_space(&app, "formation_poison").await;
        let input = |text: &str| {
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt_with_text(text, None).into()],
                ..Default::default()
            })]
        };
        let poison = stored_conversation(&space, input("poison pill")).await;
        let next = stored_conversation(&space, input("remember this preference")).await;
        let run = |conversation: Conversation| {
            let space = space.clone();
            async move {
                let ctx = space
                    .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
                    .unwrap();
                space
                    .formation
                    .processing_conversation
                    .store(conversation._id, Ordering::SeqCst);
                space.formation.process_loop(ctx, conversation).await;
                space.memory.get_conversation(poison._id).await.unwrap()
            }
        };

        // A failed round stays retryable, and the queue waits behind it.
        let mut stored = run(poison.clone()).await;
        assert_eq!(stored.status, ConversationStatus::Failed);
        assert_eq!(
            stored.extra.as_ref().unwrap()[super::FAILED_ROUNDS_KEY]["rounds"],
            1
        );
        assert_eq!(space.formation.get_processed(), None);

        // Enough rounds inside a short outage are still retried.
        stored.extra.as_mut().unwrap()[super::FAILED_ROUNDS_KEY]["rounds"] =
            json!(super::MAX_FAILED_ROUNDS - 1);
        let mut stored = run(stored).await;
        assert_eq!(stored.status, ConversationStatus::Failed);
        assert_eq!(
            space
                .memory
                .get_conversation(next._id)
                .await
                .unwrap()
                .status,
            ConversationStatus::Submitted
        );

        // Rounds spanning the give-up window cancel it, and the queue moves on.
        stored.extra.as_mut().unwrap()[super::FAILED_ROUNDS_KEY]["first_failed_at"] = json!(1);
        let stored = run(stored).await;
        assert_eq!(stored.status, ConversationStatus::Cancelled);
        assert!(
            stored
                .failed_reason
                .as_deref()
                .unwrap()
                .starts_with("formation_failed: gave up after 4 failed rounds"),
            "{:?}",
            stored.failed_reason
        );
        assert_eq!(
            space
                .memory
                .get_conversation(next._id)
                .await
                .unwrap()
                .status,
            ConversationStatus::Completed
        );
        assert_eq!(space.formation.get_processed(), Some(next._id));
        assert_eq!(calls.load(Ordering::SeqCst), 7);
    }

    #[tokio::test]
    async fn process_loop_keeps_processed_marker_as_high_water_mark() {
        let app = test_app_state_with_completer("formation_marker_high_water", SuccessCompleter);
        let space = create_loaded_space(&app, "formation_marker_high_water").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let pending = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;
        space
            .conversations
            .save_extension("brain_processed".to_string(), 9_u64.into())
            .await
            .unwrap();

        space
            .formation
            .processing_conversation
            .store(pending._id, Ordering::SeqCst);
        space.formation.process_loop(ctx, pending.clone()).await;

        // Reprocessing an older conversation must not rewind the marker.
        assert_eq!(space.formation.get_processed(), Some(9));
        assert_eq!(
            space
                .memory
                .get_conversation(pending._id)
                .await
                .unwrap()
                .status,
            ConversationStatus::Completed
        );
    }

    #[tokio::test]
    async fn process_loop_triggers_scheduled_maintenance_at_threshold() {
        let app =
            test_app_state_with_completer("formation_process_loop_maintenance", SuccessCompleter);
        let space = create_loaded_space(&app, "formation_process_loop_maintenance").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();

        for _ in 0..20 {
            let completed = Conversation {
                user: SELF_USER_ID,
                status: ConversationStatus::Completed,
                label: Some("formation".to_string()),
                created_at: unix_ms(),
                updated_at: unix_ms(),
                ..Default::default()
            };
            space
                .memory
                .add_conversation(ConversationRef::from(&completed))
                .await
                .unwrap();
        }
        let pending = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt(None).into()],
                ..Default::default()
            })],
        )
        .await;
        assert_eq!(pending._id, 21);

        space
            .formation
            .processing_conversation
            .store(pending._id, Ordering::SeqCst);
        space.formation.process_loop(ctx, pending).await;

        assert_eq!(
            space
                .formation
                .processing_conversation
                .load(Ordering::SeqCst),
            0
        );
        for _ in 0..100 {
            if !space.is_processing() {
                break;
            }
            sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(space.maintenance_for_test().get_processed_at().daydream, 21);
    }

    #[tokio::test]
    async fn process_one_reviews_once_at_threshold_with_receipts_and_source_bindings() {
        for tokens in [
            super::REVIEW_MIN_INPUT_TOKENS - 1,
            super::REVIEW_MIN_INPUT_TOKENS,
        ] {
            let name = format!("formation_review_{tokens}");
            let requests = Arc::new(Mutex::new(Vec::new()));
            let app = test_app_state_with_completer(
                &name,
                ReviewCompleter {
                    requests: requests.clone(),
                    fail_on_call: None,
                },
            );
            let space = create_loaded_space(&app, &name).await;
            let ctx = space
                .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
                .unwrap();
            let prompt = "x".repeat(tokens * 4);
            assert_eq!(anda_core::estimate_tokens(&prompt), tokens);
            let mut conversation = stored_conversation(
                &space,
                vec![json!(Message {
                    role: "user".into(),
                    content: vec![prompt.clone().into()],
                    ..Default::default()
                })],
            )
            .await;

            space.formation.process_one(&ctx, &mut conversation).await;

            let expected_calls = if tokens >= super::REVIEW_MIN_INPUT_TOKENS {
                4
            } else {
                2
            };
            assert_eq!(conversation.status, ConversationStatus::Completed);
            assert_eq!(conversation.usage.input_tokens, expected_calls as u64 * 10);
            assert_eq!(space.formation.history.read().len(), 1);
            let requests = requests.lock().unwrap().clone();
            assert_eq!(requests.len(), expected_calls);
            let receipt = requests[1]
                .content
                .iter()
                .find_map(|part| match part {
                    ContentPart::ToolOutput { output, .. } => Some(output),
                    _ => None,
                })
                .unwrap();
            assert_eq!(receipt["status"], "succeeded");
            assert!(receipt["results"][0]["result"]["handles"]["receipt"].is_string());
            if expected_calls == 4 {
                assert_eq!(
                    request_text(&requests[2])
                        .matches(super::REVIEW_INSTRUCTIONS)
                        .count(),
                    1
                );
                assert!(
                    requests[2].raw_history.iter().any(|item| {
                        item["role"] == "tool"
                            && item["content"].as_str() == Some(receipt.to_string().as_str())
                    }),
                    "review must retain the actual write receipt"
                );
                assert!(
                    requests[2]
                        .raw_history
                        .iter()
                        .any(|item| item["content"] == prompt)
                );
                let readback = requests[3]
                    .content
                    .iter()
                    .find_map(|part| match part {
                        ContentPart::ToolOutput { output, .. } => Some(output),
                        _ => None,
                    })
                    .unwrap();
                assert_eq!(readback["status"], "succeeded", "{readback:#}");
                assert!(
                    readback["results"][0]["result"][0]["payload"]["inline"]["content"][0]["text"]
                        == prompt,
                    "source readback: {}",
                    readback.to_string().chars().take(2000).collect::<String>()
                );
                assert_eq!(
                    serde_json::to_string(&conversation.messages)
                        .unwrap()
                        .matches("Host review scope:")
                        .count(),
                    1
                );
            }
            let stored = space
                .memory
                .get_conversation(conversation._id)
                .await
                .unwrap();
            assert_eq!(stored.status, ConversationStatus::Completed);
            assert_eq!(json!(stored.usage), json!(conversation.usage));
            space.close().await.unwrap();
        }
    }

    #[tokio::test]
    async fn process_one_does_not_complete_a_failed_initial_or_review_pass() {
        for fail_on_call in [0, 2] {
            let name = format!("formation_review_failure_{fail_on_call}");
            let requests = Arc::new(Mutex::new(Vec::new()));
            let app = test_app_state_with_completer(
                &name,
                ReviewCompleter {
                    requests: requests.clone(),
                    fail_on_call: Some(fail_on_call),
                },
            );
            let space = create_loaded_space(&app, &name).await;
            let ctx = space
                .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
                .unwrap();
            let mut conversation = stored_conversation(
                &space,
                vec![json!(Message {
                    role: "user".into(),
                    content: vec!["x".repeat(40_000).into()],
                    ..Default::default()
                })],
            )
            .await;

            space.formation.process_one(&ctx, &mut conversation).await;

            assert_eq!(requests.lock().unwrap().len(), fail_on_call + 1);
            assert_eq!(conversation.status, ConversationStatus::Failed);
            assert_eq!(
                conversation.failed_reason.as_deref(),
                Some("review fixture failure")
            );
            assert_eq!(
                conversation.usage.input_tokens,
                (fail_on_call as u64 + 1) * 10
            );
            assert!(space.formation.history.read().is_empty());
            assert_eq!(
                stored_status(&space, conversation._id).await,
                ConversationStatus::Failed
            );
            space.close().await.unwrap();
        }
    }

    #[test]
    fn review_scope_identifies_the_actual_captured_message_window() {
        let prompt = super::review_prompt(42, 20);
        assert!(prompt.contains("formation conversation 42, 20 input messages"));
        assert!(prompt.contains(":msg1 through :msg16 refer to input messages 5 through 20"));
        assert!(super::review_prompt(43, 0).contains("No input-message Evidence bindings"));
    }

    #[tokio::test]
    async fn process_one_compacts_before_large_prompt_review_handoff() {
        let requests = Arc::new(Mutex::new(Vec::new()));
        let models = models_with_configured_completer(
            CompactionCompleter {
                requests: requests.clone(),
            },
            |model| model.context_window = 1000,
        );
        let app = app_state_core(
            "formation_compacts_before_review",
            models,
            vec![],
            "test",
            0,
        );
        let space = create_loaded_space(&app, "formation_compacts_before_review").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        save_note(&ctx, "draft", "COMPACTION_NOTE").await;
        // ~44k chars ≈ 11k estimated tokens, above the 10k-token review threshold
        let large_text = "x".repeat(44_000);
        let mut conversation = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".to_string(),
                content: vec![formation_prompt_with_text(&large_text, None).into()],
                ..Default::default()
            })],
        )
        .await;

        space.formation.process_one(&ctx, &mut conversation).await;

        assert_eq!(conversation.status, ConversationStatus::Completed);
        let requests = requests.lock().unwrap();
        assert_eq!(requests.len(), 3, "{requests:#?}");
        assert!(requests[1].contains(COMPACTION_PROMPT.trim()));
        assert!(requests[2].contains("handoff summary"));
        assert!(requests[2].contains(super::REVIEW_INSTRUCTIONS));
        assert!(requests[2].contains(&format!(
            "formation conversation {}, 1 input messages",
            conversation._id
        )));
        assert!(
            !requests[1].contains(super::REVIEW_INSTRUCTIONS),
            "queued review must survive rather than be folded into the handoff"
        );
        // The replacement runner loads its own note index, not a stale copy.
        assert!(requests[0].contains("COMPACTION_NOTE"));
        assert!(requests[2].contains("COMPACTION_NOTE"));

        let messages = serde_json::to_string(&conversation.messages).unwrap();
        assert!(messages.contains("draft before compaction"));
        assert!(messages.contains("handoff summary"));
        assert!(messages.contains("reviewed after compaction"));
        assert!(!messages.contains("Saved note index"));
    }

    #[tokio::test]
    async fn process_one_offers_a_bounded_note_index_instead_of_full_notes() {
        let requests = Arc::new(Mutex::new(Vec::new()));
        let app = test_app_state_with_completer(
            "formation_note_index",
            ReviewCompleter {
                requests: requests.clone(),
                fail_on_call: None,
            },
        );
        let space = create_loaded_space(&app, "formation_note_index").await;
        let ctx = space
            .ctx_for_test(SELF_USER_ID, FormationAgent::NAME)
            .unwrap();
        let note = format!("NOTE_HEAD {} NOTE_TAIL", "x".repeat(400));
        save_note(&ctx, "pending", &note).await;
        let mut conversation = stored_conversation(
            &space,
            vec![json!(Message {
                role: "user".into(),
                content: vec!["I always prefer dark mode.".to_string().into()],
                ..Default::default()
            })],
        )
        .await;

        space.formation.process_one(&ctx, &mut conversation).await;

        assert_eq!(conversation.status, ConversationStatus::Completed);
        let first = requests.lock().unwrap()[0].clone();
        assert!(!first.instructions.contains("NOTE_HEAD"));
        let index = first
            .chat_history
            .iter()
            .filter_map(Message::text)
            .find(|text| text.contains("[Saved note index]"))
            .expect("the runner injects the note index");
        assert!(index.contains(r#""id":"pending""#) && index.contains("NOTE_HEAD"));
        assert!(
            !index.contains("NOTE_TAIL"),
            "an index carries excerpts only"
        );
        let stored = space
            .memory
            .get_conversation(conversation._id)
            .await
            .unwrap();
        let stored = serde_json::to_string(&stored.messages).unwrap();
        assert!(!stored.contains("Saved note index"));
        space.close().await.unwrap();
    }
}