magi-cli 0.248.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
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
<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/yukimemi/magi/main/assets/logo-dark.svg">
    <img src="https://raw.githubusercontent.com/yukimemi/magi/main/assets/logo.svg" alt="magi — multi-agent implementation competition" width="540">
  </picture>
</p>

<p align="center">
  <img src="assets/demo-desktop.gif" width="800" height="480" alt="Desktop demo, two-pane layout: Asuka's chat files an uploader retry task, the Queue list and task detail sit side by side, three blind candidates compete and the judges' tally and review rounds show in the detail pane, then the owner answers an agent question and approves the pull request merge.">
</p>

<p align="center">
  <img src="assets/demo.gif" width="360" height="646" alt="Phone demo: Asuka's chat files an uploader retry task; three blind candidates compete, judges rank them and reviews fix a finding; the owner answers a question and approves the pull request merge.">
</p>

# magi

**A multi-agent implementation competition, as a CLI.**

Three agents solve the same task in isolation. Three judges rank the results
without knowing who wrote what. If they disagree, they argue, and then vote
privately. The winner survives a review + real-machine verification loop before
anything is allowed to merge.

The premise is that one agent's *first choice of approach* is the part no amount
of reviewing fixes. Review a bad design carefully and you get a well-polished
bad design. So magi does not review one implementation — it holds an election
between several, and only then reviews.

<p align="center"><img src="assets/flow.svg" width="760" alt="magi flow: the queue loop (conductor), one competition from prep to land, and the standing chat / release bump"></p>

<details>
<summary>Mermaid source (for editing; keep <code>assets/flow.svg</code> in sync)</summary>

```mermaid
flowchart TD
  subgraph Q["queue loop — `magi serve` (outside any one run)"]
    direction LR
    conductor["conductor ×1 per poll cycle\n[roles] conductor"]
  end
  conductor -.->|arranges blocked_by / recovery, then hands off| prep

  subgraph Run["one competition — `magi run`"]
    direction TB
    prep["prep: worktrees + blind hook\n(no agent)"]
    advisor["advise: advisors ×A, read-only\n[roles] advisors (falls back to judges)\n[graph] advise, advisors"]
    synth["advise: synthesis ×1, blends the advisors\n[roles] synthesizer"]
    impl["implement ×N\n[roles] implementers\n[graph] implementers"]
    judge["judge ×M, blind\n[roles] judges\n[graph] judges"]
    delib["deliberate\n[roles] judges\n[graph] deliberate_rounds"]
    vote["final vote, private\n[roles] judges"]
    tally["tally\n(mechanical, no agent)"]
    fold["fold losers\n(no agent)"]
    review["review ×R + E2E + fix, bounded\n[roles] reviewers, fixer\n[graph] reviewers, review_rounds"]
    gate["gate commands\n[verify] gate — shell, no agent"]
    merge["merge\n[graph] land, land_approval — no agent"]
    land["land loop: watch CI, fix, ask to merge\n[roles] fixer, reused"]

    prep --> advisor --> synth --> impl --> judge
    judge -->|first choices agree| vote
    judge -->|split| delib --> vote
    vote --> tally --> fold --> review --> gate --> merge
    merge -->|merge = pr, land = true| land
  end

  subgraph Standalone["standing chat / release bump — `magi chat`, `magi bump` (outside any run)"]
    direction LR
    chatter["chatter ×1 per turn\n[roles] chatter"]
  end
```

</details>

Every box above that spawns an agent has a `[roles]` field to pin it to a
specific one:

| Seat | Runs | `[roles]` field | Other knobs | Pinnable? |
|---|---|---|---|---|
| conductor | once per poll cycle | `conductor` | — | yes |
| advisors (design deliberation) | ×`advisors` (default 3) | `advisors` *(unset falls back to `judges`)* | `[graph] advise` on/off, `[graph] advisors` count | yes |
| advise-synthesis (blends the advisors into one brief) | ×1 | `synthesizer` *(unset falls back to a claude seat, else roster order)* | — | yes |
| implementers | ×`implementers` (default 1) | `implementers` | `[graph] implementers` | yes |
| judges (rank / deliberate / vote) | ×`judges` (default 3) | `judges` | `[graph] judges`, `deliberate_rounds` | yes |
| reviewers | ×`reviewers` (default 3) | `reviewers` | `[graph] reviewers`, `review_rounds` | yes |
| fixer (review loop and land loop) | ×1, only when findings block | `fixer` *(unset falls back to the winner's own seat)* | — | yes |
| fixer (graft, between tally and review) | ×1, only with 2+ candidates and judge-named strengths in the losers | `fixer` *(same chain; unset uses a fresh seat for the winner's author)* | `[graph] graft_runner_up` on/off (default on) | yes |
| chatter (`magi chat`, `magi bump`) | ×1 per turn | `chatter` *(unset falls back to a claude seat, else roster order)* | — | yes |
| language_judge (PR title / body English check) | ×1 per check, only when set | `language_judge` *(optional; unset spawns nothing and the built-in heuristics decide, as they do after a failed, timed-out or unparsable call)* | `[graph] github_text_guard` | yes |
| tally / fold / gate / merge | n/a — no agent seat | — | `[verify] gate`, `[graph] land`, `land_approval` | n/a |

`fold_losers` は読み取り専用席の破棄イベントを各撤去の直後に保存します。
後続席の撤去が失敗しても、既に破棄したパスの記録は残ります。

**Role lists are also an ordered backup list.** An array-valued `implementers`,
`judges` or `reviewers` may be longer than its `[graph]` seat count. With
`[graph] implementers = 1` and `implementers = ["a", "b", "c"]`, only the first
entry sits on a seat (`judges` starts one place along, because its list is
rotated). The rest are spares: when a seat's agent fails or hits quota,
`graph::pick_successor` walks the full, untruncated roster
(`ResolvedRoles::implementer_roster` / `judge_roster` / `reviewer_roster`) from
that seat's position to the right, preferring agents no other seat holds and
trying each agent at most once per call. A reviewer seat can additionally
retry an agent that failed it earlier once the forward entries are used up.
This is separate from the fallback chains of `synthesizer`, `chatter`,
`fixer` and `language_judge`.

## What makes the judging blind

A judge that knows which model wrote a candidate stops grading the patch and
starts voting on the model's reputation. Four mechanisms prevent that:

| Mechanism | Where |
|---|---|
| Candidates are `A`/`B`/`C` by seeded shuffle; each judge gets its own presentation order | `src/blind.rs` |
| Branches are named after the **label** (`magi/<run>/B`), so a judge can `git show` a candidate without learning its author | `src/run.rs` |
| A per-worktree `commit-msg` hook deletes `Co-Authored-By:` / `Generated with …` before they can land | `src/blind.rs`, `src/git.rs` |
| The same trailers are stripped again at presentation time, and uncommitted work is rescued under a neutral identity | `src/blind.rs`, `src/git.rs` |

The facilitator is **code, not an agent**. magi assigns the labels, relays the
transcript, and collects the final votes one-to-one. A moderator that never
learns an author cannot leak one, and there is no seat for a model to be
persuaded out of neutrality.

Two more consequences of that design:

- **Seats, not agents.** Conversations are keyed by seat (`impl-B`, `judge-2`),
  never by agent id. The model that wrote candidate B and the model sitting as
  judge 3 may be the same model, and it still cannot recognise its own work,
  because the judge seat's conversation never contained the implementation.
- **Private final votes.** After deliberation, each judge is asked separately,
  told that nobody sees the answer, and no running tally exists to drift toward.

Vendor names appearing in the *patch body* are a different problem: redacting
them would corrupt the artifact under judgement. magi scans for them, records
what it found, and `blind.on_leak` decides (`warn` by default, or `redact` /
`fail`).

## Conversation continuity

Deliberation and the review loop are multi-turn. Re-sending three patches on
every turn is both expensive and worse — a judge should argue from what it
already said. magi therefore keeps one CLI conversation per seat:

| CLI | open | resume | notes |
|---|---|---|---|
| `claude` | `--session-id <uuid>` (magi mints it) | `--resume <uuid>` | addressable before the first turn |
| `opencode` | `run --format json` reports `sessionID` | `run -s <id>` | id captured from the event stream |
| `agy` (Antigravity) | `--output-format json` reports `conversation_id` | `--conversation <id>` | `--print-timeout` is raised to the node budget |
| `codex` | `exec --json` reports `thread.started.thread_id` | `exec … resume <id>` | `resume` is a subcommand: every option precedes it. The prompt goes on stdin |
| `omp` (oh-my-pi) | `-p --mode=json` reports `id` on its `"type":"session"` line | `-p … --resume <id>` | the answer is the last non-empty assistant text block: a turn that ends on a tool call emits **no** `agent_end` line to read it from |

When a seat has no live conversation — sessions disabled, or a first turn that
never reported an id — magi re-sends the full context instead of letting the
agent argue from memory it does not have. Set `graph.sessions = false` to force
that everywhere.

Gemini CLI is deliberately **not** supported: Google retired the standalone
client for individual accounts in favour of Antigravity, so the adapter would be
dead code. `kind = "command"` covers anything else.

## Install

```sh
cargo install magi-cli
```

magi drives *subscription CLIs*, not API keys: `claude`, `opencode`, `agy`,
`codex`, `omp`, or
any command you point it at. It spends your existing plan and nothing else.

## Use

Help and usage errors are coloured; `--no-color`, `NO_COLOR` or a pipe makes them plain.

```sh
magi                          # the observation deck (see below)
magi init                     # write a starter magi.toml
magi doctor                   # check CLIs, repo, roster, seat assignment
magi run "add retries to the uploader"
magi run --file task.md
magi run --issue 42           # task from a GitHub issue, via gh
magi run --resume 20260830-153012-a1b2
magi show                     # full report for the latest run
magi list
magi stats                    # win rates, reviewer precision, E2E yield
magi fold --all               # remove a run's worktrees and branches
magi self-update              # or let the background check tell you
magi task add "port the retry logic to the uploader"
magi task list                # the backlog `magi serve` drains
magi task done <id>           # work that landed some other way
magi serve                    # run the queue unattended
magi web                      # the phone UI, over Tailscale — Chat is where new work starts
magi repos                    # local checkouts found under [repos] roots
magi answer                   # what an agent is waiting to hear from you
```

Recovery lineage and `retain-recovery-sources` normally prevent folding, even
after a task finishes. To explicitly release one finished, non-resumable run:

```sh
magi fold <run-id> --override-recovery-retention --all
```

The flag requires an explicit run ID; `--all` includes that run's winner, not
other runs. Live or unknown drivers, dirty sources, ownership/output/execution
leases, Git checkpoints and evidence failures still refuse deletion. Unincorporated
tips are archived in `artifacts/fold-evidence` before an operator override event
is saved and deletion starts. The run record and retention sidecar remain.
Automatic housekeeping never overrides retention.

`magi run --resume <run-id>` continues only work that was interrupted or
stopped at a resumable boundary. A completed failed final gate is not retried
by resume: magi preserves the recorded command output, reports the run as
`blocked`, and exits unsuccessfully. Fix the cause and start the intended
follow-up run instead; this avoids presenting an old failed command as a new
verification attempt.

**Every run is a task.** `magi run` and `magi review` first file a task in the
queue (the same path as `magi task add`) and print its id - open it with
`magi task show <id>`. If a `magi serve` / `magi web` loop is alive on this
machine the task is filed `urgent` (its own one-slot lane, other runs are not
paused) and the command follows the loop's run and exits with its outcome;
otherwise an independent worker runs the task, holding its claim so a scheduler
that starts meanwhile cannot take it. The CLI only follows: closing that CLI
does not terminate the worker. `--merge`, `-c`, `-j`, `--review-rounds`, `--seed`
and `--config` ride on the task, so they hold either way. A run that fails
standalone leaves its task `held` (`magi task release` retries it).

Implementation imports are opt-in on both `magi task add` and `magi run`:

```sh
magi task add --start-from feature/fix --pick-commit abc1234 --pick-commit def5678 -- "Finish the implementation"
magi run --start-from feature/fix -- "Finish the implementation"
```

`--start-from <BRANCH|COMMIT>` selects one starting commit **including its
ancestry**. `--pick-commit <COMMIT>` accepts a commit SHA and applies only that
commit, in the exact order supplied; repeat it for multiple commits. Merge
commits cannot be picked. Inputs are resolved to full SHAs before filing and
stored separately from the instruction. Branch movement does not change a
queued task or retry. A branch whose local and remote-tracking tips differ
resolves to the newer tip when one contains the other (a fetch that left the
local branch behind); diverged tips, unknown/ambiguous inputs, duplicate picks
and picks already in the selected starting history are rejected before
candidate worktrees are created. Resolution uses locally available objects and
tracking refs; it never guesses from prose.

Titles, task descriptions, examples, quoted logs and conversation answers never
select imports or recovery sources. Old automatically inferred run `seeds` are
kept for audit only; they are not converted to explicit inputs. Existing explicit
review and `recover-pr` selections retain their own ownership and approval checks.
Already prepared runs keep their work; this upgrade does not rebuild them.

For a task stopped by accidental historical prose imports, inspect `magi task
show <id> --json` and its runs first, then hold it if necessary. Use `magi task
sources <id> --clear` to select no imports, or supply `--start-from` and/or
`--pick-commit` to replace the entire selection. This operation requires an
unclaimed queued/held task and refuses review/recovery tasks or any attempt that
may contain useful candidate work. It preserves the instruction and run history.
Then `magi task release <id>` explicitly authorizes preparation to retry with the
new selection. When the operation refuses because work may exist, preserve it
and use the explicit review or `recover-pr` workflow instead; do not delete runs
or close PRs merely to clear a preparation error. Source options on `run --task`
or `run --resume` are rejected rather than silently ignored.

A run created before this change whose prose-derived cherry-pick failed *after*
its candidate worktree was created is the one case `task sources` cannot help:
it has no structured sources, it keeps its registered candidates (so the
command refuses it), and it never opened a PR for `recover-pr`. Preparation
stops before any agent runs, so those candidate worktrees hold only the base
commit plus the unintended imports; the imported commits still exist on their
own branches. To resume the original task without them, take each candidate
worktree listed by `magi show <run>`, check `git -C <worktree> status` for
anything of your own (commit it to a branch of yours first if so), run
`git -C <worktree> cherry-pick --abort`, then `magi task release <id>`. The
retry removes the now clean candidates and recreates them from the base commit
with no imports, continuing the same run and its history.

To recover an existing task PR from an implementation the operator has chosen,
use `magi task recover-pr <task-id> --pr <PR-URL> --head <full-public-SHA> --disposition land`
(or `--disposition review` for local review only). Optional `--source-head <full-SHA>`
preserves a reviewed fix independently of the public-head lease. See
[the recovery contract and validation setup](docs/existing-pr-recovery.md).
This queues a single review candidate from the fetched public commit with its
complete ancestry, preserving the task's instructions. The selection overrides
historical review branches and resume pins.
The PR must be the unique open PR for the task's current assignment head:
`magi/task-<task-id>` initially, or `magi/task-<task-id>-assignment-<generation>`
after reassignment, targeting the configured base in the task's repository.
Active or unknown previous publishers prevent takeover; historical source
branches and worktrees remain.

Recovery synchronizes through the ordinary current-base path and still needs
verification, review and owner merge approval. Publication checks ownership
again and leases the public update to the approved head (or this run's last
successful push). A moved head requires a new explicit selection. Startup and
candidate preparation failures leave one actionable hold rather than automatic
new competitions; correct the cause before releasing or selecting a source
again. Partially created recoveries are recorded in run history for inspection.


`magi run` starts spending money, so an instruction whose first word names a
subcommand is refused as a probable typo: there is no `magi run show`, and
without the guard `magi run show 3cbf` opens worktrees and pays agents to
implement the sentence "show 3cbf". Write `magi run -- show 3cbf` when that is
genuinely the task.

A run branches off the **base branch's tip**, not off your working copy, so it
starts whether or not you have uncommitted work — and that work is not part of
the competition. `magi serve` would otherwise decline every task for as long as
you had something in progress, which is most of the time. magi says so in the
log when the tree is dirty, because someone watching a candidate fail to use a
change they just made deserves to know why.

## The observation deck

Bare `magi` (or `magi tui`) opens every run in one screen, refreshed from disk
once a second, so a competition can be watched instead of polled:

```text
 magi   2 runs  1 active  1 done  0 attention  |  filter: all
┌ runs ─────────────────────────┐┌ report ────────────────────────────────┐
│> reviewing   a1b2  add retries ││magi run 20260830-153012-a1b2  reviewing│
│  ready       50f1  fix the …   ││  candidates                            │
│                               ││  A  opus    3 files, 2 commits  <- winner
└───────────────────────────────┘└────────────────────────────────────────┘
 j/k move  Tab pane  J/K scroll  a filter  r refresh  o open dir  ? help  q quit
```

| key | |
|---|---|
| `j` `k` `↓` `↑` | move in the focused pane |
| `Tab` | switch pane (runs / report) |
| `J` `K`, `PageDown` `PageUp` | scroll the report |
| `g` `G` | newest / oldest run |
| `a` | cycle filter: all → active → attention → done |
| `r` | refresh now |
| `o` | open the run's directory in the OS file manager |
| `?` | help |
| `q` `Esc` `Ctrl-C` | quit |

It is **read-only on purpose**: the runs are the record of what the agents did,
and a keystroke that could rewrite one has no business being a `j` away from
browsing. Cleanup stays in `magi fold`.

Piped or in CI, bare `magi` does not raise an alternate screen — it prints the
latest run's report instead, so `magi | head` behaves.

## Running unattended

A competition takes tens of minutes, almost all of it agent latency. Sitting in
front of that is the wrong job for a human, so magi has a queue and a loop that
drains it:

```sh
magi task add "port the retry logic to the uploader"
magi task add --file tasks/rework-config.md --priority 5
magi task add --issue 42
magi serve                    # take the next task, run the graph, repeat
```

One task is one JSON file under `<data_local>/magi/queue`, so the backlog is
readable, editable, and greppable with the tools already on the machine, and a
daemon killed mid-run leaves a queue the next one picks up.

The Web Queue uses compact rows with the existing task detail alongside them
on wide screens. Drag the ↕ handle (mouse or touch), or focus it and press
Arrow Up / Down, to reorder within a section after clearing search. Queue
moves persist priorities through the ordinary priority endpoint: higher values
run first, ties use ascending task ID. Running tasks cannot move. Upgrade
resumes occupy a fixed lane ahead of ordinary priorities; admission, urgent
slots and other eligibility gates still apply. Saves are sequential, not atomic:
if a write is refused, remaining writes stop and the list reloads the saved order.
The +/− priority controls, Edit and Actions remain available on every row,
without selecting it first. Open confirmations and drafts survive list refreshes.
Row actions keep the current view even when opening a confirmation replaces
the clicked control; only non-interactive row content selects the task detail.

Competition rows already use the existing run detail. Their handles reorder within
a section in this browser after clearing search; scope and state filters may stay
active. Filtered and unloaded runs retain their remembered positions. New runs
appear before remembered rows; **Reset order** restores the default section order.
Storage refusal keeps the choice for the current tab. Refreshes retain row identity
and disclosures, freezing the DOM during a drag. Queue drops read fresh priorities
and resolve the destination by neighbouring task IDs before saving.

`magi serve` runs **one competition at a time** on purpose. The graph is already
parallel inside — candidates times judges — and two graphs at once doubles the
burn on the agent-CLI quota that is the real constraint.

If queued work is not starting, the Web loop's idle line reports the latest
completed dispatch scan's reason counts (landing waits, cooldown, occupied
ordinary/urgent slots, interrupt withholding, or claim/re-read failures).
`daemon.json` exposes the same observation as `dispatch_wait`, including the
pre-gate runnable count. It is cleared when work starts or the scan is incomplete;
it is not a fresh queue census. Tracing logs a readable explanation per skipped
task only when the task/reason set changes, and reports when the set clears.
Claim failures do not distinguish contention from other claim errors.
These diagnostics do not change dispatch policy.

`magi task add --urgent` is the escape hatch for the rare task that genuinely
cannot wait. It dispatches the moment it is runnable, through one extra,
temporary slot, alongside whatever is already running — the run already in
flight is never paused, parked, or restarted to make room. It is not a way to
raise `[daemon] max_concurrent_runs` for good: that setting, and its default
of one, is unchanged, and while an urgent task is in flight quota burn can
briefly reach `max_concurrent_runs + 1` runs at once instead of just one.
Change an existing task with `magi task urgent <ID>` to enable urgent, or
`magi task urgent <ID> --clear` to disable it. IDs may be unambiguous short IDs.
`magi task show <ID>` reports the saved enabled/disabled state. In the Web
Queue, use **Actions → Urgent: off/on**, or the same toggle in the task detail's
action sheet. The URGENT badge reflects the saved setting.
Only unclaimed queued or held tasks can change urgent. Changing a held task
keeps it held, with its reason and attempts intact; release it separately when
ready. Claimed, running, and other task states are refused; wait for the claim
to release and requeue or hold the task before retrying. This changes neither
priority ordering nor the interrupt park/resume request.

Two `--urgent` tasks do not both jump the queue — the second waits for the
first to leave the urgent slot, same as any other pair of tasks waits for a
free ordinary one. `--urgent` and `magi task interrupt` (`[daemon]
pause_for_interrupts`) do not compose, in either direction: while an urgent
run is in flight, interrupt cannot start (it only ever begins once exactly
one run is in flight); and while an interrupt's own park/resume handoff is
under way — for that same task or an unrelated one — an urgent task waits
out the same gate an ordinary task would, because the handoff's own "one run,
never two" guarantee has to win over urgent's own "never wait" one. Both are
opt-in and, together, a rare combination; `pause_for_interrupts` is off by
default.

| verb | |
|---|---|
| `magi task add` | file work; text, `--file`, `--issue`, or stdin |
| `magi task list` | the backlog, newest first |
| `magi task show <id>` | one task in full |
| `magi task urgent <id> [--clear]` | enable or disable urgent on an unclaimed queued or held task |
| `magi task implementers <id> <count>` | change implementers on a queued or held task (1 = Solo, 2–3 = competition) |
| `magi task build-cache <id> shared\|isolated\|default` | set or clear the build cache override on an unclaimed queued or held task |
| `magi task hold` / `release` | park work, or give it a real second chance |
| `magi task done` | mark it finished, for work that landed by a route the loop did not see |
| `magi task rm` | delete it |

`done` and `release` are one keystroke apart and do opposite things. Reach for
`done` when the work is already in `main` — merged by hand, or merged by a run
that recorded its own merge as a failure. `release` would put the task back in
line and pay for the whole competition again to redo it.


A queued or held task's implementer count can also be saved from its Queue card
or task actions sheet. This changes only that task, preserving its ID,
instruction, attachments, creation metadata and run history. Running and other
states cannot be changed. Switching to or from Solo may start a fresh run when
an earlier run used a different count; earlier candidate work is not reused in
that case. Explicit `magi review` tasks remain reviews of their requested branch.
Count edits on tasks without run overrides continue inheriting the daemon's
options. Existing run overrides, including empty and count-only ones, retain
configuration isolation across Solo changes. Conversation preferences and
repository defaults are unchanged.

### Agents file their own work

`magi task add` is not a human-only command. Every agent the graph spawns gets
`MAGI_RUN` and `MAGI_NODE` in its environment, so an implementer that notices
something worth doing but out of scope can file it:

```sh
magi task add "the config loader re-reads the file on every lookup"
```

The task records `implement@a1b2` as its source rather than `human`. That
attribution comes from the environment `agent::invoke` sets, which no flag can
forge by accident — which is what makes "most of the backlog was filed by
agents" a measurement rather than a claim. It is also the whole point: the CLI
is the operating surface, and the agents are its users as much as you are.

### Bounded on purpose

An autonomous loop that retries forever is a way to spend money on a task that
cannot succeed. Every attempt is counted; a task that burns its attempts becomes
`held` and waits for a person, not for another agent.

A **quota stall is refunded**. When the agent CLIs hit their rate limit the
judging panel collapses, the run stops as `stalled`, and the task goes back in
line *without* spending an attempt — a quota window closing at 4am must not
leave a backlog of tasks that were never actually judged.

Only a rate limit earns that refund. A judging panel can also collapse because
the judges answered with the wrong shape — which is ordinary flakiness, can
recur on every attempt, and is charged to the task, so the attempt counter
still bounds it. Refunding *that* would take the bound off the loop entirely
and pay for a fresh implement wave every time.

## Working out what to build, with someone

A task file without completion criteria produces a competition whose candidates
cannot be compared, and you find out forty minutes and several dollars later.
So the first step is a conversation — Chat, the standing conversation on the
phone UI (`magi web`):

```sh
magi web
```

Open Chat, talk the idea through with an agent that can read the repository
and run commands, and once the shape of the change is settled, tell it to file
the work. The agent runs `magi task add --solo` on your behalf — the same
command you would type yourself — and the conversation stays open, so any
number of tasks can come out of it over time rather than ending the moment one
does.

## Legacy question panels: the agent formats its own confirmation screen

For legacy non-task questions, an agent can hand over
a page it wrote itself:

```sh
magi ask --summary "Which cache key shape?" \
         --choice "u64 hash" --choice "string key" \
         --panel panel.html --asset before.png
```

The panel is the agent's own HTML and CSS — a diffstat table, a coloured diff,
a screenshot — rendered on your phone under the question. Attachments are
copied into the question, so a panel still renders after `magi fold` has
deleted the worktree it was written in.

### Why this is safe

Rendering someone else's HTML in your browser is the thing this UI otherwise
refuses to do: nothing from the API is ever put into `innerHTML`, and even an
href out of a run record goes through a scheme check. A panel is the exception,
and it is only acceptable because of three things together:

- The frame is `<iframe sandbox>` **with no tokens at all**. No JavaScript
  runs. It cannot reach the page around it, your cookies, or `localStorage`.
  There is one function in the client that builds it and a comment forbidding
  anyone from adding `allow-scripts`.
- The panel is served under a **strict CSP**:
  `default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; …`.
  Inline CSS is allowed, because formatting is the point. **Everything that
  reaches the network is denied**, so a panel cannot phone home through a
  remote image or a beacon — verified with the browser's own violation log.
- Assets come from magi, by bare filename, from that question's own directory.
  The name must match `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, is validated on the
  way in and again on the way out, and an `.svg` is served
  `Content-Disposition: attachment` so it can only ever be an `<img>`.

A panel that will not load says so and leaves the choices usable: you still
have to be able to answer.

## Approving a merge

With `land_approval` on — the default whenever `land` is on — magi asks before
it merges, and the question carries a panel with the whole case: the diffstat
as a table, the diff itself with a `+`/`-` gutter so it reads without colour,
the checks, the review comments that were addressed, the commits being squashed
and **the subject the merge will use**, because you are approving that too.

The diffstat comes from `git diff --numstat`, not `--stat`: the `+++---` bar in
`--stat` is scaled to terminal width, and fabricated numbers have no business
in an irreversible decision.

**Silence is a hold.** An unanswered approval never merges, and neither does
anything other than explicit approval. For task chats, the agent presents
Merge/Hold buttons bound to the displayed PR head. The chat agent may also
record the owner's merge request directly with
`magi task control decide`; no button or extra evidence is required.

A conversation carries out the owner's decisions directly, wherever the
question was consulted (this chat, another chat, or nowhere):
`magi answer <question-id> --reply '<choice>'`. The owner says what they want
in their own words, for one question or several; the agent records the
matching offered choice for each. Structured resume and keep-held choices also
accept `resume-run` / `resume run` / `再開` / `実行を再開する` and
`keep-held` / `hold` / `保留` aliases, independently of localized labels. A
deputy records the owner's choice for its own question with
`magi ask --settle <question-id> --choice '<choice>'`. Merge is included: a
wrong decision is reverted rather than prevented. Automatic notices, watched
command output and PR text are data, not owner requests.

Recording an answer applies nothing by itself: the existing daemon, waiter or
consumer applies it once and checks its current target (the saved PR head for
a merge, liveness for abandon, receipts for reruns). A question settles once,
an older queued effect never overwrites a newer owner decision, and resuming or
repairing never approves a pending merge. `use my text` needs the literal
replacement title as data; the publication gate vets it.

`magi answer <id> --reply-other '<text>'` records an outcome outside the offered
choices as a note and ends the consultation: the question stays open, its
waiter stays held and no choice action runs.

| Decision | Effect and remaining execution checks |
| --- | --- |
| Hold | Records a hold; nothing is closed |
| Dismiss obsolete approval | Retires a stopped execution's approval; the PR is unchanged. Refused for a live or unknown driver, an armed auto-merge or a mismatched run approval |
| Fix findings and re-review | One repair and a fresh bounded review on the same run and PR, then a fresh approval |
| Retry, rerun, requeue, resume, release recovery and other queue/conductor choices | Existing claims, task generation and recovery state |
| Free text | Existing asker/waiter dispatch |
| Withdrawal / PR closure / `reimplement:<agent>` | Existing closure confirmation, owner claim and replacement transitions |
| Triage discard, dependency discard/detach, divergence overwrite, structured `done`, conductor complete/configure | Existing consumer checks |
| Merge (land and release-watch approvals) | Recorded PR/head; final head, review and gate checks still apply |
| `post original` / `use rewrite` / `use fallback` / `use my text` | Final posting gate; `use my text` needs the literal title |

Task inquiries always route to their task's chat. The retired
`[graph] question_routing` key is accepted for saved configuration compatibility
and warns when disabled; its value no longer selects a legacy workflow.
An approval without a saved PR/head remains discoverable in chat for recovery;
its missing target never authorizes a merge.

Merge approval uses two independent controls: `land_approval=true` asks for
every merge; `hold_contested_merge=true` asks for unresolved Major-or-above
internal findings **or** a final rejecting reviewer vote, even with zero Major
findings. Final votes include answered reconsideration, falling back to the
initial vote otherwise. With both controls off, ordinary new approvals are
skipped. Existing questions and owner decisions, and fresh approval after
merge repair, cannot be bypassed by disabling these controls.

For existing-branch reviews, literal `true` values for either control in the
reviewed commit's `magi.toml` or `.magi/config.toml` also require the hold. These
values can only strengthen base policy, persist across later removal and resume,
and are checked again at the landing head. Questions record the source file and
commit. Branch includes and templates are not evaluated; all other settings,
including verification commands, still come from the base configuration.

The question and phone panel show all applicable approval reasons, each final
vote and its reason, and last-round internal findings (including Minor) with
available adoption evidence. A fixer claiming a finding was addressed, or a
green gate, does not prove its resolution. External PR comments are reported
separately; no outstanding external comments does not imply internal findings
were resolved. Saved questions retain their original evidence on resume.

When review hands off with unresolved Major findings or final rejecting votes,
the decision also offers **fix findings and re-review**. Selecting it runs one
repair and a fresh bounded review and gate on the same PR branch, under the
existing run's ownership. The question ID, head and original review evidence
are retained in the run's repair history. Even a repair that changes nothing
is reviewed again. This action invalidates the earlier approval and disables
auto-merge; updated results always require a fresh owner decision, including
when `land_approval` is off. **Hold only holds** and never starts a repair.
The CLI accepts the same choice with
`magi answer <question-id> --reply "fix findings and re-review"`.
This command records the choice and prints its execution status. A running
`magi serve` / `magi web` resumes the existing run; without a daemon, use the
printed `magi run --resume <run-id>` command to start the repair.
Legacy merge/hold-only cards are upgraded on read, with the same durable
choices used by the Web API, CLI and standing chat. Repair resumes the latest
owning task and run; it never files a competing task. A held owner is released
with a pin to that run, and repeated delivery of the same question is harmless.
Existing chat consultations receive the current choices on their next turn.
Repair obeys normal concurrency and quota waits rather than using the
merge-decision priority lane. Missing or unsupported owners produce recovery
guidance; restore the existing owner instead of adding another task.
If an installed server still shows only merge/hold, update and restart it from
a release containing these changes, then reload the card. The version alone
does not distinguish a release from later source builds at the same version.
Repair cycles are capped by `land_rounds`, with each new review bounded by
`review_rounds`. A changed PR head, dirty worktree, failed repair or interrupted
fixer holds with recovery guidance in `magi show`; an interrupted fixer is
never dispatched a second time automatically.

## Chat: a standing conversation, turn by turn

Chat runs as a **turn-based conversation**: your message, one headless agent
turn, repeat. Each turn resumes the CLI's own conversation (`claude -p
--resume`, `opencode run -s`, `agy --conversation`), so a turn sends only your
new sentence rather than replaying the transcript and paying for it again.
Your message is written to disk **before** the agent is invoked, so a quota
window or a crash cannot lose something you typed.

While a reply is running, Chat accepts the next message as one durable pending
draft instead of starting a second CLI turn. The web composer shows that draft;
use **Resume queued draft** to run it unchanged, **Edit text** to replace only
its text while keeping its attachments, or **Clear** to discard the exact draft
you are viewing. Clear and Edit use a snapshot check, so they refuse rather
than overwrite a draft changed by another action. Restarting the web or scheduler
does not terminate an in-flight Chat invocation: its independent worker retains
the same conversation and CLI session, and the replacement web process displays
its busy state and eventual reply. Submissions accepted after an update use the
new executable; queued sends remain serialized behind the running turn. Chat
execution, publication fencing and startup recovery are implemented together in
`src/chat_worker.rs`; they do not use the legacy question consultation dispatcher.
Use **Resume queued draft** for text-only or image-only recovery after an actual
execution failure, rather than resending the stored message. A launch failure
proven to have started no execution restores the recorded send to that draft;
an uncertain startup is never automatically replayed.

The conversation runs with writes disabled by default: an agent that had
already edited the repository mid-conversation would make a later
competition's diffs unjudgeable. `[talk] allow_write = true` lifts that for a
repository that is never entered into one — a dotfiles or personal config
checkout — so a one-line fix does not have to go through the queue to land.

Unlike a one-shot interview, Chat does not end when a task is filed: the agent
runs `magi task add --solo` from inside the conversation, tells you the task
id, and the conversation stays open for whatever comes up next.

### Durable follow-through

An explicit request for continuing work is saved as a goal, independently of
the transcript, task status and CLI session. The agent registers its purpose,
authorized scope, actual owner input, completion condition and related tasks,
runs or supervised watches through `magi task control goal`. Automatic reports
and external submissions cannot supply owner input or expand a goal. The
machine-only standing authorization below can register a goal limited to the
reported task and update its progress; it cannot broaden any goal.
Several unfinished requests remain retained; a later status question does not
replace earlier work.

Use `magi task control goal establish … --repo <path-or-name>` to follow
work outside the conversation's repository. It uses the same local path,
`owner/repo` and unique short-name selectors as `magi task add`, but never
clones. Relative paths start at the conversation directory. A path inside a
checkout selects its Git root, even if the task retained the subdirectory.
Checkout discovery ignores inherited Git repository overrides. Decision receipt
matching uses the same checkout identity while still requiring the exact run
and receipt.
Without `--repo`, the goal uses the conversation directory, including for older
saved goals. Multiple goals in one conversation can target different
checkouts without changing the conversation's directory, agent or permissions.
Repeat an establishment with the same ID and target only as an idempotent
request. Use `goal update <id> --repo <path-or-name>` from a new owner request
to change the target. If any retained task or run belongs elsewhere, the whole
update is refused; create a separate goal instead of silently dropping links.

Guarded goal transitions advance per-goal revisions. Whole-conversation saves
retain missing goals and prefer durable state at equal or newer revisions, so
a stale reply cannot erase progress, execution receipts or an owner's stop.

The scheduler reserves an independent finite goal-observation service; slow
forge and Git reads never run on its task-admission loop. Each service lap
checks at most eight goals, reading every associated task, run and watch
without truncating completion evidence. A related task contributes only its
latest execution run; listing an earlier attempt explicitly does not bring it
back into observation. Every distinct observed PR is refreshed
once per lap with a bounded lookup, including PRs beyond the first four; its
result remains associated with every referring run. Changed evidence reserves
one finite conversation worker; unchanged evidence spends no agent turn.
Waiting releases the CLI and turn lease.
Goal input is separate from drafts and never sends an unsent owner message.
Fresh, resumed and fallback seats receive the saved goals and current evidence.
Repairs use existing controls and their effect receipts, not replacement tasks.
Uncertain interrupted execution pauses for reconciliation instead of replaying it.
Automatic continuations are capped at 32 and evidence probes at 240 per
authorization; exhaustion is visible rather than an indefinite polling loop.

The compact Chat progress area shows purpose, state, target repository, current
step/wait reason and the relevant existing Run (or Task before a run exists).
Referenced tasks take precedence; otherwise the newest valid explicitly
referenced same-repository Run is used. Graph stages, reviews, verification and
logs remain on Run. A completed task or a newly opened PR is not goal
completion: landing requires a fresh confirmed merge of the recorded head.
Implementation-only goals retain the distinction between a delivered, verified
artifact and owner approval to merge. Automatic events never supply that approval.
Stop/cancel is a goal transition, and stale queued continuations cannot admit
new typed effects. Closing a chat does not authorize reopening it for a goal.

### External CLI conversations

An external tool can join an existing standing conversation without the web UI:

```sh
magi talk list --json
magi talk history <conversation-id> --limit 20 --json
magi talk history <conversation-id> --after '<cursor>' --limit 20 --json
magi talk send <conversation-id> --request <request-id> --sender 'Claude CLI' 'Hello' --json
magi talk send <conversation-id> --request <request-id> --sender 'Claude CLI' - --json < message.txt
magi talk reply <conversation-id> --request <request-id> --wait 30 --json
```

Use a full conversation ID, or a unique prefix; suffixes are not selectors.
`list` returns `talks` (including IDs, repository, agent, status and title) and
`unreadable` entries.
`history` は `talk`、`messages`、`cursor`、`more` を返します。各メッセージの
フィールドは `id`、`sender`、`body`、`at` です。`--limit` は 1〜500 件
(既定 20 件)。`--after` なしでは最新の指定件数を古い順に返し、指定時は
そのカーソルの次から指定件数を返します。`more: true` なら、返された
`cursor` をそのまま `--after` に渡して次ページを取得してください。
空ページでも指定したカーソルは維持されます。通常出力は会話一覧、
送信者付き履歴、または要求状態と返信、`--json` は標準出力の一行に JSON を出力します。

`send` records a caller-generated request ID and starts the existing detached
chat worker, not an HTTP-only or foreground agent. Persist the request ID,
conversation ID, sender and exact message **before sending**. `-` reads all of
stdin, preserving multiline text. Reusing a request ID cannot create another
turn; changing its message or sender is a `conflict`. Do not use a new ID to
work around an interrupted send: query the original request with `reply`.
Only its linked reply is returned, never a later unrelated conversation turn.
`--wait 0` queries immediately; a positive wait waits up to that many seconds.
A wait timeout neither cancels execution nor sends again.

These commands use the same local state home and repository configuration as
the web Chat. The web server and scheduler need not be running: accepted work
runs in the existing durable Chat worker without opening a listener. The worker
and its saved request survive the sending CLI, web, or scheduler exiting.
Live workers (including older executable generations), active turns and unsent
drafts refuse new external admission before any message is appended. A failed
or unknown worker launch retains the request and never promotes an owner draft.
Queued owner messages wait behind previously accepted external input, including
the interval before its worker acquires the conversation's turn lease.

For example, this Bash workflow uses an external Claude CLI to compose a
message. It requires `claude`, `magi`, `python3` and `jq`. Replace `talk_id` with
the full ID from `list`; keep the exchange directory for recovery:

```sh
magi talk list --json
talk_id='FULL-CONVERSATION-ID'
exchange="$HOME/.local/state/magi-external/$(python3 -c 'import uuid; print(uuid.uuid4())')"
mkdir -p "$exchange"
printf '%s\n' "$talk_id" > "$exchange/talk-id"
printf '%s\n' 'Claude CLI' > "$exchange/sender"
python3 -c 'import uuid; print(uuid.uuid4())' > "$exchange/request-id"
claude -p 'Write a short multiline message asking the standing chat to summarize its current work. Output only the message.' \
  > "$exchange/message.txt" || exit 1

# All request data is now on disk. Run this send only once.
magi talk send "$(cat "$exchange/talk-id")" \
  --request "$(cat "$exchange/request-id")" \
  --sender "$(cat "$exchange/sender")" - --json \
  < "$exchange/message.txt" > "$exchange/send.json"

# Even if send exited unsuccessfully or its output was lost, query; do not resend.
magi talk reply "$(cat "$exchange/talk-id")" \
  --request "$(cat "$exchange/request-id")" --wait 30 --json \
  > "$exchange/reply.json"
cat "$exchange/reply.json"

# Pending, timeout, or an interrupted query: requery the SAME request.
magi talk reply "$(cat "$exchange/talk-id")" \
  --request "$(cat "$exchange/request-id")" --wait 30 --json \
  > "$exchange/reply.json"
if jq -e '.status == "replied"' "$exchange/reply.json" >/dev/null; then
  jq -r '.reply' "$exchange/reply.json" | claude -p 'Summarize this standing-chat reply.'
fi

# Read the transcript, then only messages after its saved cursor.
magi talk history "$(cat "$exchange/talk-id")" --json > "$exchange/history.json"
cursor=$(jq -r '.cursor // empty' "$exchange/history.json")
if [ -n "$cursor" ]; then
  magi talk history "$(cat "$exchange/talk-id")" --after "$cursor" --json
fi
```

After a shell restart, set `exchange` to the same saved directory and resume
at `reply`, not `send`. Inspect `status`, not just the process exit code:

| Result | Meaning and safe next action |
|---|---|
| `accepted`, `started` | The request is recorded or executing. Query `reply` with the same ID. |
| `replied` | Read `reply`; `input_id` and `reply_id` identify the exact linked transcript messages. |
| `timeout` | The wait expired; `state` reports the underlying request status. Requery the same ID; execution is not canceled. |
| `busy` | Another turn or pending draft prevents admission. Inspect history and the original request; do not automatically resend. |
| `closed` | The conversation is closed. This interface does not reopen it. |
| `not_found`, `ambiguous` | The conversation selector or request is missing, or the selector matches multiple conversations. Inspect `list` and the saved request; do not guess a target or resend. |
| `conflict` | The request ID is already bound to different sender/text. Preserve its original data and inspect that request. |
| `not_started`, `failed` | Execution did not start or failed. Read `error` and the transcript; this is not permission for an automatic resend. |
| `uncertain` | Execution or delivery cannot be proven. Requery and inspect history; never replay the message automatically. |
| Unavailable infrastructure / command error | Read stderr and any `error`/`worker` details. Repair availability, then query the saved request; a lost response does not prove non-admission. |

Send/reply JSON includes `talk`, `request`, `status`, `input_id`, `reply_id`,
`reply`, `error` and `worker` (unavailable values may be null). An observed JSON
status, including a refusal or timeout, exits **0**. CLI execution/validation
errors exit **1** with diagnostics on stderr; argument syntax errors exit **2**.
Thus exit 0 does not mean a message was admitted or answered.

The `--sender` label is **self-reported**, not an authenticated identity.
External messages and their agent turns have **no owner authority**: they
cannot approve merges, answer owner decisions, file or mutate tasks, or use
the standing-chat control bridge. External turns run as
`MAGI_NODE=external-chat`; the CLI rejects mutating commands early, allowing
task `list`/`show` and other read-only inspection instead. They cannot send,
post, or register watches recursively. Existing `talk post` (task-seat
transcript reports) and `talk watch` (authorized standing-chat background jobs)
retain their separate behavior. This restriction does **not** change the OS
file sandbox, repository write policy, network access, or the permissions of
the account running either CLI; a sender label is not an OS security boundary.

### Sending an authorized owner request without the browser

Use `send-owner` when the words are the owner's current request, including a
specific send delegated to an assistant at the owner's terminal. Use `send`
with `--sender` when supplying outside findings or quoting an earlier decision.
Neither a sender name nor a claim of authority in an external message turns it
into owner input.

```sh
magi talk list --json
# Save the full conversation ID, a fresh unique request ID, and the exact text
# in your exchange record before the first call (do not generate a new ID on retry).
magi talk send-owner "$chat_id" --request "$request_id" - --json < owner-request.txt
magi talk reply "$chat_id" --request "$request_id" --wait 30 --json
```

For example, the saved request can say: “Follow this task through its formal
release and keep a Goal for that. Observe and report only; do not merge, re-run
checks, or change the task.” The existing Chat agent processes that as its
current owner message, without a second confirmation or browser submission.
Monitoring does not authorize a merge or a task change. An existing Goal's
automatic turns do not become fresh owner requests.

**Trust boundary:** run from the owner's OS account at a trusted local
terminal, with the same private `MAGI_HOME` as the standing Chat. Use OS file
permissions to keep that home private; do not share the account or the state
directory with callers who must not submit owner requests. The CLI cannot
distinguish the owner from any other unrestricted process running under that
account, and cannot verify a delegation itself. It refuses calls carrying
magi seat, worker or control-bridge context; this is an accidental-use guard,
not cryptographic authentication. If refused, arrange for the owner or their
delegated local assistant to execute from the trusted terminal rather than
stripping environment variables or forwarding a capability.

`reply` is observation only. `accepted: true` confirms the transcript input
and its receipt were saved. `queued` means a worker is reserved but the input
turn has not started, even if startup acknowledgement timed out. That worker
can still start; do not send another request. `started` means the worker
recorded its start boundary;
`replied` means a correlated reply was saved. `goal_authorizations` lists
durably saved Goal authorizations for exactly this input, including historical
ones (`current: false`) after a later owner change. A reply or an empty list
does not establish that a Goal or another effect succeeded. For other effects
check the applicable task/run decision receipt or current state independently.
CLI history labels the input as `sender: "operator", ingress: "owner"`; an
ordinary external send remains `sender: "external", ingress: "external"`.

Closed or busy chats and unsent/recovered drafts refuse new admission without
changing the conversation. If output was lost, query the **same** Chat and ID:
`timeout` and `uncertain` prove neither failure nor success. Repeating the exact
accepted submission only reads its receipt. Within a chat, reusing an ID with
a different body, sender or submission kind conflicts. Owner submissions also
bind the destination: their IDs remain reserved for owner use in that home
even if the chat is deleted. An external send in a different chat may use the
same ID. The separate owner binding also survives older schedulers rewriting
the Chat. Deleting a chat removes its transcript and effect evidence. If the
binding survived but its transcript receipt is missing, the result is
uncertain, not retryable.
Concurrent owner submissions with the same ID cannot reserve two destinations:
the first reservation wins, even if its transcript receipt is not yet visible.
Never switch IDs to replay uncertain work. Neither a browser nor a running web
server is needed to submit and get the reply. As with a web-established Goal,
automatic follow-through requires the scheduler.

### Controlling tasks and runs

The chat agent acts on queue work by command, with no question or offered
choice in between. `magi task control` works only for the standing chat seat
(`MAGI_NODE=chat`, `MAGI_RUN` the exact id of an open conversation). Targets are
any task id or full run id, including work this chat did not file, and an open
consultation does not block it.

通常のチャットの sandbox・ネットワーク設定・作業ディレクトリは変更しない。
Unix のチャット席では継承 FD、Windows ではローカル名前付きパイプを使い、
専用通信路からランチャーへ操作要求を渡す。Windows のパイプは接続先だけに
必要なデータ通信権限を与え、OS の暗号学的乱数で生成したターン固有の秘密で
要求を認証する。追加のパイプインスタンスを作る権限は所有者だけに与える。
ランチャーは要求元を起動時の会話に固定し、操作ごとに認可と既存の
実行条件を検証する。queue・questions・run などのストアを書き込む権限は追加しない。
通信路の準備に失敗しても会話は続き、そのターンの操作機能だけが利用できなくなる。
通信路はターンの完了・中断時に閉じる。Windows の接続は要求ごとに分離し、
通信待ちは 30 秒で打ち切る。応答が失われた場合は結果不明として自動再送しない。

| command | effect |
|---|---|
| `magi task control reconcile-repair-grant <task> --run <run> --receipt <id> --head <sha> --expect-pass <n> --question <id> --answer-at <timestamp> --request <id> --reason <text>` | Re-queue an accepted, unspent repair receipt invalidated by its original answer being applied after acceptance. Requires explicit owner authorization and exact original answer evidence; adds no repair budget. See [repair budget workflow](docs/repair-budget.md). |
| `magi task grant-repair <task> --run <run> --kind gate\|review\|base-conflict --rounds <1..=3> --head <sha> --expect-pass <n> --request <id> --reason <text>` | Queue an additional bounded repair on the exact stopped run. The chat equivalent is `magi task control grant-repair` with the same arguments. See [repair budget workflow](docs/repair-budget.md) for receipts, retries and ownership checks. No merge approval is granted. |
| `magi task reassign <task> --repo <selector>` | changes the repository for future execution, preserving task identity, conversation, evidence and run history. Accepts the same paths, owner/repo and unique short names as task add. Queued tasks remain queued; held tasks remain held; stopped failed/parked tasks become held and need release. Active or unknown drivers, retained PRs, unfinished receipts and repository-bound review/import selections must be resolved first. Old runs and questions cannot resume the previous repository, even after moving back. Branches and PRs are never moved or adopted. |
| `magi task control reassign <task> --repo <selector>` | the same transaction through the authenticated standing-chat bridge. Use it for a clear owner request to move implementation elsewhere; if the channel is unavailable, report the launcher/backend infrastructure error. Reopening the conversation does not repair descriptor propagation. Never edit queue files or repeatedly resume the old run. Queue task actions also offer repository reassignment. |
| `magi task control recover-base <full run id> --request <id> --head <retained-sha>` | explicitly authorizes bounded recovery of exhausted base movement and queues that exact run through the inherited chat channel. Inspect the retained HEAD; reuse identical request arguments after interruption. Generic resume grants no recovery budget. |
| `magi task control resume <full run id>` | pins the owning task to that run and queues it; the loop resumes it under the graph's execution lease (same checks as the Web resume). It starts no driver itself, so it needs `magi serve` |
| `magi task control hold <task> [reason]` / `release <task>` | the same transitions as `magi task hold` / `release` |
| `magi task control retry <task> <instruction>` | replaces a queued or held task's instruction and queues it in one save; attempts restart as for any release, runs and history are kept |
| `magi task control rerun-checks <full run id> --request <id> --head <sha> --workflow <id>` | 指定した head と失敗 workflow を再確認し、リクエスト単位で再実行する。同じ操作の再送には同じ request ID を使う。`chat-controls/<talk>/<request>.json` に受付を記録し、結果不明の再送は拒否する |
| `magi task control decide <question id> <option> [--title "<replacement>"]` | records the owner's decision on publication (github-text), branch divergence, release recovery or merge approval awaiting a chat decision. This includes repair, dismissal, withdrawal and replacement when available. No extra evidence is required. `use my text` requires the literal replacement title as `--title` data, which the existing publication gate vets. The calling chat, open record and offered choice are checked; existing consumers and transition checks apply the answer. |
| `magi task control abandon <full run id>` | terminal, on the owner's request: the shared liveness judge runs under the owner lock and only a proven-dead driver is abandoned; a Live or Unknown driver is refused |

Windows の実 sandbox の限定チェックは認証済み CLI が必要。PowerShell で
`$env:RUSTUP_TOOLCHAIN = "stable"` を設定し、
`cargo test --locked --test chat_control windows_sandboxed_chat_controls_without_direct_store_writes -- --ignored` を実行する。
自身の task の保留が成功し、queue 内の検証用ファイルへの直接書込みが拒否されることを確認する。
通常の子プロセス往復は `windows_chat_controls_through_real_cli_child` が検証する。

Merging stays behind the approval gate. Task decisions now arrive as free text
in the associated chat; legacy non-task Questions remain available.

## When an agent needs you

```sh
magi ask --summary "Which storage backend?" --detail "Context and recommendation"
```

From a task seat this posts free text to the task's chat and exits successfully.
The asker finishes its turn; the chat discusses the decision with you and uses
`magi task control` to apply it. No choices, deputy, or waiter are started. A
closed associated chat is reopened; a task with no chat gets a new Solo chat.
The daemon delivers the persisted message even after a restart.

The remainder of this section describes the retained legacy workflow for
questions without an associated task. Those questions block and return an
answer on the asker's stdout, and `magi answer` remains available for them.

A question is attributed to the seat that asked it — `run 9fb7 · node implement
· seat impl-A` — because "who wants to know" is the first thing you need in
order to answer. Runs blocked on an unanswered question are marked as such in
the runs list: a parked run consumes nothing and progresses never, so being
noticed is the only thing that moves it.

### Asking back

Answering isn't the only move. If the question doesn't make sense yet, say so
instead of guessing at an answer:

```sh
magi answer ab12 --say "why not Postgres, it's already a dependency?"
```

(the phone's question card has the same "ask back" box). `magi ask` on the
agent's side returns at once — exit code 0, your words on stdout — and the
agent replies on the same question rather than starting a new one it would
have no context for:

```sh
magi ask --thread ab12 --summary "Postgres needs a server to run; this is a CLI tool" --choice SQLite
```

That appends the reply and waits again. The question never leaves the card it
started on — the phone shows both turns stacked under the original summary —
and it counts as one open question throughout, however many times you go back
and forth. The one thing that changes: while your last word is waiting on the
agent, the phone locks the answer buttons and says so, because there is
nothing to decide until it replies. You won't be paged again for a reply that
lands within five minutes of your own message — long enough to mean "still
reading" — but a slower one still notifies, in case you stepped away.

Set `[notify] command` to be told out of band:

```toml
[notify]
command = ["ntfy", "publish", "magi", "{summary} — {url}"]
```

`{summary}`, `{run}` and `{url}` are substituted into the argv, never into a
shell string, so a question containing `; rm -rf` stays one argument. `{url}`
comes from `MAGI_WEB_URL`, which `magi web` prints at startup — a run cannot
discover the address another process bound. Unless the configured URL already
has a fragment, questions link to Questions and notices link to Notifications.
Question notifications identify the question and how to answer it; a notice
has no reply of its own. Related open questions have a separate response link
in the notification centre. A notification that fails is logged
and ignored: a broken webhook is not a reason to throw away an implementation.

Attention reports (blocked/stopped runs, held tasks, disk holds, release bump
failures and conductor updates) are delivered as free text to the related task's
chat. Delivery reuses task-decision routing, including reopening closed chats,
chatter agent selection, default persona and Solo. Runs without a task get a
persistent run conversation; global reports go to the home's **operations chat**
(`notice-operations`), using the first daemon repository context.

Recognized disk-capacity machine holds are automatically monitored, including
while other tasks run. Capacity and output reservations are rechecked at most
once per minute per task; pressure and failed measurements spend no attempts or
agent budget and create no triage questions. After admission succeeds, the same
task queues again with its retained run and approval evidence preserved.
Untouched automatic disk triage questions from older versions are superseded
without an owner answer. Manual holds, owner replies or discussion, unrelated
approvals and ambiguous old records still require explicit resolution; the task
chat explains these exceptions while eligible tasks continue recovering.

On Windows, live free-space checks use `GetDiskFreeSpaceExW` directly and report
bytes available to the caller (including quotas), without starting PowerShell
for each health request. Recursive directory sizes refresh separately; health
can return unknown sizes while that scan is still running. Drive and verbatim
drive paths retain their existing support; UNC shares remain unsupported.

Triage displays use saved question status, not migration's execution-only
unanswered projection. An answered question is history, even while its decision
still needs application or confirmation in Pending decisions. Applied answers
are never replayed. After “not yet”, the task stays manually held; after seven
untouched days, triage can file a fresh question with resume, keep-held and
discard choices, preserving the manual-hold labels “再開する / まだ止めておく”.
To change course immediately, use `magi task release <id>` or `magi task rm <id>`
(their existing safety checks still apply). `magi task show` displays these
commands for holds whose reason contains `[triage:`. Do not answer the consumed
question again.

The notification store is a durable outbox. The daemon coalesces queued reports
per chat, checks whether the cause cleared, and suppresses reports already
covered by a related question or posted completion report. Read/dismissed legacy
history does not replay; unread history is reconciled. Unavailable evidence or a
failed delivery stays pending for retry. The bell/list remains a compatibility
view for these pending and legacy records. Delivery marks reports read.

Every automatic delivery can spend a chat turn. Keys name kind + subject, never
prose: repeated wording changes update evidence without another turn. A newer
cause or severity escalation can page again. Legacy history without a cause
timestamp pages when a new run pass starts after its saved last raise. Persisted
delivery identities distinguish recurrences after history pruning, while chat
receipts make interrupted outbox acknowledgements safe to retry. Reports cannot start an unsent owner draft
or count as owner approval. The chat investigates and summarizes; actions require
an owner's request and the supported `magi task control` commands.

The same page decision also fires `[notify]` once for a new cause or escalation,
with the notice message as `{summary}` and its linked run as `{run}` (empty
otherwise). A question covering that cause suppresses the second page. Release
bump failures use this same decision rather than a separate webhook.

A placeholder is replaced verbatim inside one argv element: nothing escapes it
for JSON or anything else. For a Discord webhook, a naive
`-d '{"content":"{summary}"}'` breaks on a summary containing a quote or a
newline, so build the body in a wrapper that takes the summary as an argument:

```sh
#!/bin/sh
# discord-notify.sh <summary> - Discord rejects content over 2000 characters
body=$(jq -n --arg content "$1" '{content: $content}') || exit 1
exec curl -sS -H 'Content-Type: application/json' -d "$body" "$DISCORD_WEBHOOK_URL"
```

```toml
[notify]
command = ["/path/to/discord-notify.sh", "{summary}"]
```

`curl --form-string "content={summary}"` also avoids hand-written JSON (unlike
`-F`, it never reads a file for a value starting with `@` or `<`); that form
has not been verified against Discord here.

## Landing it

With `merge = "pr"`, magi opens the pull request and then keeps going: watches
the checks, reads the review comments — human and bot — runs a fix round when
either is unhappy, pushes, and asks you to merge when they are happy.

```toml
[graph]
land = true            # default: take over the watching
land_approval = true   # default: never merge without being asked
land_rounds = 4
```

**Both are on by default, and that pair is the point.** `land` takes over the
watching an operator would otherwise do by hand; `land_approval` keeps the
irreversible step a human decision. An unattended merge needs both flipped, and
that has to be chosen deliberately twice.

It **never force-merges**: out of rounds leaves the pull request open with a
comment saying what is still failing, and `checks: unknown` — no signal at all —
never merges either.

**A branch the base moved under is rebased, not fixed.** A competition that
runs for two hours against a repository merging pull requests all day will
conflict on the way in, and that is arithmetic rather than a defect. magi
rebases the winner onto the base *as the remote has it* and force-pushes with
a lease. A rebase that does not apply is a decision rather than a chore: it
stops and hands over what git said.

Scratch checkout preparation failures stop resumably as infrastructure errors,
with Git's command, exit status and diagnostic preserved. They do not spend a
base-sync or landing-sync attempt or start a conflict-fixer round. Preparation
uses conventional Windows path arguments even when the state directory is
canonicalized; the winner branch may remain checked out in its owned worktree.
An existing interrupted rebase and its saved reservation are reused on resume.

A pull request opened a second ago has no checks yet, and "not yet" is
indistinguishable from "this repository has no CI". So magi waits three minutes
for the checks to appear before believing there are none. Whatever it then
decides, a run that got as far as opening a pull request is never re-competed:
the task is **held** with the reason, because the implementation exists and is
waiting on CI or on you. Retrying would race a second branch against your open
pull request and spend the whole competition budget again.

### Release-bump checkout diagnostics

Release bump creation and pending-release escalation use the same existing-branch
checkout helper. Canonical Windows paths are converted through `git::path_arg`
before Git receives them; branch creation still starts from the fetched remote
base, independently of a detached primary checkout. Failed attempts remove only
their own unpublished branch under the existing ownership checks.

The run's `release_bump.problem` retains the complete scrubbed error chain,
including Git's command, exit status and full stderr (stdout when stderr is empty).
This uses the unchanged shared Git error format. Short attention notices prefer
the first `fatal:` or `error:` line; open the linked run for full details.

Verification: Git for Windows 2.55.0 reproduced exit 128 for an existing branch
checked out to a verbatim (`\\?\`) destination: stderr began with `Preparing
worktree` and continued with `fatal: could not create leading directories ...
Invalid argument`. The same destination in conventional spelling succeeded
without changing the branch or repository. A standalone detached Git repository
was sufficient; jj was not required to reproduce it.
`RUSTUP_TOOLCHAIN=stable cargo test --locked --lib bump::tests::` covers canonical
checkout paths (including spaces), remote-base contents, cleanup, and multiline
diagnostics surviving failure reporting and run serialization.

### Release bumps for repositories without a root `Cargo.toml`

After a merge, magi opens a `chore/release-vX.Y.Z` pull request that raises the
version; the repository's own `auto-tag.yml` then tags and `release.yml`
publishes. By default magi reads and rewrites the root `Cargo.toml`. A Tauri
application such as `yukimemi/shun` keeps it under `src-tauri/` and repeats the
version in `package.json` and `tauri.conf.json`, so name the files in the
repository's `magi.toml`:

```toml
[release]
version_files = [
  { path = "src-tauri/Cargo.toml", kind = "cargo" },
  { path = "package.json", kind = "json" },
  { path = "src-tauri/tauri.conf.json", kind = "json" },
]
```

- **Nothing is detected.** The first entry is the version of record and must be
  the `Cargo.toml` that `auto-tag.yml` reads. The others are rewritten to the
  same version (one string replaced, formatting kept). The `Cargo.lock` beside
  the first entry follows, edited as text. `package-lock.json` is not touched.
- Paths are relative to the repository root; absolute paths, `..` and symlinks
  that leave the repository are refused.
- **A bump that does not happen says so.** The run records a `skipped` reason,
  shown as `SKIPPED` in `magi show` and the web run page, and never reads as a
  finished release. Skips: no version of record on the base branch (with an
  `auto-tag.yml` there, you are also paged and pointed at `version_files`), the
  declared files disagreeing on the version, the merged change already raising
  the version itself (the repository's auto-tag releases it; no duplicate PR),
  and a change touching only the release files.
- The bump PR, automerge or the owner approval gate (`land_approval`, local
  mode) and the repository's own tagging are unchanged: magi never tags by hand.

## Project conventions in the prompts

```toml
[prompts]
all = "This repo uses jj, not git. Never run `git commit`."
review = "Ignore formatting; a hook owns it."
```

Appended to the node prompts, under a heading of their own — **never merged
into them**. The built-in prompts carry the invariants the competition rests
on: a judging prompt names no authors, structured answers arrive as one fenced
`json` block, judges are told not to speculate about authorship. A config that
could *replace* a prompt would let a typo un-blind the panel, and the symptom
would be "the judges got worse" rather than an error.

Repository-wide context belongs in `AGENTS.md`, which every agent already reads
from the checkout. These fields are for what a *magi node* needs to know and a
repository file cannot say.

## The phone UI

```sh
magi web                      # http://100.x.y.z:7878
```

The same runs, the same queue, from a phone. `--bind auto` (the default) finds
the machine's Tailscale address and serves there; with no Tailscale it falls
back to loopback and says so.

**There is no authentication. The tailnet is the security boundary.** That is a
deliberate choice for a single-operator tool on a private network, and it is the
reason the default bind is not `0.0.0.0`.

It is still one binary. The interface is three files compiled in with
`include_str!` — no JavaScript toolchain, no CDN, no remote font, nothing
fetched at runtime. `cargo install magi-cli` gives you the phone UI too.

You can watch runs, read the full report, browse the queue, hold and release
tasks, talk new work through in Chat, and delete a task or a finished run that
is no longer wanted. Deletion is guarded rather than hidden: a task the
daemon is holding a claim on, and a run a live daemon is working on right now,
are refused with the reason. So is any run whose candidate worktrees have not
been folded — that is the guard that keeps "delete" meaning "remove a record"
rather than "throw away a worktree". A run left unfinished by a killed daemon
is a leftover, not work in progress, and can be removed once it is folded.

The run's **Report** tab opens as collapsible cards, with the tally first and
separate candidate-choice and review-vote badges. Review approvals are green,
approvals with findings yellow, and rejections red; missing answers never count
as approval. Reasoning uses Markdown, while raw command output and diffs stay
literal and collapsed. Recovery, startup, merge repair and release execution
evidence remain available in the cards. **Raw** shows the terminal-style report;
its **Wrap** toggle is unchanged.

**A stalled run can be folded and resumed from the phone.** Those are the two
halves of "this run is in the way", and they are opposites, so the run's page
offers both and says so:

- **Resume** carries the run on from where it stopped, re-asking only the
  seats whose absence collapsed the panel. The candidates are already built
  and paid for; the alternative an operator actually had was releasing the
  task, which competes three fresh implementations against work that exists.
  It answers **202** and runs in the background — a resume takes minutes, and
  a phone that locks mid-request must not lose it.
- **Fold** removes the run's worktrees and branches, which is what the delete
  button is waiting for, and is where the disk goes: three finished runs here
  were holding 53 GB. Folding a run makes it unresumable, which the
  confirmation says in as many words.

Both are refused while a live daemon is working on that run. A resume is also
refused while the loop is running *at all*, not merely on that run: magi runs
one competition at a time on purpose, and a tap that quietly started a second
graph would double the quota burn for no extra throughput.

Before this the delete button greyed itself out and said "Run `magi fold`
first" — a phone being told to open a terminal, in the one product whose point
is that it does not need one.

**Update & restart, from the phone.** One tap arms it, the second installs the
newest release and replaces the web and scheduler processes. **Running work does
not park, restart, or wait for a graph node to finish.**

The same binary has three process roles:

- `magi web` serves the screen and API. Its Start/Stop controls operate an
  independent scheduler, including one started by an earlier web process.
- `magi serve` dispatches the queue and manages ordinary, urgent and
  decision-only lanes. On restart it reconstructs occupied slots from live
  worker reservations, rather than starting those tasks again.
- Independent workers own task claims, graph execution leases, Chat sessions,
  deputy turns and finite maintenance operations until their outcomes are saved.
  A worker survives its launching web, scheduler or following CLI exiting.

During an upgrade:

1. `kaishin` replaces the installed executable.
2. The scheduler stops claiming work and is replaced. Existing task, Chat and
   maintenance workers continue on their immutable executable generations.
3. The web closes admission briefly and finishes only outstanding
   persistence-to-reservation handoffs, not agent invocations.
4. The listener is released before the successor web starts on the same address.
   The browser reconnects; new work uses the new executable.

Finishing an old worker needs no ownership transfer, new run, extra pass or
attempt refund. Its existing owner saves the result normally. Ordinary
concurrency and the separate urgent lane remain bounded across scheduler
replacement. Standalone CLI executions remain outside the scheduler's lanes.

External supervisors can still terminate an entire process container. On Windows,
a worker requests breakaway only when the host Job Object permits it; otherwise
it retains that job's restrictions. Configure the supervisor to preserve worker
containers when restarting only the web or scheduler.

Short ownership-maintenance transactions are awaited at execution boundaries
using the run's existing resource-wait budget, not an agent's runtime budget.
An ordinary maintenance pass must not turn a live task into an immediate hold.

**Stop and park are different.** Stop promptly stops the scheduler from claiming
new work; active workers continue. **Park at the next step** explicitly asks
queue-owned task workers to checkpoint at a graph boundary and leave their runs
resumable. A park refunds its attempt, but an update does not need one.
Historical runs already parked by an older binary upgrade keep their existing
resume ordering.

**First migration:** an older embedded scheduler cannot be extracted from its
process while running. Finish or park that legacy scheduler once before starting
the independent scheduler. A live legacy process is protected even when its
heartbeat is stale. This limitation does not apply to later worker-based updates.

**Local execution evidence:** `<magi-home>/workers/jobs/<id>/` contains active
reservations and `worker.log`; finished records move to `workers/results/<id>/`.
The most recent 256 finished records are retained. Content-addressed executables
live under `workers/generations/<sha256>/` and are deliberately retained, so an
old worker's later helper commands cannot switch to a newly installed binary.
Interrupted snapshot copies are reclaimed from staging paths only. On Windows,
cleanup clears their readonly attribute without changing retained executables.
Do not remove a generation while its workers are running. Health and the loop
strip show active worker versions separately from the web version; worker
configuration payloads and command output are not exposed by Health.

If a worker cannot start or acknowledge startup, dispatch stops and a notification
records the failure. An uncertain startup reservation stays protected and may
still complete; the scheduler does not repeatedly reserve the same task or spend
agent attempts retrying it. Already-running workers are not cancelled.

`GET /api/loop` reports scheduler ownership; `POST /api/loop
{"running": true|false}` starts or stops it, and `"park": true` requests an
explicit queue-worker park. Accepted Chat submissions return **202** after their
durable handoff, before the agent answers. Conversation transcripts and queued
drafts remain readable throughout process replacement.

Every list is ordered by creation, never by last activity. A list that reorders
itself while you are reading it moves the row out from under your thumb.

## Configuration

Config files are TOML rendered by
[teravars](https://github.com/yukimemi/teravars), and they **deep-merge in
increasing precedence**:

```text
<config_dir>/magi/config.toml   <   <repo>/.magi/config.toml   <   <repo>/magi.toml
```

That split exists because the roster is a *machine* fact — which CLIs and which
plans you pay for — while the gate is a *repository* fact (`cargo make check`
here, `pnpm test` there). Declare the roster once per machine and let each repo
state only what is its own. `--config <path>` uses that single file instead.
With no config at all, magi builds a roster from the agent CLIs on `PATH`.

Inside a config file you have `[vars]`, `{{ env.NAME }}`, `{{ system.os }}`,
`{{ repo }}`, `{{ repo_name }}`, and `include = [...]`:

```toml
[vars]
cache = "{{ env.MAGI_CACHE | default(value='/tmp') }}"

[verify]
gate = ["CARGO_TARGET_DIR={{ vars.cache }}/magi-target cargo make check"]
```

One trap, not two: teravars renders the raw text before TOML unescaping, so use
single quotes inside the braces (`value='/tmp'`, never `value=\"/tmp\"`).
Comments used to be the other one — since teravars 0.2.2 they are stripped
before Tera renders, so a comment may quote `{{ ... }}` or `{% ... %}` freely.

**Tables merge; arrays do not.** teravars appends arrays when it merges layers,
which is wrong for every array magi has: `implementers` is an ordered list of
seats, `verify.gate` is the commands to run, `notify.command` is an argv.
Concatenating two of those produces something nobody wrote — three
implementers from a machine's two and a repository's one, or an argv of
`["ntfy", "publish", "curl", "-X"]`.

So magi refuses it. Declare any given array in **exactly one layer**: either
the machine states the roster and repositories override only scalars, or a
repository states its own. Naming the same array in two layers is an error that
names both files, rather than a roster you did not ask for and are paying for.
`magi doctor` prints what actually resolved.

It also names the states nothing will move on its own: tasks **held** for a
person, and tasks left **running** by a daemon that is no longer alive. The
second is the one worth having a line for — the loop only ever offers itself
runnable tasks, and `running` is not one, so a competition interrupted by a
killed daemon leaves its task sitting there forever while the summary counts
it as work in progress.

The full surface:

```toml
[[agents]]
id = "opus"
kind = "claude"        # claude | opencode | antigravity | codex | command
model = "opus"
# max_turn_secs = 300   # optional cap per CLI invocation, including resumed turns

[[agents]]
id = "sonnet"
kind = "claude"
model = "sonnet"

[[agents]]
id = "opencode"
kind = "opencode"

# Leave a role empty to rotate through the roster. The judge seats are rotated
# by one, so judge i is never the author of candidate i.
[roles]
implementers = ["opus", "sonnet", "opencode"]
judges = ["sonnet", "opencode", "opus"]
reviewers = ["opus", "opencode"]
# fixer defaults to the winner's own author, continuing its own conversation.
# chatter is who Chat asks; unset picks a claude seat, else the first
# runnable agent in roster order. Name one explicitly if that agent is also a
# judge seat — Chat is opened far more often than any single competition and
# would otherwise compete with that judge for the same account.
# language_judge = "jev"  # kind = "command" wrapper deciding if PR text is English; unset keeps the built-in heuristics
# "jev" is an example name for such a wrapper, not a built-in agent. When unset,
# or when the call fails, times out or returns an unparsable reply, the PR text
# guard falls back to the built-in heuristics.

[graph]
implementers = 3                # default 1 (solo); 2+ runs a blind competition
judges = 3
deliberate_rounds = 1
reviewers = 3
review_rounds = 6
incomplete_review = "block"  # block | warn — a round a seat never answered in
rerun_failed_e2e = true        # run a failed verify.e2e once more on the same commit; a pass is a recorded, filed flake (see "The review loop")
max_parallel = 4
language = "en"          # prose language for the agents; "ja" etc.
github_language = "en"   # language of PR / issue titles, bodies and GitHub comments; anything but English drops the English-only check (commits stay English)
sessions = true
timeout_implement = 3600
# A re-ask that only has to restate an answer the seat already worked out gets
# a quarter of these budgets, not the whole one again.
worktree_root = '{{ home() }}/wt/magi'   # optional; see path notes under [repos]

[blind]
commit_msg_hook = true
on_leak = "warn"         # warn | redact | fail
# seed = 42              # reproduce a run's label assignment

[verify]
# build_cache = "shared" # default; "isolated" gives each linked checkout its own target
# Run once per review round in the winner's worktree; failures are fed back to
# the fixer. This is the "real machine" leg of the review.
e2e = ["cargo test --locked"]
# Final gate. Every command must exit 0 before a merge is attempted.
gate = ["cargo make check"]
# Mechanical fixers (formatters) run on the winner before e2e and before the
# gate; changes become one commit. A failing command only warns. Uses
# timeout_verify. Must be idempotent.
pre_gate = ["cargo fmt --all"]

[worktree]
# Prepared in order right after magi creates a worktree, before any agent or
# verify command touches it (see "Worktree setup" below).
setup = [
  { copy = ".env.example -> .env" },
  { copy = ".env.local", optional = true },
  { run = "pnpm install --frozen-lockfile", timeout_secs = 900 },
]

[merge]
mode = "none"            # none | local | pr
# ci = "expected"       # expected | none

[update]
mode = "notify"          # off | notify | install
# interval = "24h"
# auto_restart = false     # magi web only: update and restart when idle

[repos]
# Where `magi repos` (and `GET /api/repos`) look for other local checkouts.
# `roots` is an array, so it follows the same "declare it in exactly one
# layer" rule as `[[agents]]` - and since which checkouts exist on disk is a
# machine fact rather than a repository one, that layer is almost always the
# machine config.
# The root is the directory above <host>, e.g. src above github.com.
# These roots and worktree_root do not expand ~; use {{ home() }} instead.
# Single quotes keep home()'s raw Windows backslashes from being TOML escapes.
roots = ['{{ home() }}/src']   # scanned as <root>/<host>/<owner>/<repo>
auto_clone = false             # opt in to acquiring explicit owner/repo misses
# clone_command = ["shoka", "clone", "{repo}"]
scan_ttl = 86400                # seconds a scan is trusted before re-scanning
fetch_interval = 600            # seconds between `git fetch origin` in every checkout (0 = off)
```

With `[repos] auto_clone = true`, `magi task add`, `magi run`, `magi review`,
and tasks filed from chat can acquire a missing explicit `owner/repo`. Local
matches are checked first; ambiguous matches still fail. Bare names never
trigger network access. The default is `false` to keep unattended filing from
acquiring repositories unless explicitly enabled. Read-only listing and stats
never acquire repositories.

Acquisition validates GitHub names and confirms access using
`gh repo view https://github.com/owner/repo --json nameWithOwner`.
Redirects to a different name are rejected (case-only differences are accepted).
It then runs
`gh repo clone https://github.com/{repo}.git {dest}` by default, so `GH_HOST`
cannot redirect these gh commands to another host. `gh` must be installed and
authenticated.
`clone_command` is an argv array with `{repo}`, `{owner}`, `{name}`, and `{dest}`
placeholders, passed directly without a shell. Declare it in one config layer;
arrays are never concatenated into a command. The destination must be
`<first root>/github.com/<owner>/<name>`; an existing destination is never
overwritten. For the `shoka` example above, configure shoka's own clone root to
match the first root. Commands that fail or create a checkout elsewhere report
an error; magi does not switch to another repository. Simultaneous acquisitions
under the same root are serialized and recheck local matches. An incomplete
acquisition is hidden from discovery and refused by direct path resolution.
A sibling `.magi-clone@<name>` marker is removed after successful checkout
validation, or after a completed failure that leaves no destination, allowing a
retry. If a partial checkout remains or acquisition is interrupted, inspect and
repair or remove the partial checkout before manually removing its marker and
retrying. After acquisition, repository configuration still comes from the
remote base commit.

`mode = "none"` is the default on purpose: magi prints the merge command and
stops. It does not touch your base branch unless you ask it to.

For a repository without CI, set `[merge] ci = "none"` in its repository
config. This explicitly ignores every check status, including third-party
statuses, and skips waiting for an empty rollup. Conflicts, unresolved review
comments, head verification, and the configured approval gates still apply.
The default `"expected"` waits for readable checks and refuses to merge when
they remain unreadable. Local release mode does not change this default.
Repository config is read from the remote base branch, so land the setting
there before using it. Avoid putting `ci = "none"` in machine config: it would
ignore CI across repositories inheriting that setting. Restore `"expected"`
when CI is introduced.

`[update] auto_restart = true` opts `magi web` into the same update-and-restart
handover as the UI's **Update & restart** button. It defaults to `false`.
Checks use `interval` (default `24h`, minimum `1m`); configuration is reloaded
on each poll (every 30 seconds to 15 minutes). Cached releases can trigger an
update without another network check. `mode = "off"` and `MAGI_NO_AUTOUPDATE`
disable it. `mode = "install"` keeps its existing CLI startup behavior.

Automatic requests wait indefinitely for no active runs, resumes, in-process
chat turns, or on-disk chat leases. They do not park active runs. If work races
the idle check, the handover waits for the run to finish and for chats without
a timeout before releasing the listener and starting the successor. A loop
owned by another process prevents the update. Standalone `magi serve` cannot
perform this restart; run `magi web` and start its loop from the UI instead.

Deferrals and automatic triggers appear as `auto-upgrade:` entries in the
upgrade log; `/api/health` includes the progress `trigger` (`manual` or `auto`).
A failed automatic release tag is skipped for this process's lifetime; a
different tag or a process restart allows another attempt. Failed-tag memory
is not persisted. Config errors defer automatic updates. Older binaries reject
the new `auto_restart` key, so upgrade them before adding it to shared config.

An arbitrary agent, or a deterministic stub for testing:

```toml
[[agents]]
id = "mock"
kind = "command"
command = ["sh", "./mock-agent.sh"]   # {prompt_file} {cwd} {label} {session}
```

An agent's optional `max_turn_secs` caps each invocation at the smaller of this
limit and the caller's remaining budget. Unset leaves the caller's timeout
unchanged. Use it to move on sooner from a slow CLI in a fallback chain while
leaving the successor its own budget. It also applies to direct calls outside
the graph; it does not reset or extend a node's budget. Zero times out immediately.

`command` agents also receive `MAGI_SEAT`, `MAGI_TURN`, `MAGI_PROMPT_FILE` and
`MAGI_ALLOW_WRITE` in the environment.

New `kind = "omp"` sessions use a separate session directory per conversation
under `$MAGI_HOME/agent-sessions/omp/`, not the operator's normal omp history.
Use an omp release that supports `--session-dir`. Authentication, settings,
models, extensions and tools still resolve normally. Existing sessions resume
from their original history and remain visible there. Claude Code, Codex,
OpenCode and Antigravity session storage is unchanged. See
[omp session storage](docs/seat-write-scope.md#omp-session-storage) for backup
and recovery considerations.

### Standing chat recovery (`[talk]`)

Set this in `<config_dir>/magi/config.toml` to opt in. It defaults to `false`;
any value in a repository layer or other config file is ignored.

```toml
[talk]
standing_authorization = true
```

This supersedes “automatic reports authorize nothing” only for the recovery
allowlist. A task outcome, attention report, linked watch result, or goal wake
can authorize the chat to resume retained work, retry unchanged work, rerun
failed checks, release a machine hold after verifying the cause is gone, grant
one bounded repair round, file a separate fix for a verified independent
failure, or register/update a goal for the reported task. The task must have
been filed by that chat, have that conversation as its own chat (`Task::chat`,
which only the launcher writes, so every task's watching chat counts), or be
part of an active goal there. A watch result
must be linked to such a goal. Report prose is data, not authority. A goal the
owner established keeps the authority the owner gave it; this setting does not
narrow it.

The chat uses `magi task control --standing-task <task> --evidence <reason>`
with the existing recovery command, or `magi task add --standing-task <task>
--evidence <reason> --solo --repo <repo>` for a separate fix. The launcher
records the operation, evidence, and outcome in the transcript. A repeat
of the same cause asks instead of acting again, even after a restart; registering
or updating the goal does not count as that one action. An
uncertain outcome is not replayed. Recovery does not reset task attempts,
review rounds, or base synchronization budgets.

Fresh owner input is still required for landing decisions and merge approval,
abandonment, removal, reassignment, replacing or discarding retained work,
`--force`, clearing a manual hold, and configuration changes. Sandbox grants
do not change. With `land_approval` enabled, silence remains a hold.

### External repository coordination

Coordination is disabled unless `[coordination]` is configured in the machine
config or a repository config layer. All three keys are required after normal
layer merging and template rendering; unknown keys are rejected. For example,
replace these placeholder values with the external updater's protocol:

```toml
[coordination]
contract_file = "example-updater.contract"
contract_token = "example-protocol-v1"
lock_file = "example-updater.lock"
```

`contract_file` and `lock_file` are plain file names inside the Git common
directory: empty or whitespace-only names, `.`, any `..`, separators (`/` or
`\`), NUL, absolute paths and drive prefixes are rejected. `contract_token`
must be nonempty, single-line, and have no surrounding whitespace. The trimmed
contract file contents must equal that token. A missing contract leaves the
repository unregistered; an unreadable or mismatched contract fails closed.
Without this section no contract is inspected and no coordination lock is taken.

The launcher shares one exclusive OS handle among its readers, serializes
editors fairly, and holds reader locks until their processes terminate.
External contention uses `[graph] timeout_resource_wait` and remains an
infrastructure resource wait. See [seat write scope](docs/seat-write-scope.md).
Operators relying on the former built-in file names must set all three keys in
their machine config to keep coordinating with their external updater.

### Worktree setup

magi creates its worktrees with plain `git worktree add` and does not read
`renri.toml`, so a copied `.env` or a one-off bootstrap that `renri add` would
have produced is missing there. `[worktree] setup` is an ordered list of steps
run in each new worktree:

- `{ copy = "src -> dst" }` (or `{ copy = "path" }`) copies from the **primary
  checkout's working tree** (an absolute source is allowed; this is not the
  `origin/main` commit the rest of the config is read from). It never
  overwrites a file that already exists in the worktree, and a missing source is
  an error unless the step has `optional = true`. `dst` must stay inside the
  worktree (no absolute path, no `..`, nothing under `.git`).
- `{ run = "..." }` goes through the configured shell with the worktree as cwd,
  `timeout_secs` (default `timeout_verify`) and stdin closed. `MAGI_RUN` and
  `MAGI_NODE` are removed from its environment so nothing seat-shaped leaks.

A failing step (copy error, non-zero exit, timeout) fails that worktree with the
step number, the command and the tail of its output; the run is `Blocked`, never
carried on. The key is an array, so it is declared in exactly one layer; the
default is empty and changes nothing.

Covered worktrees: implementer candidates (hence the winner/verify worktree,
which is the candidate itself and is not set up twice), judge and advisor
seats, reviewer seats (set up again every round, because the reset wipes them),
the review-takeover checkout and the operator-fix checkout. **Not covered:**
the throwaway worktrees used for rebases and local releases; a release command
prepares its own checkout.

Things to know:

- Setup must not edit tracked files; one that does fails the worktree. For the
  same reason it is the wrong place for things like `kata apply`: every
  candidate would carry the same diff. That is explicitly out of scope.
- What setup leaves untracked is hidden from `git add` through a per-worktree
  `core.excludesFile`, and magi's rescue commits skip it too, so a copied `.env`
  never lands in a candidate branch.
- The cost is paid once per seat (and per review round), so prefer light
  commands, and write `run` steps to be safe to repeat.

### Project cleanup before destructive cleaning

Some tool caches need their own cleanup command: for example Go module
cache directories can be read-only even when owned by the current user.
Configure optional, ordered commands in one configuration layer:

```toml
[worktree]
pre_clean = [
  { run = 'GOMODCACHE="$PWD/target/nats-identity/cache/mod" go clean -modcache', timeout_secs = 60 },
]
```

This POSIX shell example targets **only the project's explicit worktree-local
GOMODCACHE**. It must match the cache path used by the build. Never omit that
assignment or substitute the user's global Go cache. Nothing in magi detects
Go or changes directory permissions automatically.

Commands use the configured verification shell, stdin closed, and the target
worktree as cwd. `run` is required and nonempty; `timeout_secs` must be positive
and defaults to the verification timeout. Unknown step keys are rejected.
`MAGI_RUN`, `MAGI_NODE` and worker invocation overrides are removed. Configuration
comes from the launcher's pinned upstream base, never from the cleanup target.

For Windows or other shell differences, prefer a tracked project task/script,
for example `{ run = "python scripts/clean-local-go-cache.py", timeout_secs = 60 }`.
A project-owned Python script can use this pattern (Python is an example, not a
magi dependency):

```python
import os
from pathlib import Path
import subprocess

root = Path.cwd().resolve()
cache = root / "target/nats-identity/cache/mod"
resolved = cache.resolve()
if resolved != cache or not resolved.is_relative_to(root):
    raise RuntimeError("local module cache must use its worktree-local path")
if cache.exists():
    subprocess.run(["go", "clean", "-modcache"], check=True,
                   env={**os.environ, "GOMODCACHE": str(resolved)})
```

The script constructs an absolute path, rejects symlink escapes, succeeds if
the cache is already absent, and works without POSIX environment assignments.
Use the same explicit cache path in the project's build task.

| Cleanup path | Runs `pre_clean`? |
| --- | --- |
| Candidate base synchronization, including resumed and fixer-finished synchronization | Yes, in that candidate only |
| Existing reviewer reset for a new review round | Yes, in that reviewer only; before setup is repeated |
| New worktree creation / setup | No |
| `restore_to`, including recursive submodule cleans (`git clean -ffdq`, preserves ignored products) | No |
| Primary checkout, actual foreign checkout, rebase/base-conflict scratch, local release scratch | No |
| Worktree removal, retention, setup rollback | No |
| Low-level Git helpers called without the owned-worktree wrapper | No |

The sequence is reset to the selected commit, run hooks in declaration order,
then `git clean -fdx`. Hooks therefore see scripts from the selected commit.
The first failure, timeout or interruption prevents later hooks and clean;
failures identify the target, purpose and step, with at most 4000 bytes of
output read from the log tail. Attempts are saved before command launch; an
interrupted command retains its temporary output file, whose location is logged.
Timeout and cancellation use the existing process
tree cleanup owner; output reservations, repository coordination and the
pre-clean lock remain held until child processes terminate. A worktree output
lease excludes active borrowers/reclamation; a separate exclusive pre-clean
lock and inherited recursion marker reject nested or concurrent cleanup.
The caller's run driver claim remains responsible for run liveness.

**Hooks must be safe to repeat**, including after partial execution and when a
cache no longer exists. They should clean only disposable worktree-local data.
A hook can still modify files; it is trusted project code, not a sandbox.
With an empty list magi follows its existing Git path without extra subprocesses
or ownership checks. With hooks configured, targets must belong to this run,
share its Git common directory, and reside directly in its worktree root;
linked-worktree status alone does not authorize execution. An owned shadow
worktree used to review a foreign branch remains eligible; the original external
checkout is always excluded. Candidate cleanup never enumerates or resets independent reviewer worktrees.

Synchronization completion is recorded only after hooks and clean succeed.
An interrupted rebase may already have moved the branch while its worktree
still needs synchronization. The existing operation reservation remains
unfinished on cleanup failure. A candidate-local Git metadata marker also records
the cleanup boundary before reset, including legacy synchronization histories
without an operation reservation. The marker records the target HEAD, the
accepted index tree before reset, and the untracked/ignored paths already
scheduled for deletion. Before classifying a resumed branch, magi accepts either
that unchanged old index/tree or the clean target tree. Existing recorded cache
paths may remain: hooks run again to remove them before Git clean. Changed HEAD,
unrecognized tracked edits, or newly introduced untracked/ignored paths stop
recovery for inspection. Hook-created paths that were not present when cleanup
started also require inspection after interruption. Removing the hook
configuration cannot skip the recorded clean. The marker is removed only after
clean succeeds. Older head-only markers lack this evidence and retain their
conservative clean-tree/empty-untracked recovery requirement. No additional
conflict-resolution attempt is introduced by cleanup.

## The review loop

The winner — and only the winner — enters a bounded loop:

1. Each reviewer gets its **own detached worktree** pinned at the exact commit
   under review, so no reviewer can perturb the tree and the fixer never races
   one.
2. `verify.e2e` runs in the winner's worktree. Its output is fed to the fixer.
3. The fixer addresses the blocking findings, or **rejects one with an
   argument** — a rejected finding with a checkable reason is a correct outcome,
   and magi records it as such.
4. Repeat until no blocking finding remains and verification is green, or
   `review_rounds` is exhausted (`blocked`). A round where the fixer produces no
   commit stops the loop instead of spinning on an unchanged tree.

Finding ids (`R2-1-3`) are assigned by magi, never by the agent, because the
fixer's adoption report is keyed by them — that is what makes reviewer precision
measurable rather than self-reported.

**A red e2e is run again before it is believed.** When `verify.e2e` fails with
an ordinary test result (not a build/link failure, a timeout or a resource
block), the failed command runs once more on the same commit, in the same
worktree, under the same build-cache lease and with its own full
`timeout_verify`; no review round, fix round, task attempt or repair budget is
spent. This applies wherever `verify.e2e` decides something: the per-round leg,
the deferred catch-up, the current-head check (before and after the gate, after
a base sync, at publication) and the gate-repair check. A verification runs at
most three times for one decision (the existing build/link retry, then this
rerun).

- **The second run fails:** the failure stands, and the fixer receives the
  second run's output, marked as the output of a command that failed twice.
- **The second run passes:** the head is verified, but the failure is recorded
  as a flake — a `verify` event, `RunState::verify_flakes`, a "flaky
  verification" section in `magi show` and on the web run page, and the round
  reads "e2e green on rerun only", never plain green. magi files one queue task
  per distinct failure (`Source::Agent`, node `flake`) asking for the root cause
  to be fixed rather than the test loosened or retried away. A failure is
  identified by its normalised failure lines (numbers, hashes and temporary
  directory names removed, sorted), so ten runs hitting the same flaky test leave
  one task; a task that is already `done` does not cover a recurrence. A filing
  failure is an event, never a run failure.

`[graph] rerun_failed_e2e = false` turns the rerun off: the first result decides,
as before.

**A seat that never answered is not a seat that found nothing.** Every round
records how many reviewers it expected against how many actually came back, so
a timeout, a crash or an unparsable reply cannot pass for a clean pass. `magi
show` labels such a round `incomplete` and names the seats that went missing,
`magi stats` carries a per-seat timeout rate, and by default
(`graph.incomplete_review = "block"`) the round is never treated as clean: with
nothing raised to fix, it is re-reviewed, and if the round budget runs out
while the panel is still short the run ends `blocked` rather than `ready`. Set
`incomplete_review = "warn"` to let the round gate on whatever did answer — the
gap stays in the report either way.

`magi run` and `magi review` **exit non-zero when the run ends `blocked` or
`stalled`**, after printing the report — a script or CI step that only reads
the exit code must not take "nothing panicked" for "the change is reviewed".
The one exception is a run that left a pull request open: that is a hand-off
to a human, not a failure, and exits 0.

## Statistics

`magi stats` aggregates every run on disk:

- **implementation** — win rate per agent, and how often an agent produced
  nothing at all.
- **review** — findings per round, precision (adopted / submitted), unique
  find rate (findings no other reviewer in the same round raised, matched by
  normalised title or same file within five lines), and the share of its
  seated rounds a seat never answered in at all.
- **verification** — how often E2E failed while every static review was clean:
  the runtime defects only execution found.

These are a by-product, not a benchmark. Seats rotate, the task distribution is
whatever you happened to ask for, and an agent that drew harder tasks looks
worse. Read them as *relative performance on your workload*.

## Where a run spends its time

Measured on a real run (2 candidates, 2 judges, 1 reviewer, 219 s wall):

| node | wall | spent by |
|---|---|---|
| prep | 2.8 s | git: four worktrees plus the hook |
| implement ×2, parallel | 93.0 s | the slower agent (69 s / 92 s) |
| judge ×2, parallel | 84.6 s | agent latency |
| vote | 9.2 s | agent latency |
| tally / fold / merge | 0.5 s | magi |
| review | 26.1 s | agent latency |
| e2e + gate | 1.6 s | your commands |

magi's own compute was 3.3 s of 219 s. Everything else is the agent CLIs, so the
three levers that matter are:

- **`max_parallel`** — agent processes are network-bound, so raising it is close
  to free. Implement, judge and review run as parallel waves.
- **`deliberate_rounds`** — deliberation is *sequential* by design, because a
  turn has to be able to answer the one before it. Each round costs
  `judges × turn latency`. Set it to `0` to skip arguing and go straight to the
  private vote.
- **`verify.e2e` on a compiled language** — each worktree would otherwise build
  from scratch, which dwarfs every agent call. `verify` commands run through
  `sh -c`, so share the cache:

  ```toml
  e2e = ["CARGO_TARGET_DIR=${TMPDIR:-/tmp}/magi-target cargo test --locked"]
  ```

  Only the winner's worktree runs them, one at a time, so nothing contends on
  cargo's lock.

### Isolated Cargo build outputs

Use `magi run --build-cache isolated`, `magi review <branch> --build-cache isolated`,
or `magi task add --build-cache isolated` to opt in for one task. For new runs,
magi chooses the mode in this order:

1. An explicit task choice (`shared` or `isolated`), including `shared` on
   an urgent task.
2. `isolated` for an urgent task, so its extra slot does not wait on the shared
   cache. This applies only when the repository has a shared cache and its
   verification commands are ones isolated mode can run; otherwise the urgent
   task keeps the configured mode rather than stopping on an unsupported
   command.
3. The layered `[verify] build_cache` setting, which defaults to `shared`.

Use `magi task build-cache <id> shared|isolated|default` while the task is
unclaimed and queued or held. `default` clears the override and restores the
urgent/config rules. `magi task show <id>` and `--json` show the choice for a
new run and its source. Historical tasks retain their shared choice until
changed. A resumed run always uses its saved mode; `magi run --resume` does
not accept `--build-cache`.

Set `[verify] build_cache = "isolated"` in the machine layer to isolate all new
work that inherits that default. This suits machines with disk to spare:
each isolated target holds a full build output.

Each linked checkout generation in isolated mode gets a separate target under
`MAGI_HOME/isolated-builds`. Editing seats and managed verification in that
checkout reuse it; reviewers do not get the path. Git's absolute and relative
linked-worktree registrations are supported.
No outputs go in the source tree. Inspect the run's build mode with `magi show`.
Use `magi cache list` for the actual target paths, owners, and leases. The
usual cache maintenance locks and `[disk] cache_limit_bytes` apply to the isolated
pool independently of the shared cache. Clearing a registered isolated path
keeps its ownership record so a resume can rebuild.
Folding a checkout reclaims its proven, idle isolated outputs under the same
locks. Busy or unproven targets are not reclaimed by fold.

A literal leading `CARGO_TARGET_DIR=…` on a verification command is replaced
by the managed target, including quoted paths with spaces. Simple commands and
`&&` chains made entirely of Cargo invocations are supported through `sh -c`,
`bash -c` or `dash -c`; invoke Cargo by name in every clause. `cargo make`,
`cargo nextest`, `cargo clippy` and `cargo fmt` run with the same managed
Cargo environment. Other compound syntax, dynamic overrides, explicit Cargo
executables, unknown Cargo aliases and output-affecting flags such as
`--target-dir` or `--config` are refused. Trusted setup scripts, tool plugins and
build scripts must not bypass the launcher by replacing `PATH` or invoking
absolute Cargo executables; this is build isolation, not a sandbox.

Isolation trades less waiting on shared outputs for more rebuilding and more
concurrent CPU, memory and disk use. Same-target builds still serialize; registry
and download locks, task/candidate limits, repository coordination, disk
admission, and the existing incremental policy are unchanged.
If isolated setup cannot reserve disk headroom, magi holds the task without
spending an attempt. An archived seat whose setup was refused before it began
can be restored after recovery; a started setup's failure retains its checkout
and checkpoint for inspection. Recovery checks the task's selected output
volume, or the saved run's volume when resuming.


### Disk

`candidates + judges + reviewers` worktrees exist at peak (8 with the defaults).
Judge worktrees are removed as soon as the tally lands, and `magi fold` clears
the rest. On a large repository that is real disk; lower `judges` or point
`worktree_root` at a roomier volume.

State lives in `<data_local>/magi/runs/<id>/` — `run.json` plus every prompt and
raw agent reply under `artifacts/`. `MAGI_HOME` moves it.

## License

MIT

### MAGI message appearance

Automatic task updates, watched-job reports, consult handovers, task posts, and
system notices use the **MAGI** sender name, a gold bubble in both themes, and
a dedicated built-in avatar. Operator sends and conversation persona replies
keep their own names and icons. Older operator records retain their original
attribution; message text alone is not evidence that MAGI wrote them.

Chat agents must route work that outlives their turn to `magi talk watch` or
`magi task add`, never a plain background shell job. A later-report promise
requires a successful command to print a watch or task ID. After a successful
reply, MAGI adds a warning note for explicit English or Japanese promises
without a new registration during that turn (including fallback attempts).
The reply is unchanged; no decision or task is created. Quoted/code examples
are ignored, and unreadable registration evidence suppresses the warning.

In the web **Settings** page, use **MAGI sender icon** to choose an image from
your phone's image picker. Review the preview and tap **Save MAGI icon**, or
**Reset to built-in** to restore the supplied artwork. The choice applies to
all conversations, independently of operator and persona icons, and survives
reloads and server restarts. It is stored atomically as `magi-icon.data` in the
magi home directory; it does not rewrite repository or machine configuration.
The picker resizes images to at most 384 pixels per side. PNG, JPEG, GIF, and
WebP inputs are accepted; uploaded icons are limited to 256 KiB (including the
data URI). Invalid or unavailable saved images fall back to the built-in icon.

### Choosing the next action at the merge gate

The approval card offers these actions (localized for `graph.language = "ja"`):

| Action | Result |
| --- | --- |
| Fix findings and re-review / 指摘を修正して再レビュー | One bounded repair and fresh review on the **same PR, branch, run and task**. Previous findings and gate evidence remain in repair history. A new decision is required; this action never approves merging. |
| Reimplement with selected agent / 選択した agent で再実装 | Select a configured implementer explicitly. The old execution retires and auto-merge is disabled; closure of the old PR must be confirmed before the **same task** starts a new attempt and PR. The original instruction, attachments and review context survive. |
| Hold decision and stop work / 判断を保留して作業を停止 | Leaves the PR open, blocks the run and manually holds the queue task. Stops repair, rebasing and merge work, including when the PR head changed. It is not a request for repair. |
| Withdraw: close PR and end task / 取り下げ | A second confirmation explicitly closes the PR and terminates the task. History remains. Failed or unconfirmed closure holds the task instead of declaring it done. |
| End obsolete approval (no merge; PR unchanged) / 古い承認を終了 | A second confirmation retires a stopped execution and its pending approval, preserving history even when the original queue task is missing. It never contacts the forge, closes a PR, or starts replacement work. Later attempts and completed tasks are unaffected. A live or unknown driver, an existing auto-merge arm, or a conflicting decision refuses dismissal; stop the driver and disable auto-merge first. Use Withdraw when you explicitly intend to close an active PR. |
| Merge this pull request / マージを承認 | A second confirmation approves only the displayed head, including the outstanding findings shown in the review panel. A changed head needs a fresh decision. |

CLI answers use stable tokens, independently of translated button labels:

```sh
magi answer <question-id> --reply 'fix findings and re-review'
magi answer <question-id> --reply 'reimplement:<configured-agent-id>'
magi answer <question-id> --reply hold
magi answer <question-id> --reply 'withdraw: close PR and end task'
magi answer <question-id> --reply 'dismiss: end obsolete approval without changing PR'
magi answer <question-id> --reply merge
```

`merge` and `hold` remain compatible with older cards and CLI clients. Open
legacy cards are extended in place, keeping their question ID and displayed
head. Answered cards retain their choices and decision history.

Dismissal is applied locally while saving the answer; no daemon or original
queue task is required. It is permanent for that execution, unlike Hold.
For the other actions, the daemon resumes the existing parked owner to apply the answer. Answering
alone does not dispatch an agent. Without a running daemon, explicitly resume
the existing owning task/run; do not file a second repair or replacement task.
After an applied hold, explicitly run `magi task release <task-id>` with the
daemon running, or `magi run --resume <run-id>`. This keeps the same run and PR,
retains the old answered card, and parks at a fresh decision card before any
repair, rebase or merge. Resuming does not approve a merge.

The replacement implementer selection is persisted and enforced in both initial
dispatch and implementation fallback. It applies to implementation seats;
reviewers, advisors and repair/fixer roles retain their configured assignments.
A missing or quota-limited selected implementer leaves the task manually held,
without substituting another implementer. Restore availability and explicitly
release the held task to retry. Ambiguous previous-driver ownership or a crash
between minting a replacement and linking it to the queue also holds for manual
inspection rather than starting a concurrent attempt. The run records link the
old question, attempt, PR and replacement attempt/PR.

Question free-text replies require a live recipient or one the running daemon
can automatically recover. The card distinguishes listening, waiting for startup
or restart/capacity, and unavailable recipients. It disables only text submission
when the deputy has exhausted its start budget, is disabled/unavailable, or the
asking seat cannot resume. The running daemon publishes its effective recovery
capacity; editing settings requires restarting it before new capacity becomes
available. Conversational text commands check again before saving; a stale card
cannot submit into a dead thread. Rejected drafts
remain in the input, and earlier saved messages remain in the question history,
marked undelivered when no recipient can read them. Offered decisions (including
free-text answers) and the explicit originating-chat consultation route keep
their existing authorization;
delivery availability never authorizes merging or closing a PR.

Standing chat and deputy consultation leave the card unanswered while discussing
it. When the owner asks in their own words to merge, stop, repair, withdraw or
replace, the chat or deputy records that choice; a merge stays bound to the
displayed head, and a changed head needs a fresh decision. Silence, discussion
and repair never permit a merge.

### Task decisions in chat

Task questions (including `magi ask` from a task seat) are posted as free text
in the task's chat and the asker finishes without waiting. The daemon uses the
task-owned delivery record in `notifications/task-inquiries`, then runs the
existing chat turn; it starts no deputy or waiter. If needed it opens a Solo
chat with the chatter-chain head
and default persona, and records that chat on the task for later messages.
Decision delivery reopens a closed associated chat. Passive completion and
watched-command notifications still skip closed chats.

The chat discusses decisions with the owner and applies them through
`magi task control`. Automatic reports do not authorize new tasks or repository
edits. Merge approval remains default-on and bound to the displayed PR head:
the chat agent presents Merge/Hold buttons by including the full approval ID in
its reply. At the owner's request, the chat agent may also record merge directly
with `magi task control decide`, without any extra evidence.
Buttons remain optional and validate their displayed head. Silence is a hold.
Existing head verification and merge transitions remain in charge. The Question store and legacy non-task
question/deputy/waiter workflows remain available during this migration.
Delivery requires the daemon; pending outbox records survive a restart.

### Pending decisions in task chats

The phone dock and desktop rail include **判断待ち** (Pending decisions), separate
from notifications. Each actionable native inquiry retains its reason, task,
optional run, exact chat inquiry link, lifecycle status and outcome history.
Delivery, opening or reading the chat, ordinary replies and newer messages never
remove an unresolved decision. Informational deliveries do not create items.

Task-scoped `magi ask --summary ... --detail ...` files a native durable inquiry
and exits. Each CLI invocation creates an independent inquiry, even with identical
wording. Use `--request <stable-occurrence-id>` to retry the same post after an
uncertain CLI result; reusing that key preserves the original inquiry and its
lifecycle. Use a different key for a different decision. The scheduler reuses
or reopens the task chat and creates a missing
chat with its configured chatter head, default persona, task repository and Solo
mode. An unsent owner draft remains a draft. The outbox and independent chat
execution workers recover across web and scheduler replacement.

The owner discusses and decides in free text. The chat binds a task/run effect
to the inquiry with `magi task control --decision <inquiry-id> <command>`.
Acceptance, execution and confirmed application are separate states; recording
or queuing an operation is insufficient to clear it. A failed or uncertain
operation remains visible with its error and receipt context. Repeating a request
never blindly replays an effect that might already have happened. A task claim or
pure validation failure is recorded as a proven pre-execution failure: the owner
can retry the same command after fixing the cause or explicitly cancel it with
`settle-decision`. A failed write or uncertain external result retains its receipt
reconciliation requirement. Restart itself performs no retry. Resume requests
remain active until the scheduler observes the owning execution running.

再開 pin を消費するタスク開始保存には、依頼 ID と対象 run の対応も含める。
開始 pass の保存前に worker が終了しても、再起動後の実行へこの対応を引き継ぐ。
タスクが Running になっただけでは解決せず、実行 lease と所有権を取得して
`decision_starts` と開始 pass を永続化したことを確認して解決する。

Task-local hold, release, completion and instruction-retry effects save the exact
command receipt in the same queue write as their transition. Restart recovery
can therefore finish an interrupted decision projection even after the task has
moved to a later state; it does not execute the command again. Repeated inquiry
wording in a later execution pass or owner-decision generation creates a new
pending item while redelivery in the same generation remains deduplicated.

If the owner explicitly settles discussion with no effect remaining necessary,
the chat uses `magi task control settle-decision <id> --reason <reason>`. Add
`--replacement <new-inquiry-id>` to supersede an unanswered inquiry with an
existing active one in the same task chat. Native commands with accepted or
uncertain effects need receipt reconciliation first. For a task-local crash window, the owner can ask
for `magi task control reconcile-decision <id>`: it executes nothing and resolves
only if the exact intended task condition is already durably confirmed. External
merge and check-rerun operations retain their own request-bound receipts. No exact owner phrase, quote fingerprint or button
click is required; silence remains a hold and landing approval remains on by
default.

An imported inquiry with missing ownership can be explicitly settled from any
existing authorized chat using `settle-decision <id> --reason <reason>` when the
owner confirms no effect remains. This assigns neither a task nor a delivery
chat and executes no operation. Its ID and recovery instructions appear in the
Pending decisions list. Native commands with accepted or uncertain effects still
require receipt reconciliation. A successful obsolete-approval dismissal is confirmed by
its durable run checkpoint, including when its task is already done or has moved
to another attempt; it does not require changing that task's later outcome.
release-watch の hold / leave it は、監視終了後にも残す適用済み問い合わせ ID で
照合する。triage の破棄は削除対象のタスクを問い合わせ専用の受領記録へ原子的に
移すため、タスク削除後も再起動時の照合証拠を失わず、その判断を解決できる。

ローカルのリリース承認の hold と、失敗ジョブへの leave it も、効果を保存する
同じ監視状態に問い合わせ ID を記録する。merge / retry / 従来の rerun など、
consumer が完了受領記録を出せない従来型依頼は、結果を確認した所有者が
`settle-decision <id> --reason <reason>` で残る効果がないことを明示的に精算できる。
これは成功受領記録や実行中の操作の取消ではない。元の依頼・回答・不確実な結果の
履歴を残し、精算済みの回答は以後の consumer に実行可能な回答として渡さない。
通常の再照合は操作を繰り返さず、読むことや回答の保存だけで精算されることもない。
実行中の consumer が共有実行権を保持している間は精算を拒否する。
チェック再実行で forge の事前読取りに失敗した場合は、効果未開始として同じ依頼を
再試行できる。開始受領記録を保存した後の失敗は、引き続き照合が必要な不確実な結果として残す。

Existing task-scoped source inquiries are imported under their original delivery
keys, including saved replies without confirmed effects. A saved reply is
historical evidence, never a new owner instruction or approval. Migration posts
no operation and retains unresolved outcomes. Source decision consumers still
remain operational in this foundation stage. Their complete retirement, including
Questions, deputy, waiter, legacy CLI/API/UI and choice-effect consumers, is
explicitly deferred to the subsequent migration task. This stage does not claim
that retirement is complete. Non-task foreground inquiries retain their legacy
answer and wait workflow.

Unreadable saved inquiry files are included in the migration boundary. Their
source identities and errors remain visible in Pending decisions across visits
and restarts, alongside readable items. Restoring a source retries its import
with the original delivery identity. The migration decoder reads history without
repair upgrades or routing writes; importing actionable work still uses the
source adapter described above.

The migration retains its complete source-ID boundary after imports finish.
Saved replies in that boundary remain history, including while awaiting import;
operational readers cannot use them to execute task actions, merge or release.
Fresh chat commands bind their exact response generation before it is exposed
to consumers, avoiding a crash window that could consume an older title or
answer. Legacy workers cannot resume imported sources. The original source
files remain available to the passive history decoder.

回答済みの履歴は Questions と API でも保存済みの状態・回答・回答時刻を保ち、
再回答の操作を表示しない。通常の scheduler が保存済みの移行境界内を一度に
64 件ずつ補正し、再起動後も続行する。効果不明の回答は新たな OPEN Question
ではなく inquiry として残す。更新後の収束、証拠だけによる再照合、所有者による
明示的な精算は [履歴の判断の復旧手順](docs/historical-decisions.md) を参照。


判断待ち基盤の追加検証(2026-11-02):
`watch_supervisor_loss_is_reported_without_reexecuting_the_command` の既報の失敗は、
watch 登録後、コマンドが `starts` を作成するまでの5秒待ちで発生しており、
SIGKILL 後の効果再実行や判断待ちへの投影まで到達していない。
第1修正ラウンドでは実際の CLI・supervisor・コマンドを使う同テストが2回とも通過した。
その時点の `src/chat_watch.rs` と `tests/chat_notify.rs` は、固定された基点
`4eda9559dff7c6a9fac29100d549d8e22bddcea2` との差分がないことを確認した。
したがって今回導入した判断状態の変更による回帰を示す証拠は得られていないが、
既報のタイムアウトの根本原因は未特定であり、修正済みとは扱わない。
再発時の診断用に、同じ5秒制限の失敗メッセージへ永続ジョブと
`armed` / `executing` / `spawn-error` の状態を追加した。
本番の wrapper 起動猶予は10秒で、登録成功はコマンドの最初の書込み完了を保証しない。
この差から起動遅延は調査候補になるが、既報の実測原因だとは断定できない。
テストの時間制限、強制終了、通知内容と一度だけの実行の検証は維持している。
第2修正ラウンドでも、`RUSTUP_TOOLCHAIN=stable cargo test --locked --test chat_notify
watch_supervisor_loss_is_reported_without_reexecuting_the_command -- --nocapture`
を3回実行してすべて通過し、既報の失敗は再現しなかった。
第1修正時点と基点の同一性は `git diff 4eda9559dff7c6a9fac29100d549d8e22bddcea2
f93acf27 -- src/chat_watch.rs tests/chat_notify.rs` が空であることから再確認できる。
全対象テストと最終ゲートは親実行で確認する。

run を持つ従来型問い合わせも維持対象となる。新規 CLI 問い合わせは
所有タスクがないため foreground 経路を選んだことを `legacy_foreground` に保存する。
過去分は operator 由来、またはタスクを持たない run と保存済みの作業ディレクトリから
来歴を確認し、タスク不在だけでは非タスク扱いにしない。
撤回の解決には対応する質問・対象の閉鎖確認と `Superseded` の永続記録が必要で、
回答の受付や閉鎖失敗では解決しない。無関係な破損項目は報告を続けながら新規作成から隔離する。

適用済みの着地保留は、その後の解放や指示変更で判断待ちへ戻らない。
同一 run への再開依頼が実行前に置換された場合や、完了・指示変更で取り消された場合は、
queue に元の依頼と run の置換記録を残して照合する。
通常の実行開始による pin の消費だけでは解決せず、実行開始の永続記録が必要となる。
再開要求を受理してから queue に公開する前の中断は、再起動時または
`reconcile-decision` で未公開と確認できれば再試行待ちへ戻す。
判断の実行権と task claim を保持し、公開時に同時保存する `actions_applied`、
pin、dispatch・置換記録と実行開始受領記録を照合する。公開前なら所有者が
同じ要求を明示的に再試行するか `settle-decision --reason` で取り消せる。
照合だけでは再公開せず、公開済み・実行開始待ちの要求は未実行扱いに戻さない。
放棄操作は run の終了状態と同時に依頼固有の受領記録を保存するため、
判断一覧への最終更新が失われても、再起動時または `reconcile-decision` で
操作を再実行せずに解決できる。単なる Failed 状態は別の依頼の完了証拠にならない。

今回の受領記録修正でも、相談の統合テスト8件と問い合わせの統合テスト33件、
および上記 watch テスト1件が通過した。
`cargo test --locked --lib landing_` は24件成功・6件失敗で、
失敗6件はいずれも既存の着地検証が約4.1GBの空き容量を disk pressure と判定し、
検証コマンドを開始できなかったもの。今回追加した保留受領記録と再起動照合の
単体テストは成功した。この環境上の失敗を解消済み・基点でも再現済みとは扱わず、
全体検証と最終ゲートの結果は引き続き親実行で確認する。

通常の従来型 choice による保留・再キュー・完了も、適用と同じ task 保存で
受領記録を残すため、次の worker 開始や別理由の保留で完了証拠を失わない。
再開は着地停止専用の経路でも依頼 ID を実行 pass に記録する。
放棄操作の live driver・終了済み run などの保存前拒否は、未開始として同じ依頼を
再試行または明示的取消できる。保存を試みた後の失敗は不確実なまま残し、
自動的に再実行しない。

今回の第2レビュー修正では、タスク所有の質問と実在する run の関連を維持した
相談テストを復元し、非タスク相談も含む10件が通過した。
問い合わせの統合テスト35件と、追加した着地保留再開の本番経路テスト1件も通過した。
後者は同じ run で新しい着地承認待ちへ進み、依頼固有の実行開始記録から解決すること、
所有者の新たな回答なしに merge しないことを確認する。
前回の容量不足による着地テスト6件の失敗は、この修正で解消済みとは扱わない。
全体検証と最終ゲートは引き続き親実行が担当する。