magi-cli 0.247.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
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
//! Direct task and run control for the standing chat: `magi task control ...`,
//! and a chat seat's `magi answer --reply` / `--reply-other`.
//!
//! A chat agent carries out the owner's requests by command, with no question
//! or offered choice in between: resume a run, hold or release a task, retry a
//! task with a changed instruction, rerun the failed checks of a pull request,
//! abandon a dead run, and record the owner's choice for a decision the
//! machinery waits on (a merge included). The owner's request in the chat is
//! the authority: no quote, fixed phrase or "only tasks this chat filed" scope
//! applies, including to direct PR merges. Every command goes
//! through the transitions the rest of magi already uses ([`crate::resume`],
//! [`Task::hold_manual`], [`Task::release_operator`], [`Task::edit`],
//! [`crate::daemon::rerun_checks_once`], [`crate::driver::abandon_proven_dead`],
//! [`crate::ask::Question::answer`]); this module only checks *who is asking*
//! and that the target is consistent. A chat seat's answers go through the
//! same bridge ([`Operation::Answer`], [`Operation::ReplyOther`]) because a
//! read-only turn's sandbox may refuse magi's stores; the launcher records
//! them with exactly the terminal's functions.
//!
//! - **Authorization.** `MAGI_NODE=chat` and `MAGI_RUN` equal to the exact id
//!   of an open conversation ([`crate::chat_watch::authorize`]).
//! - **Targets.** Any task (full or unambiguous-prefix id) and any recorded
//!   run (full run id). Ids are checked against the queue, and a task is
//!   re-read under its claim, never trusted from a lookup made before it.
//! - **Resume starts nothing here.** It pins the owning task to the run and
//!   queues it; the loop's ordinary start logic resumes it under the graph's
//!   execution lease, so a second driver cannot appear.
//! - **Abandon needs a proven-dead driver.** Liveness is judged by the shared
//!   judge under the owner lock; an unknown or live driver is refused.
//! - **A merge waits for the owner.** It is recorded only when the owner asks
//!   for it; the land driver then merges the saved head with
//!   `--match-head-commit`.
//! - **Direct PR merging is head-bound, not phrase-bound.** The chat reads the
//!   head from the forge and merges on the owner's plain request. Pending land
//!   approvals retain their existing decision path.

use std::path::Path;

use anyhow::{Context, Result, bail, ensure};

/// Immutable synchronization stop evidence offered by a recovery decision.
pub use crate::base_sync_recovery::Stop as BaseRecoveryStop;
use crate::queue::{Queue, Task, TaskStatus};
use crate::talk::{Talk, Talks};

#[cfg(any(unix, windows))]
pub(crate) mod bridge;

pub(crate) mod standing;

/// Only these operations cross the standing turn's inherited capability.
/// No shell commands or calling conversation identities are input.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(tag = "operation", deny_unknown_fields)]
pub enum Operation {
    /// Request a recovery effect using machine-layer standing authorization.
    Standing {
        /// Task in the current automatic report.
        task: String,
        /// Evidence the chat checked, and why it justifies this action.
        evidence: String,
        /// Existing typed command; the launcher admits only the recovery allowlist.
        command: Box<Operation>,
    },
    /// Persist owner-authorized follow-through through a turn capability.
    Goal {
        /// Typed lifecycle transition; completion is observer-only.
        command: crate::chat_goal::Command,
    },
    /// Reassign an idle task to a different repository without migrating runs.
    Reassign {
        /// Task id or unambiguous prefix.
        task: String,
        /// Repository path, owner/repo, or unique short name.
        repo: std::path::PathBuf,
    },
    /// Authorize bounded repair through the same transaction as the terminal.
    GrantRepair {
        /// Head-bound operator request.
        request: crate::repair_budget::Request,
    },
    /// Reconcile an existing unimported repair receipt; never adds budget.
    ReconcileRepairGrant {
        /// Exact owner-authorized recovery identity.
        request: crate::repair_budget::reconcile::Request,
    },
    /// Reconcile a task-local uncertain effect against its durable end condition.
    ReconcileDecision {
        /// Stable inquiry id.
        inquiry: String,
    },
    /// Bind a command to its durable inquiry; acceptance is not resolution.
    ForDecision {
        /// Stable inquiry id.
        inquiry: String,
        /// Existing typed task/run command.
        command: Box<Operation>,
    },
    /// Explicitly confirm no effect remains, including accepted legacy choices.
    SettleDecision {
        /// Stable inquiry id.
        inquiry: String,
        /// Owner's reason for settlement.
        reason: String,
        /// Replacement active inquiry in the same task/chat.
        replacement: Option<String>,
    },
    /// File a new task through the launcher, including from read-only chats.
    Add {
        /// Validated filing inputs, without task state or a caller-selected id.
        filing: Box<Filing>,
    },
    /// Mark a task complete using the terminal's transition.
    Done {
        /// Task id or unambiguous prefix.
        task: String,
    },
    /// Change a task's queue priority.
    Priority {
        /// Task id or unambiguous prefix.
        task: String,
        /// New priority.
        priority: i32,
    },
    /// Merge a PR the owner asked for, once per request.
    MergePr {
        /// Exact owner/repository name.
        repo: String,
        /// Pull request number.
        number: u64,
        /// Full head SHA the chat just read from the forge.
        head: String,
        /// Idempotency key minted by the chat agent.
        request: String,
    },
    /// Authorize one bounded base-recovery interval and queue the existing run.
    RecoverBase {
        /// Exact retained run ID.
        run: String,
        /// Retained HEAD inspected for the owner's request (full SHA or 7+ hex digits).
        head: String,
        /// Durable idempotency key; reuse only for identical arguments.
        request: String,
    },
    /// 既存 run の再開を queue に登録する。
    Resume {
        /// 完全な run ID。
        run: String,
    },
    /// task を手動保留する。
    Hold {
        /// task ID または一意な接頭辞。
        task: String,
        /// 保留理由。
        reason: String,
    },
    /// task を保留から解放する。
    Release {
        /// task ID または一意な接頭辞。
        task: String,
    },
    /// 指示を変更して再試行する。
    Retry {
        /// task ID または一意な接頭辞。
        task: String,
        /// 新しいタイトル、省略時は指示から生成する。
        title: Option<String>,
        /// 新しい指示全文。
        instruction: String,
    },
    /// PR の失敗した workflow を再実行する。
    RerunChecks {
        /// 完全な run ID。
        run: String,
        /// 冪等性を保証するリクエスト ID。
        request: String,
        /// 観測した PR head。
        head: String,
        /// 再実行対象の workflow run ID。
        workflows: Vec<String>,
    },
    /// タスクチャットで所有者の判断を記録する(マージを含む)。
    Decide {
        /// 質問 ID(完全または一意な接頭辞)。
        question: String,
        /// 記録された選択肢のラベル。
        choice: String,
        /// 「use my text」で公開する置換タイトルそのもの。
        #[serde(default)]
        title: Option<String>,
    },
    /// `magi answer --reply`: the owner's answer to a question, as an ordinary
    /// answer ([`crate::ask::record_answer`]).
    Answer {
        /// Full question id, resolved by the CLI.
        question: String,
        /// An offered choice (label or alias), or the free-text answer.
        reply: String,
        /// The literal replacement title for the posting gate's `use my text`.
        #[serde(default)]
        title: Option<String>,
    },
    /// `magi answer --reply-other`: the owner's decision outside the offered
    /// choices, saved as a note that ends the consultation
    /// ([`crate::consult::reply_other`]).
    ReplyOther {
        /// Full question id, resolved by the CLI.
        question: String,
        /// The owner's outcome.
        text: String,
    },
    /// 保存された計画を作成、または適用する。
    ReconcileRetention {
        /// 対象タスク ID。
        task: String,
        /// 保護する実装の完全な run ID。
        authority: String,
        /// 適用する保存済み計画 ID(省略時は計画のみ)。
        apply: Option<String>,
    },
    /// 生存が否定された run を破棄する。
    Abandon {
        /// 完全な run ID。
        run: String,
    },
}

/// Inputs prepared by `magi task add` before saving a fresh queue record.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Filing {
    /// Task title.
    pub title: String,
    /// Complete task instruction.
    pub instruction: String,
    /// Validated absolute repository path.
    pub repo: std::path::PathBuf,
    /// Filing provenance prepared by the CLI.
    pub source: crate::queue::Source,
    /// Resolved implementation imports.
    pub sources: crate::refs::Sources,
    /// Optional initial hold reason.
    pub hold: Option<String>,
    /// Queue priority.
    pub priority: i32,
    /// Use one implementer.
    pub solo: bool,
    /// Prioritize execution.
    pub urgent: bool,
    /// Optional implementer count.
    pub implementers: Option<usize>,
    /// Absolute attachment paths to copy into the queue.
    pub attach: Vec<std::path::PathBuf>,
}

/// Whether this process inherited a launcher control channel.
/// Provenance-only CLI calls without a channel retain their ordinary local route.
pub fn has_channel() -> bool {
    #[cfg(any(unix, windows))]
    {
        #[cfg(unix)]
        let socket = std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some();
        #[cfg(windows)]
        let socket = false;
        std::env::var_os(bridge::CHANNEL_ENV).is_some() || socket
    }
    #[cfg(not(any(unix, windows)))]
    {
        false
    }
}

/// The CLI sends only a typed operation when it inherited a turn capability.
/// Outside a launched turn the existing, authorized local route remains usable.
pub async fn dispatch(
    queue: &Queue,
    home: &Path,
    talks: &Talks,
    talk: &str,
    operation: Operation,
) -> Result<String> {
    if matches!(
        &operation,
        Operation::Reassign { .. }
            | Operation::RecoverBase { .. }
            | Operation::Goal { .. }
            | Operation::Standing { .. }
    ) {
        #[cfg(unix)]
        {
            return bridge::request(&operation).context("this operation requires the authenticated chat control channel; repair the launcher/backend transport; reopening the conversation does not repair descriptor propagation");
        }
        #[cfg(windows)]
        {
            return bridge::request(&operation).await.context("this operation requires the authenticated chat control channel; repair the launcher/backend transport; reopening the conversation does not repair descriptor propagation");
        }
        #[cfg(not(any(unix, windows)))]
        {
            bail!("authenticated chat control channel is unavailable on this platform");
        }
    }
    if standing_turn() {
        #[cfg(unix)]
        return bridge::request(&operation)
            .context("automatic recovery requires the authenticated chat control channel");
        #[cfg(windows)]
        return bridge::request(&operation)
            .await
            .context("automatic recovery requires the authenticated chat control channel");
        #[cfg(not(any(unix, windows)))]
        bail!("authenticated chat control channel is unavailable on this platform");
    }
    #[cfg(unix)]
    if std::env::var_os(bridge::CHANNEL_ENV).is_some()
        || std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some()
    {
        // The launcher sets this flag for writable seats, including effective
        // unsandboxed chat turns. execute() still enforces talk authorization.
        match bridge::request(&operation) {
            Err(error)
                if error.is::<bridge::Unavailable>()
                    && std::env::var("MAGI_ALLOW_WRITE").as_deref() == Ok("1") => {}
            result => return result,
        }
    }
    #[cfg(windows)]
    if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
        return bridge::request(&operation).await;
    }
    execute(queue, home, talks, talk, operation).await
}

/// The transport supplies immutable launcher authority, never the CLI frame.
async fn execute_authenticated(
    queue: &Queue,
    home: &Path,
    talks: &Talks,
    talk: &str,
    source: crate::chat_goal::Source,
    operation: Operation,
) -> Result<String> {
    if let crate::chat_goal::Source::Standing(scope) = source {
        return Box::pin(standing::execute(
            queue, home, talks, talk, &scope, operation,
        ))
        .await;
    }
    crate::chat_goal::with_source(source, execute(queue, home, talks, talk, operation)).await
}

/// Whether the launcher restricted this CLI to read-only inspection and typed controls.
/// The environment marker can only restrict the CLI; it cannot grant bridge authority.
pub fn standing_turn() -> bool {
    std::env::var_os(standing::ENV).is_some()
}

async fn execute(
    queue: &Queue,
    home: &Path,
    talks: &Talks,
    talk: &str,
    operation: Operation,
) -> Result<String> {
    authorize(talks, talk, crate::queue::CHAT_NODE)?;
    crate::chat_goal::fence(talks, talk, &crate::chat_goal::current_source())?;
    admit_goal_operation(queue, home, talks, talk, &operation)?;
    Ok(match operation {
        Operation::Standing { .. } => bail!(
            "standing authorization is disabled or this turn is not an eligible automatic report"
        ),
        Operation::Goal { command } => {
            crate::chat_goal::apply(
                queue,
                home,
                talks,
                talk,
                &crate::chat_goal::current_source(),
                command,
            )
            .await?
        }
        Operation::Reassign { task, repo } => {
            let cwd = &talks.get(talk)?.repo;
            let task = crate::task_reassign::reassign(
                queue,
                home,
                cwd,
                &task,
                &repo,
                &format!("chat:{talk}"),
            )
            .await?;
            let mut message = describe(&task, "reassigned");
            for note in crate::task_reassign::advisory_notes(&task, home) {
                message.push_str(&format!("\n  {note}"));
            }
            message
        }
        Operation::ReconcileDecision { inquiry } => {
            reconcile_task_decision(queue, home, talk, &inquiry)?;
            format!("decision {inquiry} reconciled from the task's durable state")
        }
        Operation::ForDecision { inquiry, command } => {
            execute_decision(queue, home, talks, talk, &inquiry, *command).await?
        }
        Operation::SettleDecision {
            inquiry,
            reason,
            replacement,
        } => {
            let outbox = crate::task_inquiry::Outbox::at(home);
            let record = outbox.get(&inquiry)?;
            let questions = crate::ask::Questions::at(home.join("questions"));
            let source = questions.read_history(&inquiry).ok();
            // A quarantined saved reply is not a live unanswered decision.
            // The owner can explicitly confirm that its unknown effect needs
            // no further work without accepting or replaying the old reply.
            let unaccepted_history = record
                .decision
                .as_ref()
                .is_some_and(|d| d.request.is_none())
                && source.as_ref().is_some_and(|source| {
                    source.status == crate::ask::QuestionStatus::Answered
                        && crate::task_chat::saved_reply_requires_confirmation(home, source)
                });
            // Task-backed legacy consumers run under the task claim. Hold it
            // through settlement; ownerless release consumers use the inquiry
            // execution fence inside Outbox::settle instead.
            let _task_claim = if !record.task.is_empty()
                && (unaccepted_history
                    || record
                        .decision
                        .as_ref()
                        .is_some_and(|d| d.request.is_some()))
            {
                Some(
                    queue
                        .claim(&record.task)
                        .context("decision task is executing")?,
                )
            } else {
                None
            };
            if record
                .decision
                .as_ref()
                .is_some_and(|d| d.request.is_none())
                && let Some(source) = source
                && !(record.task.is_empty() && record.delivered_to.is_none())
            {
                ensure!(
                    unaccepted_history || !crate::task_chat::awaits_decision(&source),
                    "a legacy effect still awaits consumer reconciliation; settlement executes no action"
                );
            }
            outbox.settle(&inquiry, talk, &reason, replacement.as_deref())?;
            format!("settled decision {inquiry}: {reason}")
        }
        Operation::Add { filing } => serde_json::to_string(&file_task(queue, *filing)?)?,
        Operation::Done { task } => {
            let t = done_claimed(queue, home, claimed_for_chat(queue, &task, talks, talk)?)?;
            format!("done {} {}", t.short(), t.title)
        }
        Operation::Priority { task, priority } => {
            let t = priority_claimed(
                queue,
                claimed_for_chat(queue, &task, talks, talk)?,
                priority,
            )?;
            format!("{} priority now {} - {}", t.short(), t.priority, t.title)
        }
        Operation::MergePr {
            repo,
            number,
            head,
            request,
        } => crate::chat_merge::merge(
            home,
            talks,
            talk,
            crate::chat_merge::Request {
                repo,
                number,
                head,
                request,
            },
        )
        .await
        .map_err(|error| {
            if error.is::<crate::chat_merge::BeforeMergeWrite>() {
                anyhow::Error::new(BeforeEffect(error))
            } else {
                error
            }
        })?,
        Operation::ReconcileRepairGrant { request } => serde_json::to_string(
            &Box::pin(crate::repair_budget::reconcile::apply(queue, home, request)).await?,
        )?,
        Operation::GrantRepair { request } => {
            // Keep run-state admission out of the shared control dispatcher
            // future, which is also embedded in ordinary CLI task operations.
            serde_json::to_string(
                &Box::pin(crate::repair_budget::grant(queue, home, request)).await?,
            )?
        }
        Operation::RecoverBase { run, head, request } => {
            let result = Box::pin(crate::base_recovery_control::recover(
                queue,
                home,
                crate::base_recovery_control::Request {
                    run,
                    head,
                    request,
                    actor: talk.to_owned(),
                    decision: None,
                    expected_stop: None,
                },
            ))
            .await?;
            if result.repeated {
                format!(
                    "This base-recovery request was already applied to task {}; inspect its current status before continuing",
                    result.task.id
                )
            } else {
                format!(
                    "{}; bounded base recovery authorized; the daemon resumes the exact run under its execution lease",
                    describe(&result.task, "recovery queued for")
                )
            }
        }
        Operation::Resume { run } => {
            let t = resume(queue, home, &run)?;
            format!(
                "{}; the loop (`magi serve`) resumes the run under its execution lease",
                describe(&t, "resume queued for")
            )
        }
        Operation::Hold { task, reason } => describe(
            &hold_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?, &reason)?,
            "held",
        ),
        Operation::Release { task } => describe(
            &release_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?)?,
            "released",
        ),
        Operation::Retry {
            task,
            title,
            instruction,
        } => describe(
            &retry_claimed(
                queue,
                claimed_for_chat(queue, &task, talks, talk)?,
                title,
                &instruction,
            )?,
            "retry queued for",
        ),
        Operation::RerunChecks {
            run,
            request,
            head,
            workflows,
        } => {
            let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
            format!("requested a rerun of workflow run(s) {}", ids.join(", "))
        }
        Operation::Decide {
            question,
            choice,
            title,
        } => {
            let q = record_decision(home, &question, &choice, title.as_deref())?;
            format!(
                "recorded `{choice}` for decision {}; effect pending until its durable application receipt is confirmed",
                q.short()
            )
        }
        Operation::Answer {
            question,
            reply,
            title,
        } => crate::ask::record_answer(
            &crate::ask::Questions::at(home.join("questions")),
            &question,
            &reply,
            title.as_deref(),
        )?,
        Operation::ReplyOther { question, text } => crate::consult::reply_other(
            &crate::ask::Questions::at(home.join("questions")),
            &question,
            &text,
        )?,
        Operation::ReconcileRetention {
            task,
            authority,
            apply,
        } => {
            let path = Box::pin(crate::retention::reconcile::run_chat(
                home,
                &task,
                &authority,
                apply.as_deref(),
                crate::retention::reconcile::ChatRequest {
                    talks,
                    conversation: talk,
                },
            ))
            .await?;
            if apply.is_none() {
                // Return the complete saved evidence through the capability bridge.
                crate::retention::reconcile::chat_summary(&path)?
            } else {
                format!(
                    "Applied saved plan {}",
                    apply.as_deref().unwrap_or_default()
                )
            }
        }
        Operation::Abandon { run } => {
            abandon(queue, home, &run)?;
            format!("abandoned run {run}")
        }
    })
}

fn file_task(queue: &Queue, filing: Filing) -> Result<Task> {
    let mut task = Task::new(filing.title, filing.instruction, filing.repo, filing.source);
    task.sources = filing.sources;
    if let Some(reason) = filing.hold {
        task.hold_manual(Some(reason));
    }
    task.priority = filing.priority;
    task.solo = filing.solo;
    task.urgent = filing.urgent;
    if filing.implementers.is_some() {
        task.overrides = Some(crate::queue::RunOverrides {
            candidates: filing.implementers,
            ..Default::default()
        });
    }
    if filing.attach.is_empty() {
        queue.put(&mut task)?;
    } else {
        queue.attach_and_put(&mut task, &filing.attach)?;
    }
    Ok(task)
}

/// A goal turn cannot redirect existing effects to unrelated work.
fn admit_goal_operation(
    queue: &Queue,
    home: &Path,
    talks: &Talks,
    talk_id: &str,
    operation: &Operation,
) -> Result<()> {
    let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source()
    else {
        return Ok(());
    };
    let talk = talks.get(talk_id)?;
    let goal = talk
        .goals
        .iter()
        .find(|goal| goal.id == id)
        .context("unknown goal")?;
    goal.admit(generation)?;
    ensure!(
        !goal.owner_input.is_empty(),
        "this goal was registered under standing authorization; fresh owner input is required with the setting off"
    );
    let repo = goal.effective_repo(&talk.repo);
    let task_allowed = |reference: &str| -> Result<()> {
        let id = queue.resolve_id(reference)?;
        ensure!(
            goal.tasks.contains(&id),
            "effect targets a task outside this goal"
        );
        crate::chat_goal::task_record(queue, &id, repo)?;
        Ok(())
    };
    let run_allowed = |run: &str| -> Result<()> {
        ensure!(
            goal.runs.iter().any(|id| id == run)
                || goal
                    .tasks
                    .iter()
                    .any(|id| crate::chat_goal::task_record(queue, id, repo)
                        .is_ok_and(|task| task.execution_runs().iter().any(|id| id == run))),
            "effect targets an execution outside this goal"
        );
        crate::chat_goal::run_record(home, run, repo)?;
        Ok(())
    };
    match operation {
        Operation::Standing { .. } => bail!("standing authorization is disabled for this turn"),
        Operation::Goal { .. } => {}
        Operation::Add { filing } => {
            crate::chat_goal::require_repo("filing", talk_id, &filing.repo, repo)?;
            ensure!(
                matches!(&filing.source, crate::queue::Source::Agent { run, node }
                    if run == talk_id && node == crate::queue::CHAT_NODE),
                "goal filing must retain this conversation's provenance"
            );
        }
        Operation::Done { task }
        | Operation::Priority { task, .. }
        | Operation::Hold { task, .. }
        | Operation::Release { task }
        | Operation::Retry { task, .. }
        | Operation::ReconcileRetention { task, .. } => task_allowed(task)?,
        Operation::GrantRepair { request } => {
            task_allowed(&request.task)?;
            run_allowed(&request.run)?;
        }
        Operation::ReconcileRepairGrant { request } => {
            task_allowed(&request.task)?;
            run_allowed(&request.run)?;
        }
        Operation::Resume { run }
        | Operation::RecoverBase { run, .. }
        | Operation::Abandon { run }
        | Operation::RerunChecks { run, .. } => run_allowed(run)?,
        Operation::ForDecision { inquiry, .. }
        | Operation::ReconcileDecision { inquiry }
        | Operation::SettleDecision { inquiry, .. } => {
            let record = crate::task_inquiry::Outbox::at(home).get(inquiry)?;
            crate::chat_goal::require_repo("inquiry", inquiry, &record.repo, repo)?;
            task_allowed(&record.task)?;
            if let Some(run) = record.run {
                run_allowed(&run)?;
            }
        }
        Operation::Decide { question, .. }
        | Operation::Answer { question, .. }
        | Operation::ReplyOther { question, .. } => {
            let questions = crate::ask::Questions::at(home.join("questions"));
            let question = questions.get_for_effects(&questions.resolve_id(question)?)?;
            if question.run_names_task() {
                task_allowed(&question.run)?;
            } else {
                run_allowed(&question.run)?;
            }
        }
        Operation::MergePr {
            repo: slug, number, ..
        } => {
            let expected = format!("https://github.com/{slug}/pull/{number}");
            let mut found = false;
            let mut inspect = |run: &str| -> Result<()> {
                let state = crate::chat_goal::run_record(home, run, repo)?;
                found |= state
                    .pr
                    .as_ref()
                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected));
                Ok(())
            };
            for run in &goal.runs {
                inspect(run)?;
            }
            for task in &goal.tasks {
                for run in crate::chat_goal::task_record(queue, task, repo)?.execution_runs() {
                    inspect(run)?;
                }
            }
            ensure!(found, "merge targets a pull request outside this goal");
        }
        Operation::Reassign { .. } => bail!("automatic goal turns cannot change repository scope"),
    }
    Ok(())
}

/// Run one typed operation on behalf of the owner, retaining failures and
/// uncertainty. A repeated command never blindly replays a possibly applied
/// external effect. The underlying operation retains its existing claims and
/// receipts; this journal is its user-visible lifecycle, not a second worker.
async fn execute_decision(
    queue: &Queue,
    home: &Path,
    talks: &Talks,
    chat: &str,
    id: &str,
    command: Operation,
) -> Result<String> {
    use crate::task_decision::Status;
    admit_goal_operation(queue, home, talks, chat, &command)?;
    let outbox = crate::task_inquiry::Outbox::at(home);
    let _execution = outbox.execution_claim(id)?;
    let inquiry = outbox.get(id)?;
    ensure!(
        inquiry.delivered_to.as_deref() == Some(chat),
        "decision belongs to another chat"
    );
    let task = queue.get(&inquiry.task)?;
    ensure!(task.repo == inquiry.repo, "decision repository changed");
    let deferred = matches!(
        command,
        Operation::Resume { .. } | Operation::MergePr { .. }
    );
    let merge = match &command {
        Operation::MergePr {
            repo,
            number,
            head,
            request,
        } => Some(crate::chat_merge::Request {
            repo: repo.clone(),
            number: *number,
            head: head.clone(),
            request: request.clone(),
        }),
        _ => None,
    };
    match &command {
        Operation::Done { task: target }
        | Operation::Hold { task: target, .. }
        | Operation::Release { task: target }
        | Operation::Retry { task: target, .. } => {
            ensure!(
                queue.resolve_id(target)? == task.id,
                "command targets another task"
            );
        }
        Operation::Resume { run }
        | Operation::Abandon { run }
        | Operation::RerunChecks { run, .. } => {
            ensure!(
                task.runs.contains(run) && inquiry.run.as_ref().is_none_or(|own| own == run),
                "command targets another execution"
            );
            ensure!(
                queue
                    .list()
                    .iter()
                    .filter(|owner| owner.runs.contains(run))
                    .count()
                    == 1,
                "execution ownership is ambiguous"
            );
        }
        Operation::MergePr { repo, number, .. } => {
            let run = inquiry
                .run
                .as_ref()
                .or_else(|| task.runs.last())
                .context("task has no execution for this merge")?;
            let state = crate::run::RunState::load_under(run, home)?;
            ensure!(state.id == *run, "merge run identity changed");
            ensure!(
                crate::git::same_checkout(&state.repo, &task.repo)?,
                "merge targets another repository"
            );
            let expected = format!("https://github.com/{repo}/pull/{number}");
            ensure!(
                state
                    .pr
                    .as_ref()
                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected)),
                "merge targets another task or repository"
            );
        }
        _ => bail!("use a task/run effect command with --decision; routed approvals use decide"),
    }
    let request = serde_json::to_string(&command)?;
    let mut decision = inquiry.decision.context("inquiry is informational")?;
    if decision.request.is_some()
        && decision.status != Status::Resolved
        && let Operation::Resume { run } = &command
    {
        ensure!(
            decision.request.as_deref() == Some(&request),
            "decision already binds a different request"
        );
        // Queued also includes successfully published resumes. Reconcile under
        // the execution claim before permitting any retry, even if the run has
        // since returned to a resumable state. Only proven non-publication may
        // enter the retry path below.
        reconcile_resume_claimed(queue, home, &outbox, id, run)?;
        decision = outbox
            .get(id)?
            .decision
            .context("inquiry is informational")?;
        ensure!(
            decision.status == Status::Resolved || decision.retry_safe,
            "previous resume remains queued or executing; it will not be replayed"
        );
    }
    if decision.status == Status::Resolved {
        ensure!(
            decision.request.as_deref() == Some(&request),
            "decision resolved for a different request"
        );
        return Ok(format!(
            "decision {id} is already resolved; inspect its outcome history"
        ));
    }
    if let Operation::RerunChecks { run, request, .. } = &command {
        // Reject correctable input before binding the decision to this exact
        // command. Execution revalidates these reads before taking its lock.
        rerun_preflight(queue, home, run, request)?;
    }
    if let Some(action) = &merge {
        // Malformed input must not durably bind this decision to a command
        // that can never reach its effect service.
        action.validate()?;
    }
    // Keep admission across acceptance and execution: contention and request
    // collisions must not bind a fresh decision to an unstartable operation.
    let merge_admission = merge
        .as_ref()
        .map(|action| crate::chat_merge::admit(home, talks, chat, action))
        .transpose()?;
    if decision.request.is_none() && decision.status == Status::RetryNeeded {
        if let Ok(source) = crate::ask::Questions::at(home.join("questions")).get(id) {
            ensure!(
                !crate::task_chat::awaits_decision(&source),
                "a legacy effect still needs its receipt reconciled before another effect is accepted"
            );
        }
    }
    {
        // A live task cannot accept a repair grant. Do not prevent decisions
        // that its active driver is waiting for by taking its execution claim.
        let claim = (queue.get(&task.id)?.status != TaskStatus::Running)
            .then(|| queue.claim(&task.id))
            .transpose();
        let _claim = match claim {
            Ok(claim) => claim,
            Err(error) => {
                // Admission could not start this attempt. Retain the exact
                // owner request and pre-effect failure just as execution-side
                // claim contention does, without publishing any task effect.
                let message = format!(
                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
                );
                outbox.update_decision(id, |d| {
                    let safe = d.request.is_none() || d.retry_safe;
                    d.accept(&request)?;
                    if safe {
                        d.fail_before_effect(&message)
                    } else {
                        // A prior queued/uncertain attempt still needs its own
                        // receipt. Contention is not proof that it never ran.
                        Ok(false)
                    }
                })?;
                return Err(anyhow::Error::new(BeforeEffect(error)));
            }
        };
        outbox.update_decision(id, |d| d.accept(&request))?;
    }
    let late_admission = crate::chat_goal::fence(talks, chat, &crate::chat_goal::current_source())
        .and_then(|()| admit_goal_operation(queue, home, talks, chat, &command));
    if late_admission.is_ok()
        && decision.request.is_some()
        && matches!(decision.status, Status::InProgress | Status::RetryNeeded)
    {
        if decision.retry_safe {
            outbox.update_decision(id, |d| {
                d.retry_unapplied()?;
                d.start()
            })?;
        } else {
            let action = merge
                .as_ref()
                .context("previous effect needs receipt reconciliation; it will not be replayed")?;
            ensure!(
                merge_receipt(home, chat, action)?.is_some(),
                "previous merge has no receipt; inspect the operation before retrying"
            );
        }
        // The shared merge service only checks the forge once this exact
        // request has a receipt; it never issues the merge command twice.
    } else if late_admission.is_ok() {
        outbox.update_decision(id, |d| d.start())?;
    }
    let local = match late_admission {
        // A refusal now says nothing about a prior attempt that may have acted.
        Err(error)
            if decision.request.is_some()
                && !decision.retry_safe
                && (matches!(decision.status, Status::InProgress | Status::RetryNeeded)
                    || decision
                        .history
                        .iter()
                        .any(|event| event.status == Status::InProgress)) =>
        {
            return Err(error);
        }
        Err(error) => Err(anyhow::Error::new(BeforeEffect(error))),
        Ok(()) => apply_local_decision(
            queue,
            home,
            id,
            &request,
            &inquiry.task,
            &inquiry.repo,
            &command,
        ),
    };
    let result = if let Err(error) = local {
        Err(error)
    } else if let Some(message) = local? {
        Ok(message)
    } else if let Operation::Resume { run } = &command {
        // Validation precedes any write: a refusal means nothing began.
        crate::resume::validate(home, run)
            .map(|_| ())
            .map_err(|e| anyhow::Error::new(BeforeEffect(e)))
            .and_then(|()| -> Result<String> {
                let pinned =
                    crate::resume::pin_queued(queue, run, None, Some(id)).map_err(|error| {
                        if error.is::<crate::resume::BeforeQueueWrite>() {
                            anyhow::Error::new(BeforeEffect(error))
                        } else {
                            error
                        }
                    })?;
                if !pinned {
                    return Err(anyhow::Error::new(BeforeEffect(anyhow::anyhow!(
                        "no queued task owns this run"
                    ))));
                }
                Ok(format!(
                    "resume queued for {run}; execution start remains unconfirmed"
                ))
            })
    } else if let Operation::Abandon { run } = &command {
        crate::driver::abandon_decision(home, run, id, &request)
            .map_err(|error| {
                if error.is::<crate::driver::BeforeAbandonWrite>() {
                    anyhow::Error::new(BeforeEffect(error))
                } else {
                    error
                }
            })
            .map(|()| format!("abandoned run {run}"))
    } else if let Some(admission) = merge_admission {
        crate::chat_merge::merge_admitted(home, merge.as_ref().unwrap().clone(), admission)
            .await
            .map_err(|error| {
                if error.is::<crate::chat_merge::BeforeMergeWrite>() {
                    anyhow::Error::new(BeforeEffect(error))
                } else {
                    error
                }
            })
    } else {
        Box::pin(execute(queue, home, talks, chat, command)).await
    };
    match result {
        Ok(message) => {
            if let Some(action) = &merge {
                if let Some(receipt) = merge_receipt(home, chat, action)? {
                    if receipt["status"] == "merged" {
                        outbox.update_decision(id, |d| d.applied(&message))?;
                    } else if receipt["status"] != "pending" {
                        outbox.update_decision(id, |d| {
                            d.fail(&format!(
                                "{message}; reuse this same request ID to reconcile only"
                            ))
                        })?;
                    }
                }
            } else if !deferred {
                outbox.update_decision(id, |d| {
                    d.applied(&format!("typed command completed: {message}"))
                })?;
            }
            if deferred
                && outbox
                    .get(id)?
                    .decision
                    .as_ref()
                    .is_some_and(|d| d.status == Status::InProgress)
            {
                outbox.update_decision(id, |d| d.queued())?;
            }
            // Resume has only been queued. Its execution is confirmed by a
            // later scheduler projection, never by this command's return.
            Ok(message)
        }
        Err(error) => {
            let message = if error.is::<BeforeEffect>() {
                format!(
                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
                )
            } else {
                format!(
                    "Operation failed or has an uncertain result: {error:#}. Inspect its receipt before retrying."
                )
            };
            outbox.update_decision(id, |d| {
                if error.is::<BeforeEffect>() {
                    d.fail_before_effect(&message)
                } else {
                    d.fail(&message)
                }
            })?;
            Err(error)
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[error("effect did not start: {0:#}")]
struct BeforeEffect(anyhow::Error);

/// Commit a task-local effect and its exact receipt under one queue claim.
/// The inquiry projection may lag this write, but restart never has to infer
/// completion from the task's current status or repeat the operation.
fn apply_local_decision(
    queue: &Queue,
    home: &Path,
    id: &str,
    request: &str,
    owner: &str,
    repo: &Path,
    command: &Operation,
) -> Result<Option<String>> {
    let target = match command {
        Operation::Done { task }
        | Operation::Hold { task, .. }
        | Operation::Release { task }
        | Operation::Retry { task, .. } => task,
        _ => return Ok(None),
    };
    let prepare = || -> Result<_> {
        let (_claim, mut task) = claimed(queue, target)?;
        ensure!(
            task.id == owner && task.repo == repo,
            "decision ownership changed"
        );
        if let Some(prior) = task.decision_effects.get(id) {
            ensure!(prior == request, "decision receipt binds another command");
            let message = format!("task {}: decision {id} already applied", task.id);
            return Ok((_claim, task, message, true));
        }
        let message = match command {
            Operation::Done { .. } => {
                task.succeed();
                describe(&task, "done")
            }
            Operation::Hold { reason, .. } => {
                check_hold_release(&task, "hold")?;
                let reason = reason.trim();
                task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
                describe(&task, "held")
            }
            Operation::Release { .. } => {
                check_hold_release(&task, "release")?;
                task.release_operator("chat", Some(id));
                describe(&task, "released")
            }
            Operation::Retry {
                title, instruction, ..
            } => {
                ensure!(
                    !instruction.trim().is_empty(),
                    "the new instruction is empty"
                );
                let title = title
                    .clone()
                    .unwrap_or_else(|| crate::queue::title_from(instruction, 72));
                task.edit(title, instruction.clone())?;
                task.release_operator("chat", Some(id));
                describe(&task, "retry queued for")
            }
            _ => unreachable!("task-local operation checked above"),
        };
        task.decision_effects
            .insert(id.to_owned(), request.to_owned());
        Ok((_claim, task, message, false))
    };
    let (_claim, mut task, message, already_applied) = prepare().map_err(BeforeEffect)?;
    if !already_applied {
        queue.put(&mut task)?;
    }
    if matches!(command, Operation::Done { .. }) {
        crate::daemon::supersede_prior_runs(&task, home);
    }
    Ok(Some(message))
}

/// Explicit owner-requested reconciliation executes nothing. Under the task
/// claim, prove that the exact intended condition already holds; otherwise keep
/// uncertainty visible. External effects require their own receipts instead.
fn reconcile_task_decision(queue: &Queue, home: &Path, chat: &str, id: &str) -> Result<()> {
    let outbox = crate::task_inquiry::Outbox::at(home);
    let inquiry = outbox.get(id)?;
    ensure!(
        inquiry.delivered_to.as_deref() == Some(chat)
            || (inquiry.task.is_empty() && inquiry.delivered_to.is_none()),
        "decision belongs to another chat"
    );
    let decision = inquiry.decision.context("inquiry is informational")?;
    if decision.status == crate::task_decision::Status::Resolved {
        return Ok(());
    }
    if decision
        .request
        .as_ref()
        .is_none_or(|request| request.starts_with("decision: "))
    {
        let source = crate::ask::Questions::at(home.join("questions")).read_history(id)?;
        crate::task_chat::sync_effect_receipt(home, queue, &source);
        ensure!(
            outbox
                .get(id)?
                .decision
                .is_some_and(|d| d.status == crate::task_decision::Status::Resolved),
            "source effect remains unconfirmed; no operation was replayed"
        );
        return Ok(());
    }
    let request = decision
        .request
        .context("decision has no accepted operation to reconcile")?;
    let command: Operation = serde_json::from_str(&request)?;
    if let Operation::Resume { run } = &command {
        reconcile_resume_decision(queue, home, &outbox, id, run)?;
        ensure!(
            outbox.get(id)?.decision.is_some_and(|d| {
                d.status == crate::task_decision::Status::Resolved || d.retry_safe
            }),
            "resume remains queued or executing; no operation was replayed"
        );
        return Ok(());
    }
    let (_claim, task) = claimed(queue, &inquiry.task)?;
    ensure!(task.repo == inquiry.repo, "decision repository changed");
    if let Some(receipt) = task.decision_effects.get(id) {
        ensure!(
            receipt == &request,
            "decision receipt binds another command"
        );
        return outbox.update_decision(id, |d| {
            d.applied("exact task command receipt confirmed; no operation replayed")
        });
    }
    let matches = match command {
        Operation::Hold {
            task: target,
            reason,
        } => {
            queue.resolve_id(&target)? == task.id
                && task.status == TaskStatus::Held
                && task.hold_reason.as_deref() == Some(reason.trim())
        }
        Operation::Release { task: target } => {
            queue.resolve_id(&target)? == task.id
                && task.status == TaskStatus::Queued
                && !task.operator_held()
        }
        Operation::Done { task: target } => {
            queue.resolve_id(&target)? == task.id && task.status == TaskStatus::Done
        }
        Operation::Retry {
            task: target,
            title,
            instruction,
        } => {
            queue.resolve_id(&target)? == task.id
                && task.instruction == instruction
                && title.as_ref().is_none_or(|title| *title == task.title)
                && task.status == TaskStatus::Queued
        }
        Operation::Abandon { run } => abandonment_receipt(home, &task, id, &run, &request)?,
        _ => anyhow::bail!(
            "external effects require their authoritative receipt; no operation was replayed"
        ),
    };
    ensure!(
        matches,
        "intended task condition is not confirmed; no operation was replayed"
    );
    outbox.update_decision(id, |d| d.applied("owner-requested reconciliation: exact intended task condition confirmed under its claim; no effect remains necessary"))
}

/// Read the exact request's committed execution pass or durable pin supersession.
/// A transient task status alone never proves either outcome.
pub(crate) fn resume_started(home: &Path, task: &Task, inquiry: &str, run: &str) -> Result<bool> {
    ensure!(
        crate::run::is_run_id(run) && task.runs.iter().any(|id| id == run),
        "resume run ownership changed"
    );
    let state = crate::run::RunState::load_under(run, home)?;
    ensure!(state.id == run, "resume run identity changed");
    ensure!(
        crate::git::same_checkout(&state.repo, &task.repo)?,
        "resume run repository changed"
    );
    if task
        .superseded_resumes
        .get(inquiry)
        .is_some_and(|target| target == run)
    {
        return Ok(true);
    }
    Ok(state.decision_starts.get(inquiry).is_some_and(|index| {
        state
            .passes
            .get(*index)
            .is_some_and(|pass| pass.index == *index)
    }))
}

/// Publication writes the pin and actions_applied marker atomically. Fence the
/// publisher and scheduler before treating their absence as pre-effect proof.
/// A published pin may already be consumed, so its absence alone is not proof.
fn reconcile_resume_decision(
    queue: &Queue,
    home: &Path,
    outbox: &crate::task_inquiry::Outbox,
    id: &str,
    run: &str,
) -> Result<()> {
    let Ok(_execution) = outbox.execution_claim(id) else {
        return Ok(());
    };
    reconcile_resume_claimed(queue, home, outbox, id, run)
}

/// The caller holds this inquiry's execution claim, including on resubmission.
fn reconcile_resume_claimed(
    queue: &Queue,
    home: &Path,
    outbox: &crate::task_inquiry::Outbox,
    id: &str,
    run: &str,
) -> Result<()> {
    let inquiry = outbox.get(id)?;
    let Ok(_claim) = queue.claim(&inquiry.task) else {
        return Ok(());
    };
    let task = queue.get(&inquiry.task)?;
    ensure!(task.repo == inquiry.repo, "resume task repository changed");
    let decision = inquiry.decision.context("inquiry is informational")?;
    if decision.status == crate::task_decision::Status::Resolved {
        return Ok(());
    }
    if resume_started(home, &task, id, run)? {
        outbox.update_decision(id, |d| {
            d.applied("exact resume execution-start or supersession receipt confirmed")
        })?;
    } else if !task.action_applied(id)
        && !task.dispatched_resumes.contains_key(id)
        && !task.superseded_resumes.contains_key(id)
        && !task
            .resume_override
            .as_ref()
            .is_some_and(|pin| pin.question_id == id)
    {
        outbox.update_decision(id, |d| {
            d.fail_before_effect("Resume was not published to the queue; the owner may retry the same request or cancel it. No operation was replayed.")
        })?;
    }
    Ok(())
}

fn abandonment_receipt(
    home: &Path,
    task: &Task,
    id: &str,
    run: &str,
    request: &str,
) -> Result<bool> {
    ensure!(
        task.runs.iter().any(|own| own == run),
        "abandon run ownership changed"
    );
    let state = crate::run::RunState::load_under(run, home)?;
    ensure!(state.id == run, "abandon run identity changed");
    ensure!(
        crate::git::same_checkout(&state.repo, &task.repo)?,
        "abandon run repository changed"
    );
    Ok(state
        .abandonment_receipts
        .get(id)
        .is_some_and(|receipt| receipt == request))
}

fn merge_receipt(
    home: &Path,
    chat: &str,
    action: &crate::chat_merge::Request,
) -> Result<Option<serde_json::Value>> {
    ensure!(
        crate::ask::valid_asset_name(chat) && crate::ask::valid_asset_name(&action.request),
        "invalid merge receipt identity"
    );
    let path = home
        .join("chat-controls")
        .join(chat)
        .join(format!("{}.json", action.request));
    let bytes = match std::fs::read(path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error.into()),
    };
    let receipt: serde_json::Value = serde_json::from_slice(&bytes)?;
    ensure!(
        receipt["action"] == serde_json::to_value(action)?,
        "merge receipt names another operation"
    );
    Ok(Some(receipt))
}

/// Repair the decision projection from independently durable command receipts.
/// This starts no workers and retries no operation.
pub fn reconcile_decisions(queue: &Queue, home: &Path) -> Result<()> {
    let outbox = crate::task_inquiry::Outbox::at(home);
    let (inquiries, unreadable) = outbox.list_readable()?;
    let mut errors = Vec::new();
    if unreadable != 0 {
        errors.push(format!("{unreadable} unreadable inquiry record(s)"));
    }
    for inquiry in inquiries {
        let id = inquiry.id.clone();
        if let Err(error) = reconcile_inquiry(queue, home, &outbox, inquiry) {
            let message = format!(
                "Decision receipt reconciliation failed: {error:#}. Inspect this inquiry's receipt before retrying."
            );
            tracing::warn!("decision {id}: {message}");
            if let Err(error) = outbox.update_decision(&id, |d| d.fail(&message)) {
                tracing::warn!("decision {id} error could not be persisted: {error:#}");
            }
            errors.push(format!("{id}: {message}"));
        }
    }
    ensure!(
        errors.is_empty(),
        "{} decision reconciliation problem(s): {}",
        errors.len(),
        errors.join("; ")
    );
    Ok(())
}

fn reconcile_inquiry(
    queue: &Queue,
    home: &Path,
    outbox: &crate::task_inquiry::Outbox,
    inquiry: crate::task_inquiry::Inquiry,
) -> Result<()> {
    use crate::task_decision::Status;
    let Some(decision) = inquiry.decision else {
        return Ok(());
    };
    if decision.status == Status::Resolved {
        return Ok(());
    }
    let Some(request) = decision.request else {
        return Ok(());
    };
    let Ok(command) = serde_json::from_str::<Operation>(&request) else {
        return Ok(());
    };
    if let Operation::Resume { run } = &command {
        return reconcile_resume_decision(queue, home, outbox, &inquiry.id, run);
    }
    let task = queue.get(&inquiry.task)?;
    ensure!(task.repo == inquiry.repo, "decision repository changed");
    if let Some(receipt) = task.decision_effects.get(&inquiry.id) {
        ensure!(
            receipt == &request,
            "decision receipt binds another command"
        );
        outbox.update_decision(&inquiry.id, |d| {
            d.applied("exact task command receipt confirmed after restart")
        })?;
        return Ok(());
    }
    let mut pending_external = false;
    let receipt = match command {
        Operation::Abandon { run } => {
            abandonment_receipt(home, &task, &inquiry.id, &run, &request)?
                .then(|| format!("run {run}: exact abandonment receipt committed"))
        }
        Operation::RerunChecks {
            request,
            run,
            head,
            workflows,
        } => {
            let chat = inquiry.delivered_to.as_deref().unwrap_or_default();
            let path = home
                .join("chat-controls")
                .join(chat)
                .join(format!("{request}.json"));
            let state = crate::run::RunState::load_under(&run, home)?;
            let action = serde_json::json!({
                "run": run, "repo": state.repo,
                "pr": state.pr.as_ref().map(|pr| pr.url.as_str()),
                "head": head, "runs": workflows,
            });
            std::fs::read(path)
                .ok()
                .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
                .filter(|receipt| receipt["status"] == "applied" && receipt["action"] == action)
                .map(|_| format!("chat-controls/{chat}/{request}.json: applied"))
        }
        Operation::MergePr {
            repo,
            number,
            head,
            request,
        } => {
            let action = crate::chat_merge::Request {
                repo,
                number,
                head,
                request,
            };
            let chat = inquiry
                .delivered_to
                .as_deref()
                .context("merge decision has no chat")?;
            let receipt = merge_receipt(home, chat, &action)?;
            pending_external = receipt
                .as_ref()
                .is_some_and(|receipt| receipt["status"] == "pending");
            if let Some(receipt) = &receipt
                && receipt["status"] != "merged"
                && receipt["status"] != "pending"
            {
                outbox.update_decision(&inquiry.id, |d| d.fail(&format!("Merge outcome requires reconciliation: {}. Reuse the same request ID to check only.", receipt["detail"])))?;
            }
            receipt
                .filter(|receipt| receipt["status"] == "merged")
                .map(|receipt| format!("confirmed merge receipt: {}", receipt["detail"]))
        }
        _ => None,
    };
    if let Some(receipt) = receipt {
        outbox.update_decision(&inquiry.id, |d| d.applied(&receipt))?;
    } else if decision.status == Status::InProgress
        && !pending_external
        && outbox
            .get(&inquiry.id)?
            .decision
            .as_ref()
            .is_some_and(|d| d.status == Status::InProgress)
    {
        let talks = Talks::at(home.join("talks"));
        let chat = inquiry
            .delivered_to
            .as_deref()
            .context("executing decision has no chat")?;
        if !talks.turn_held(chat) && !crate::chat_worker::turn_worker_active(&talks, chat) {
            outbox.update_decision(&inquiry.id, |d| d.fail("Execution ended without a confirmed effect receipt. Inspect the operation before retrying; restart did not replay it."))?;
        }
    }
    Ok(())
}

/// Record the owner's choice for a decision from an open standing chat. The
/// chat agent interprets the owner's request directly, a merge included; no
/// quote, consent phrase or task ownership is required. See [`record_decision`].
pub fn decide(
    talks: &Talks,
    home: &Path,
    talk: &str,
    question: &str,
    choice: &str,
) -> Result<crate::ask::Question> {
    authorize(talks, talk, crate::queue::CHAT_NODE)?;
    record_decision(home, question, choice, None)
}

/// Answer an open decision whose answer the machinery consumes
/// ([`crate::task_chat::awaits_decision`]: a merge or release approval, the
/// posting gate, triage, a divergence reconcile, a structured choice action).
/// The question must still be open and `choice` one of its offered choices;
/// the consumer behind it keeps its own state and transition checks.
fn record_decision(
    home: &Path,
    question: &str,
    choice: &str,
    title: Option<&str>,
) -> Result<crate::ask::Question> {
    use crate::ask::{Answer, Questions};
    let questions = Questions::at(home.join("questions"));
    let id = questions.resolve_id(question)?;
    let q = questions.get(&id)?;
    let queue = Queue::at(home.join("queue"));
    let _claims = decision_claims(&queue, &q)?;
    for task in queue.list() {
        if q.run == task.id
            || task.runs.contains(&q.run)
            || q.routed_task.as_deref() == Some(&task.id)
        {
            ensure!(
                !task.stale_question(&q),
                "question predates task repository reassignment; inspect the current task and release it for fresh execution"
            );
        }
    }
    ensure!(
        crate::task_chat::awaits_decision(&q),
        "question {} is not a decision the machinery waits on; answer it with `magi answer`",
        q.short()
    );
    let (q, ()) = questions.update(&q.id, |r| {
        if crate::task_chat::saved_reply_requires_confirmation(home, r) {
            ensure!(
                crate::task_inquiry::Outbox::at(home)
                    .get(&r.id)?
                    .decision
                    .is_some_and(
                        |decision| decision.status != crate::task_decision::Status::Resolved
                    ),
                "saved decision is settled; no effect remains necessary"
            );
            r.status = crate::ask::QuestionStatus::Open;
            r.answer = None;
            r.answered_at = None;
            r.answer_authority = None;
        }
        ensure!(
            r.status.open(),
            "question {} is already {}",
            r.short(),
            r.status.as_str()
        );
        let reply = r.resolve_reply(choice)?.to_owned();
        ensure!(
            crate::land::approval(Some(&reply)) != crate::land::Approval::Merge || r.merge_target.is_some()
                || !(r.node == crate::land::APPROVAL_NODE || (r.node == crate::bump::NOTICE_NODE && r.seat == "release-watch")),
            "approval has no recorded PR/head; recover its target or discuss a non-merge operation in chat"
        );
        let replacement =
            r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
        ensure!(
            replacement || title.is_none(),
            "--title is only valid for a publication decision's `use my text` choice"
        );
        let title = if replacement {
            let title =
                title.context("use my text needs --title with the literal replacement title")?;
            ensure!(
                !title.trim().is_empty(),
                "replacement title must not be empty"
            );
            Some(title.to_owned())
        } else {
            None
        };
        let answer = if r.free_text() {
            Answer::Text(reply)
        } else {
            Answer::Choice(reply)
        };
        r.publication_title = title;
        r.answer(answer)?;
        Ok(())
    })?;
    Ok(q)
}

/// Fence idle built-in triage answers with grant admission and worker writes.
/// Live drivers must remain answerable (grant admission refuses them). Other
/// question consumers keep their own claims, including synchronous dismissal.
/// Every grant also rechecks answered-but-unsettled effects before acceptance.
pub(crate) fn decision_claims(
    queue: &Queue,
    q: &crate::ask::Question,
) -> Result<Vec<crate::queue::Claim>> {
    let mut owners: Vec<_> = queue
        .list()
        .into_iter()
        .filter(|task| {
            q.run == task.id
                || task.runs.contains(&q.run)
                || q.routed_task.as_deref() == Some(&task.id)
        })
        .map(|task| task.id)
        .collect();
    owners.sort();
    let mut claims = Vec::new();
    if matches!(
        q.node.as_str(),
        crate::triage::NODE | crate::triage::DEPS_NODE
    ) {
        for id in &owners {
            if queue.get(id)?.status != TaskStatus::Running {
                claims.push(queue.claim(id)?);
            }
        }
    }
    for id in owners {
        ensure!(
            !crate::repair_budget::reconcile::superseded_question(&queue.get(&id)?, q),
            "question was superseded by explicit repair receipt recovery; inspect the reconciliation receipt"
        );
    }
    Ok(claims)
}

/// The conversation this process speaks for, or why it may not act.
pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
    if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
        bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
    }
    let id = crate::chat_watch::authorize(talks, run, node)?;
    talks.get(&id)
}

/// The task that recorded `run` (a full run id).
fn run_task(queue: &Queue, run: &str) -> Result<Task> {
    ensure!(
        crate::run::is_run_id(run),
        "an execution command needs the full run id"
    );
    queue
        .list()
        .into_iter()
        .find(|t| t.runs.iter().any(|r| r == run))
        .with_context(|| format!("run {run} belongs to no task"))
}

/// Claim a task from a full or unambiguous-prefix id and read it under the
/// claim, never from a lookup made before it.
fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
    let id = queue.resolve_id(reference)?;
    let claim = queue
        .claim(&id)
        .with_context(|| format!("task {id} is claimed by a running daemon"))?;
    let task = queue.get(&id)?;
    Ok((claim, task))
}

fn claimed_for_chat(
    queue: &Queue,
    reference: &str,
    talks: &Talks,
    chat: &str,
) -> Result<(crate::queue::Claim, Task)> {
    let claimed = claimed(queue, reference)?;
    if let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source() {
        let talk = talks.get(chat)?;
        let goal = talk
            .goals
            .iter()
            .find(|goal| goal.id == id)
            .context("unknown goal")?;
        goal.admit(generation)?;
        let task = &claimed.1;
        ensure!(
            goal.tasks.contains(&task.id),
            "effect targets a task outside this goal"
        );
        crate::chat_goal::require_repo(
            "task",
            &task.id,
            &task.repo,
            goal.effective_repo(&talk.repo),
        )?;
    }
    Ok(claimed)
}

fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
    match task.status {
        TaskStatus::Queued
        | TaskStatus::Held
        | TaskStatus::Failed
        | TaskStatus::Blocked
        | TaskStatus::Parked => Ok(()),
        TaskStatus::Done => bail!(
            "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
            task.id
        ),
        TaskStatus::Running => bail!(
            "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
            task.id
        ),
    }
}

/// Mark a task complete under its queue claim, as `magi task done` does.
pub fn done(queue: &Queue, home: &Path, reference: &str) -> Result<Task> {
    done_claimed(queue, home, claimed(queue, reference)?)
}

fn done_claimed(
    queue: &Queue,
    home: &Path,
    (_claim, mut task): (crate::queue::Claim, Task),
) -> Result<Task> {
    task.succeed();
    // Manual completion also retires earlier attempts when the latest one landed.
    crate::daemon::supersede_prior_runs(&task, home);
    queue.put(&mut task)?;
    Ok(task)
}

/// Change priority under the same claim and state check as the terminal route.
pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
    priority_claimed(queue, claimed(queue, reference)?, priority)
}

fn priority_claimed(
    queue: &Queue,
    (_claim, mut task): (crate::queue::Claim, Task),
    priority: i32,
) -> Result<Task> {
    task.set_priority(priority)?;
    queue.put(&mut task)?;
    Ok(task)
}

/// Hold a task for the owner.
pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
    hold_claimed(queue, claimed(queue, reference)?, reason)
}

fn hold_claimed(
    queue: &Queue,
    (_claim, mut task): (crate::queue::Claim, Task),
    reason: &str,
) -> Result<Task> {
    check_hold_release(&task, "hold")?;
    let reason = reason.trim();
    task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
    queue.put(&mut task)?;
    Ok(task)
}

/// Release a task (the same transition as `magi task release`: the attempt
/// count restarts, the history stays). An operator hold is released too: the
/// owner asked for it.
pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
    release_claimed(queue, claimed(queue, reference)?)
}

fn release_claimed(queue: &Queue, (_claim, mut task): (crate::queue::Claim, Task)) -> Result<Task> {
    check_hold_release(&task, "release")?;
    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
    let run = task.execution_runs().last().cloned();
    let preserved = match run {
        Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
        None => false,
    };
    if !preserved {
        task.release_operator("chat", None);
    }
    queue.put(&mut task)?;
    Ok(task)
}

/// Change a queued or held task's instruction and queue it again, in one
/// save under one claim. Only what [`Task::edit`] allows can be retried; the
/// attempt count follows [`Task::release`] (restarts), while runs, passes and
/// the resumption history are kept.
pub fn retry(
    queue: &Queue,
    reference: &str,
    title: Option<String>,
    instruction: &str,
) -> Result<Task> {
    retry_claimed(queue, claimed(queue, reference)?, title, instruction)
}

fn retry_claimed(
    queue: &Queue,
    (_claim, mut task): (crate::queue::Claim, Task),
    title: Option<String>,
    instruction: &str,
) -> Result<Task> {
    ensure!(
        !instruction.trim().is_empty(),
        "the new instruction is empty"
    );
    if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
        && state
            .base_sync_recovery
            .stop
            .as_ref()
            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
    {
        anyhow::bail!(
            "retry cannot authorize editing a retained base-sync stop. {} Keep the retained review criteria and use a dedicated repair grant for the narrow resolution.",
            state.base_sync_next_action()
        );
    }
    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
    let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
    task.edit(title, instruction.to_owned())?;
    task.release_operator("chat", None);
    queue.put(&mut task)?;
    Ok(task)
}

/// Resume a stopped, blocked or parked run (its task's latest). Only queues
/// the pinned resume; returns the owning task.
pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
    let task = run_task(queue, run)?;
    ensure!(
        task.execution_runs().last().map(String::as_str) == Some(run),
        "only the task's latest run can be resumed"
    );
    crate::resume::validate(home, run)?;
    ensure!(
        crate::resume::pin_queued(queue, run, None, None)?,
        "no queued task owns run {run}"
    );
    queue.get(&task.id)
}

// These reads and input checks cannot start an effect. Keep them shared by
// decision acceptance and execution so invalid input never pins a new request.
fn rerun_preflight(
    queue: &Queue,
    home: &Path,
    run: &str,
    request: &str,
) -> Result<crate::run::RunState> {
    run_task(queue, run)?;
    let state = crate::run::RunState::load_under(run, home)?;
    ensure!(state.pr.is_some(), "the run recorded no pull request");
    ensure!(
        crate::ask::valid_asset_name(request),
        "request must be a safe filename of at most 64 bytes"
    );
    Ok(state)
}

/// チャットのリクエスト単位で受付記録を残し、共通遷移でチェックを再実行する。
pub async fn rerun_checks(
    queue: &Queue,
    home: &Path,
    talk: &str,
    run: &str,
    request: &str,
    head: &str,
    workflows: &[String],
) -> Result<Vec<String>> {
    let state = rerun_preflight(queue, home, run, request).map_err(BeforeEffect)?;
    let dir = home.join("chat-controls").join(talk);
    std::fs::create_dir_all(&dir)?;
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(dir.join(format!("{request}.lock")))?;
    crate::pr_head::try_lock_file(&lock).map_err(|error| BeforeEffect(error.into()))?;
    let path = dir.join(format!("{request}.json"));
    let pr = &state
        .pr
        .as_ref()
        .context("the run recorded no pull request")?
        .url;
    let action = serde_json::json!({
        "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
    });
    if path.exists() {
        let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
        if prior["action"] != action {
            return Err(BeforeEffect(anyhow::anyhow!(
                "request ID already binds a different operation"
            ))
            .into());
        }
        ensure!(
            prior["status"] == "applied",
            "previous request has an uncertain result; inspect its receipt before a new request"
        );
        return Ok(workflows.to_vec());
    }
    let record = |status: &str| -> Result<()> {
        let tmp = path.with_extension("tmp");
        std::fs::write(
            &tmp,
            serde_json::to_vec(&serde_json::json!({
                "action": action, "status": status
            }))?,
        )?;
        std::fs::rename(tmp, &path)?;
        Ok(())
    };
    let operation = format!("chat:{talk}:{request}");
    let started = std::sync::atomic::AtomicBool::new(false);
    crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
        // Once a receipt exists, failure must remain uncertain even if the
        // external command has not returned yet.
        started.store(true, std::sync::atomic::Ordering::SeqCst);
        record("started")
    })
    .await
    .map_err(|error| {
        if started.load(std::sync::atomic::Ordering::SeqCst) {
            error
        } else {
            anyhow::Error::new(BeforeEffect(error))
        }
    })?;
    record("applied")?;
    Ok(workflows.to_vec())
}

/// Abandon a recorded run whose driver is proven gone. No confirmation phrase
/// is needed; an unknown or live driver is refused by
/// [`crate::driver::abandon_proven_dead`], so a working driver is never broken.
pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
    run_task(queue, run)?;
    crate::driver::abandon_proven_dead(home, run)
}

/// One line a person or agent can read after a successful command.
pub fn describe(task: &Task, what: &str) -> String {
    let status = match task.status {
        TaskStatus::Queued => "queued",
        _ => task.status.as_str(),
    };
    format!("{what} {} {} ({status})", task.short(), task.title)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::queue::Source;
    use jiff::Timestamp;

    fn talk(talks: &Talks, id: &str) -> Talk {
        let mut t: Talk = serde_json::from_value(serde_json::json!({
            "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
            "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
            "seat":crate::agent::SeatState::new("talk","worker",1)
        }))
        .unwrap();
        talks.put(&mut t).unwrap();
        t
    }

    fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
        let mut t = Task::new(
            text.into(),
            text.into(),
            ".".into(),
            Source::Agent {
                run: talk.into(),
                node: crate::queue::CHAT_NODE.into(),
            },
        );
        queue.put(&mut t).unwrap();
        t
    }

    #[test]
    fn ownerless_import_reconciliation_requires_effect_evidence_not_saved_consent() {
        use crate::ask::{Answer, Question, Questions};
        let home = tempfile::tempdir().unwrap();
        let home = home.path();
        let queue = Queue::at(home.join("queue"));
        let talks = Talks::at(home.join("talks"));
        let questions = Questions::at(home.join("questions"));
        let mut q = Question::new(
            String::new(),
            crate::bump::NOTICE_NODE.into(),
            "release-watch".into(),
            "Historical release hold".into(),
            String::new(),
            vec!["hold".into()],
        );
        q.answer(Answer::Choice("hold".into())).unwrap();
        q.answer_delivered = true;
        questions.put(&mut q).unwrap();
        let source = std::fs::read(questions.path_of(&q.id)).unwrap();
        crate::task_chat::sweep(&queue, &talks, &questions, home);
        assert!(reconcile_task_decision(&queue, home, "authorized-chat", &q.id).is_err());
        let outbox = crate::task_inquiry::Outbox::at(home);
        assert_eq!(
            outbox.get(&q.id).unwrap().decision.unwrap().status,
            crate::task_decision::Status::RetryNeeded
        );
        let dir = home.join("release-watch-receipts");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(format!("{}.json", q.id)),
            serde_json::to_vec(&crate::release_watch::WatchState {
                applied: vec![q.id.clone()],
                ..Default::default()
            })
            .unwrap(),
        )
        .unwrap();
        for _ in 0..2 {
            reconcile_task_decision(&queue, home, "authorized-chat", &q.id).unwrap();
        }
        let decision = outbox.get(&q.id).unwrap().decision.unwrap();
        assert_eq!(decision.status, crate::task_decision::Status::Resolved);
        assert!(decision.request.is_none());
        assert!(decision.source_answer_at.is_none());
        assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), source);
        assert!(queue.list().is_empty());
        assert!(talks.list().is_empty());
    }

    #[test]
    fn resume_recovery_waits_for_the_inquiry_publisher() {
        let tmp = tempfile::tempdir().unwrap();
        let queue = Queue::at(tmp.path().join("queue"));
        let mut task = filed(&queue, "talk-a", "work");
        let mut state = crate::run::RunState::new(
            task.repo.clone(),
            "main".into(),
            "base".into(),
            "work".into(),
            crate::config::Config::default(),
        );
        state.status = crate::run::RunStatus::Blocked;
        state.driver_exited = true;
        state.save_under(tmp.path()).unwrap();
        task.runs.push(state.id.clone());
        queue.put(&mut task).unwrap();
        let outbox = crate::task_inquiry::Outbox::at(tmp.path());
        let inquiry = outbox
            .file(
                &task,
                Some(state.id.clone()),
                "resume".into(),
                "Resume?",
                "",
            )
            .unwrap();
        let request = serde_json::to_string(&Operation::Resume {
            run: state.id.clone(),
        })
        .unwrap();
        outbox
            .update_decision(&inquiry.id, |d| {
                d.accept(&request)?;
                d.start()
            })
            .unwrap();
        let before = outbox.get(&inquiry.id).unwrap().decision.unwrap();
        let publisher = outbox.execution_claim(&inquiry.id).unwrap();
        reconcile_decisions(&queue, tmp.path()).unwrap();
        assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), before);
        drop(publisher);
        reconcile_decisions(&queue, tmp.path()).unwrap();
        let recovered = outbox.get(&inquiry.id).unwrap().decision.unwrap();
        assert_eq!(recovered.status, crate::task_decision::Status::RetryNeeded);
        assert!(recovered.retry_safe);
    }

    #[tokio::test]
    async fn resume_receipt_matches_checkout_root_not_filing_directory() {
        use crate::task_decision::Status;
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let repo = home.join("checkout");
        let subdir = repo.join("src");
        let foreign = home.join("foreign");
        std::fs::create_dir_all(&subdir).unwrap();
        std::fs::create_dir(&foreign).unwrap();
        for checkout in [&repo, &foreign] {
            crate::git::git(checkout, &["init", "-q"]).await.unwrap();
        }
        let queue = Queue::at(home.join("queue"));
        let mut task = Task::new("work".into(), "work".into(), subdir, Source::Human);
        let mut state = crate::run::RunState::new(
            repo,
            "main".into(),
            "base".into(),
            "work".into(),
            crate::config::Config::default(),
        );
        state.reserve_under(home).unwrap();
        task.runs.push(state.id.clone());
        queue.put(&mut task).unwrap();
        let outbox = crate::task_inquiry::Outbox::at(home);
        let inquiry = outbox
            .file(
                &task,
                Some(state.id.clone()),
                "resume".into(),
                "Resume?",
                "",
            )
            .unwrap();
        let request = serde_json::to_string(&Operation::Resume {
            run: state.id.clone(),
        })
        .unwrap();
        outbox
            .update_decision(&inquiry.id, |d| {
                d.accept(&request)?;
                d.start()
            })
            .unwrap();
        task.dispatched_resumes
            .insert(inquiry.id.clone(), state.id.clone());
        queue.put(&mut task).unwrap();
        reconcile_decisions(&queue, home).unwrap();
        assert_eq!(
            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
            Status::InProgress
        );

        state.carry_dispatched_resumes(&task);
        state.begin_pass();
        state.save_under(home).unwrap();
        let mut reassigned = task.clone();
        reassigned.repo = foreign;
        assert!(resume_started(home, &reassigned, &inquiry.id, &state.id).is_err());
        reconcile_decisions(&queue, home).unwrap();
        assert_eq!(
            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
            Status::Resolved
        );
    }

    #[test]
    fn only_the_chat_seat_of_an_open_talk_is_authorized() {
        let tmp = tempfile::tempdir().unwrap();
        let talks = Talks::at(tmp.path().join("talks"));
        let t = talk(&talks, "talk-a");
        assert!(authorize(&talks, &t.id, "chat").is_ok());
        assert!(authorize(&talks, &t.id, "deputy").is_err());
        assert!(authorize(&talks, &t.id, "").is_err());
        assert!(authorize(&talks, "", "chat").is_err());
        assert!(
            authorize(&talks, "talk-", "chat").is_err(),
            "prefix is not an id"
        );
    }

    #[test]
    fn tasks_of_any_origin_are_controlled_on_request() {
        let tmp = tempfile::tempdir().unwrap();
        let queue = Queue::at(tmp.path().join("queue"));
        let theirs = filed(&queue, "talk-b", "theirs");
        let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
        hand.hold_manual(Some("operator".into()));
        queue.put(&mut hand).unwrap();
        // Another chat's task and an operator-held human task are the owner's
        // work too: the request goes through without any ownership scope.
        assert_eq!(
            hold(&queue, &theirs.id, "wait").unwrap().status,
            TaskStatus::Held
        );
        assert_eq!(
            release(&queue, &hand.id).unwrap().status,
            TaskStatus::Queued
        );
        let again = retry(&queue, &theirs.id, None, "new").unwrap();
        assert_eq!(again.instruction, "new");
        assert_eq!(again.status, TaskStatus::Queued);
    }

    #[test]
    fn hold_then_release_keeps_history_and_restarts_attempts() {
        let tmp = tempfile::tempdir().unwrap();
        let queue = Queue::at(tmp.path().join("queue"));
        let mut t = filed(&queue, "talk-a", "work");
        t.attempts = 3;
        t.runs.push("20260101-000000-aaaa".into());
        queue.put(&mut t).unwrap();
        let held = hold(&queue, &t.id, "owner asked").unwrap();
        assert_eq!(held.status, TaskStatus::Held);
        assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
        let back = release(&queue, &t.id).unwrap();
        assert_eq!(back.status, TaskStatus::Queued);
        assert_eq!(back.attempts, 0);
        assert_eq!(back.runs, t.runs);
        assert!(back.resumption.is_some());
    }

    #[test]
    fn hold_and_release_refuse_done_and_running_without_saving() {
        let tmp = tempfile::tempdir().unwrap();
        let queue = Queue::at(tmp.path().join("queue"));
        for status in [TaskStatus::Done, TaskStatus::Running] {
            let mut t = filed(&queue, "talk-a", "work");
            t.start("20260101-000000-aaaa".into());
            if status == TaskStatus::Done {
                t.succeed();
            }
            queue.put(&mut t).unwrap();
            let before = std::fs::read(queue.path_of(&t.id)).unwrap();
            for operation in ["hold", "release"] {
                let error = if operation == "hold" {
                    hold(&queue, &t.id, "owner asked")
                } else {
                    release(&queue, &t.id)
                }
                .unwrap_err()
                .to_string();
                assert!(error.contains(operation), "{error}");
                assert!(error.contains(&t.id), "{error}");
                assert!(error.contains(status.as_str()), "{error}");
                let guidance = if status == TaskStatus::Done {
                    "create a new task"
                } else {
                    "use resume or abandon"
                };
                assert!(error.contains(guidance), "{error}");
                assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
            }
        }
    }

    #[test]
    fn hold_and_release_allow_unfinished_inactive_tasks() {
        let tmp = tempfile::tempdir().unwrap();
        let queue = Queue::at(tmp.path().join("queue"));
        for status in [
            TaskStatus::Queued,
            TaskStatus::Held,
            TaskStatus::Failed,
            TaskStatus::Blocked,
            TaskStatus::Parked,
        ] {
            for operation in ["hold", "release"] {
                let mut t = filed(&queue, "talk-a", "work");
                t.status = status;
                t.hold_reason = Some("old reason".into());
                t.attempts = 3;
                t.runs.push("20260101-000000-aaaa".into());
                queue.put(&mut t).unwrap();
                let changed = if operation == "hold" {
                    let held = hold(&queue, &t.id, " new reason ").unwrap();
                    assert_eq!(held.status, TaskStatus::Held);
                    assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
                    assert_eq!(held.attempts, t.attempts);
                    held
                } else {
                    let released = release(&queue, &t.id).unwrap();
                    assert_eq!(released.status, TaskStatus::Queued);
                    assert_eq!(released.attempts, 0);
                    assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
                    released
                };
                assert_eq!(changed.runs, t.runs);
                assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
            }
        }
    }

    #[test]
    fn retry_edits_and_requeues_in_one_save() {
        let tmp = tempfile::tempdir().unwrap();
        let queue = Queue::at(tmp.path().join("queue"));
        let mut t = filed(&queue, "talk-a", "old text");
        t.runs.push("20260101-000000-aaaa".into());
        t.attempts = 2;
        t.hold_manual(Some("stopped".into()));
        queue.put(&mut t).unwrap();
        let again = retry(&queue, &t.id, None, "new text").unwrap();
        assert_eq!(again.instruction, "new text");
        assert_eq!(again.status, TaskStatus::Queued);
        assert_eq!(again.attempts, 0);
        assert_eq!(again.runs, t.runs, "run history is kept");
        assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
        assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
        // A running task cannot be edited: nothing is changed.
        let mut running = filed(&queue, "talk-a", "busy");
        running.start("20260101-000000-bbbb".into());
        queue.put(&mut running).unwrap();
        assert!(retry(&queue, &running.id, None, "x").is_err());
        assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
        assert!(retry(&queue, &t.id, None, "  ").is_err());
    }

    #[test]
    fn execution_commands_need_the_full_id_of_a_recorded_run() {
        let tmp = tempfile::tempdir().unwrap();
        let queue = Queue::at(tmp.path().join("queue"));
        let mut t = filed(&queue, "talk-b", "work");
        t.runs.push("20260101-000000-aaaa".into());
        queue.put(&mut t).unwrap();
        assert_eq!(
            run_task(&queue, "20260101-000000-aaaa").unwrap().id,
            t.id,
            "any chat may address another chat's run"
        );
        assert!(run_task(&queue, "aaaa").is_err());
        assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
        assert!(resume(&queue, tmp.path(), "aaaa").is_err());
    }

    #[test]
    fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
        let tmp = tempfile::tempdir().unwrap();
        let queue = Queue::at(tmp.path().join("queue"));
        let mut t = filed(&queue, "talk-b", "work");
        t.runs.push("20260101-000000-aaaa".into());
        queue.put(&mut t).unwrap();
        // A run no task recorded is refused before liveness is judged.
        assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
        // A recorded run whose driver is not proven dead (here: no state to
        // judge at all) is never abandoned.
        assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
    }
}

#[cfg(test)]
mod goal_admission_tests {
    use super::*;

    #[tokio::test]
    async fn goal_effects_require_current_generation_scope_and_no_new_owner_input() {
        let tmp = tempfile::tempdir().unwrap();
        let talks = Talks::at(tmp.path().join("talks"));
        let queue = Queue::at(tmp.path().join("queue"));
        let target = tmp.path().join("target");
        std::fs::create_dir(&target).unwrap();
        crate::git::git(&target, &["init", "-q"]).await.unwrap();
        let mut talk = crate::talk::seeded_for_test("goal-effect", tmp.path().into());
        talk.turns.push(
            serde_json::from_value(serde_json::json!({
                "sender": "operator", "who": "operator", "body": "Follow this task through",
                "at": jiff::Timestamp::now()
            }))
            .unwrap(),
        );
        talks.put(&mut talk).unwrap();
        let mut task = Task::new(
            "work".into(),
            "work".into(),
            target.clone(),
            crate::queue::Source::Agent {
                run: talk.id.clone(),
                node: crate::queue::CHAT_NODE.into(),
            },
        );
        queue.put(&mut task).unwrap();
        let mut unrelated = Task::new(
            "other".into(),
            "other".into(),
            target.clone(),
            crate::queue::Source::Agent {
                run: talk.id.clone(),
                node: crate::queue::CHAT_NODE.into(),
            },
        );
        queue.put(&mut unrelated).unwrap();
        crate::chat_goal::apply(
            &queue,
            tmp.path(),
            &talks,
            &talk.id,
            &crate::chat_goal::Source::Input { turn: 0 },
            crate::chat_goal::Command::Establish {
                id: "g".into(),
                purpose: "Deliver this task".into(),
                scope: "This task only".into(),
                condition: "Verified delivery".into(),
                completion: crate::chat_goal::Completion::TasksDone,
                repo: Some(target),
                tasks: vec![task.id.clone()],
                runs: vec![],
                watches: vec![],
            },
        )
        .await
        .unwrap();
        talks
            .mutate(&talk.id, |talk| {
                let boundary = talk.turns.len();
                let goal = &mut talk.goals[0];
                goal.wake = 1;
                goal.started = Some(1);
                goal.launch_turns = Some(boundary);
                Ok(())
            })
            .unwrap();
        let source = crate::chat_goal::Source::Goal {
            id: "g".into(),
            generation: 1,
        };
        assert!(
            execute_authenticated(
                &queue,
                tmp.path(),
                &talks,
                &talk.id,
                source.clone(),
                Operation::Priority {
                    task: unrelated.id.clone(),
                    priority: 8
                }
            )
            .await
            .is_err()
        );
        execute_authenticated(
            &queue,
            tmp.path(),
            &talks,
            &talk.id,
            source.clone(),
            Operation::Priority {
                task: task.id.clone(),
                priority: 3,
            },
        )
        .await
        .unwrap();
        let hold = Operation::Hold {
            task: task.id.clone(),
            reason: "pause".into(),
        };
        crate::chat_goal::with_source(source.clone(), async {
            // Reassignment publishes under this same claim, between the first
            // admission and the mutation's claim acquisition.
            admit_goal_operation(&queue, tmp.path(), &talks, &talk.id, &hold).unwrap();
            let original = task.repo.clone();
            {
                let claim = queue.claim(&task.id).unwrap();
                task = queue.get(&task.id).unwrap();
                task.repo = talk.repo.clone();
                queue.put(&mut task).unwrap();
                drop(claim);
            }
            let result = claimed_for_chat(&queue, &task.id, &talks, &talk.id)
                .and_then(|claimed| hold_claimed(&queue, claimed, "pause"));
            assert!(result.unwrap_err().to_string().contains(&task.id));
            assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
            task.repo = original;
            queue.put(&mut task).unwrap();
        })
        .await;
        talks
            .mutate(&talk.id, |talk| {
                talk.turns.push(serde_json::from_value(serde_json::json!({
                    "sender": "operator", "who": "operator", "body": "Stop",
                    "at": jiff::Timestamp::now()
                }))?);
                Ok(())
            })
            .unwrap();
        assert!(
            execute_authenticated(
                &queue,
                tmp.path(),
                &talks,
                &talk.id,
                source.clone(),
                Operation::Priority {
                    task: task.id.clone(),
                    priority: 9
                }
            )
            .await
            .is_err()
        );
        talks
            .mutate(&talk.id, |talk| {
                talk.turns.pop();
                talk.goals[0].state = crate::chat_goal::State::Stopped;
                talk.goals[0].wake = 2;
                talk.goals[0].started = None;
                Ok(())
            })
            .unwrap();
        assert!(
            execute_authenticated(
                &queue,
                tmp.path(),
                &talks,
                &talk.id,
                source,
                Operation::Priority {
                    task: task.id.clone(),
                    priority: 9
                }
            )
            .await
            .is_err()
        );
        assert_eq!(queue.get(&task.id).unwrap().priority, 3);
    }
}