vpf-runner 0.4.0

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

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};

use jiff::Timestamp;
use serde::Serialize;
use serde::de::DeserializeOwned;
use vpf::{By, OnFail, Plan, Proof, Prover, Step, Tool};

use crate::agent::{Agent, AgentAnswer, AgentRequest, Role};
use crate::command::{self, TimeOver};
use crate::fill::{fill, text};
use crate::folder;
use crate::journal::{Entry, Journal, Keeper, stamp};
use crate::needs::{describe, meets};
use crate::person::Person;
use crate::person::{Ask, Verdict};
use crate::record::{
    Attempt, Decision, ItemRecord, Outcome, ProofRecord, Record, Reply, StepRecord, Version, Wait,
    Waiting, runs, spent_this_month,
};
use crate::time::{Clock, Moment, SystemClock, words};

const ALL_TOOLS: [&str; 5] = ["read", "write", "commands", "internet", "screen"];

/// Before a step is done for more items than this, the person is asked.
const MANY_ITEMS: usize = 200;

/// How many agents and commands work at once, unless the runner is told otherwise.
const AT_ONCE: usize = 8;

/// What the person may do when a step passes its deadline.
const LATE: [&str; 3] = [
    "wait until a later deadline",
    "go on without it",
    "stop the run",
];

fn tool_name(tool: Tool) -> &'static str {
    match tool {
        Tool::Read => "read",
        Tool::Write => "write",
        Tool::Commands => "commands",
        Tool::Internet => "internet",
        Tool::Screen => "screen",
    }
}

fn by_name(by: By) -> &'static str {
    match by {
        By::Agent => "agent",
        By::Algorithm => "algorithm",
        By::Person => "person",
        By::Plan => "plan",
    }
}

fn prover_name(by: Prover) -> &'static str {
    match by {
        Prover::Algorithm => "algorithm",
        Prover::Agent => "agent",
        Prover::Person => "person",
    }
}

/// Why a run does not go on now.
#[derive(Debug)]
enum Halt {
    /// It stops, for this reason.
    Stop(String),
    /// It waits for what the runner keeps in its list of what is waited for.
    Pause,
    /// The work it asked for failed, with these points against it: its agent ended with an error, or it cannot be
    /// undone and was not done when the run stopped. The work is refused with them; out of such work, the run stops.
    Failed(String),
}

impl Halt {
    /// The halt out of any work: an agent's error stops the run.
    fn out_of_work(self) -> Self {
        match self {
            Self::Failed(why) => Self::Stop(why),
            other => other,
        }
    }
}

/// How the points against work begin when its agent ended with an error.
const AGENT_ERROR: &str = "The agent ended with an error: ";

/// The points against work that cannot be undone, when the person says it was not done before the run stopped.
const NOT_DONE: &str =
    "The run stopped before this work ended, and the person said it was not done.";

/// Where work that cannot be undone stands as an attempt begins.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Out {
    /// It is to be done, or is being done now.
    Fresh,
    /// The run stopped while it was out, and the person said it was done, and what it answered.
    Done(String),
    /// The run stopped while it was out, and the person said it was not done.
    NotDone,
    /// The person did not start it, and sent the work back to these earlier steps, with these points.
    Back(Vec<String>, String),
}

impl From<String> for Halt {
    fn from(reason: String) -> Self {
        Self::Stop(reason)
    }
}

/// The texts references name: `asked`, the answers of the steps done, and `item`.
type Values = HashMap<String, String>;

/// Where a step stands in a run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
    /// Not done: waiting, or to be done again.
    Open,
    /// Its work is done and every proof passed.
    Passed,
    /// Not on the path taken, or left out by the person.
    Skipped,
    /// Started, and waiting for an answer: the steps that wait for it wait too.
    Parked,
}

impl State {
    fn ended(self) -> bool {
        matches!(self, Self::Passed | Self::Skipped)
    }
}

/// What the run knows of one step.
#[derive(Clone, Debug)]
struct Progress {
    state: State,
    answer: String,
    done: Option<Timestamp>,
    /// Refused attempts since the person last said to go on.
    refused: u32,
    /// The last answer and the points against it, when its work was sent back.
    again: Option<(String, String)>,
    /// How many times it has started.
    rounds: u32,
}

impl Default for Progress {
    fn default() -> Self {
        Self {
            state: State::Open,
            answer: String::new(),
            done: None,
            refused: 0,
            again: None,
            rounds: 0,
        }
    }
}

/// How a step's work ended.
enum Ended {
    Passed(String),
    /// The person went on without it.
    LeftOut,
    /// A proof refused it and sent the work back to these earlier steps.
    Back {
        to: Vec<String>,
        points: String,
    },
}

/// Runs plans in a folder, with an agent and a person.
pub struct Runner<'a> {
    folder: PathBuf,
    plans: PathBuf,
    agent: &'a dyn Agent,
    person: &'a mut dyn Person,
    clock: Box<dyn Clock + 'a>,
    time_cap: Option<Duration>,
    name: Option<String>,
    detach: bool,
    at_once: usize,
    // What one run has used so far.
    end: Option<Timestamp>,
    repeats: u32,
    cost: f64,
    cost_limit: Option<f64>,
    unmeasured: bool,
    told_unmeasured: bool,
    decisions: Vec<Decision>,
    stack: Vec<String>,
    journal: Journal,
    waiting: Vec<Waiting>,
    /// What the person is told while the run goes over what it was given before, told once it goes past it.
    held: Vec<String>,
    /// The agents and commands the run would ask now, to be started.
    jobs: Vec<(String, Job)>,
    /// The keys of the agents and commands working now.
    working: HashSet<String>,
    /// The keys of the agents and commands asked in this session, working or waiting for their turn.
    asked: HashSet<String>,
    /// Why agents and commands that ended could not answer, by key.
    failures: HashMap<String, String>,
    /// The soonest time a step waits for, and the step.
    soonest: Option<(Timestamp, String)>,
    /// The folder as it was when each attempt began its work, by the attempt's key, to tell its proofs what changed.
    before: HashMap<String, folder::Snapshot>,
    /// The record of the run as it started, kept again while work that cannot be undone is out.
    draft: Option<Record>,
    /// The work that cannot be undone that is out now: the question a run that stopped meanwhile asks of each.
    out: Vec<Waiting>,
    /// Who is handed each entry as it is kept.
    keeper: Option<&'a mut dyn Keeper>,
    /// The entries the run holds that were handed out, or that it was given, by key.
    handed: HashMap<String, Entry>,
}

impl<'a> Runner<'a> {
    /// A runner for plans that work in `folder`, finding other plans by name in the same folder.
    pub fn new(folder: &Path, agent: &'a dyn Agent, person: &'a mut dyn Person) -> Self {
        Self {
            folder: folder.to_owned(),
            plans: folder.to_owned(),
            agent,
            person,
            clock: Box::new(SystemClock),
            time_cap: None,
            name: None,
            detach: false,
            at_once: AT_ONCE,
            end: None,
            repeats: 3,
            cost: 0.0,
            cost_limit: None,
            unmeasured: false,
            told_unmeasured: false,
            decisions: Vec::new(),
            stack: Vec::new(),
            journal: Journal::default(),
            waiting: Vec::new(),
            held: Vec::new(),
            jobs: Vec::new(),
            working: HashSet::new(),
            asked: HashSet::new(),
            failures: HashMap::new(),
            soonest: None,
            before: HashMap::new(),
            draft: None,
            out: Vec::new(),
            keeper: None,
            handed: HashMap::new(),
        }
    }

    /// Finds the plans that steps name in this folder, `name.vpf.json`.
    pub fn plans_in(&mut self, plans: &Path) -> &mut Self {
        plans.clone_into(&mut self.plans);
        self
    }

    /// Ends each run within this time, even when its plan allows more. A run that goes on later has this time
    /// again.
    pub fn time_limit(&mut self, limit: Duration) -> &mut Self {
        self.time_cap = Some(limit);
        self
    }

    /// Reads and waits on this clock instead of the computer's.
    pub fn clock(&mut self, clock: Box<dyn Clock + 'a>) -> &mut Self {
        self.clock = clock;
        self
    }

    /// Keeps a record of each run in the folder's `.vpf/runs`, under the plan's name, and keeps to the plan's
    /// `limits.month` across them.
    pub fn keep_records(&mut self, name: &str) -> &mut Self {
        self.name = Some(name.to_owned());
        self
    }

    /// Asks no one and waits for no time: whatever a run would ask a person, and any time it would wait for,
    /// leaves it waiting, holding nothing, while the steps that do not wait for it go on.
    pub fn detach(&mut self, detach: bool) -> &mut Self {
        self.detach = detach;
        self
    }

    /// Has no more than this many agents and commands work at once, 8 when not told. Steps that wait for none
    /// of each other, and the items of a step, are done at the same time up to it.
    pub fn at_once(&mut self, most: usize) -> &mut Self {
        self.at_once = most.max(1);
        self
    }

    /// Hands each entry a run keeps to `keeper` as soon as it is kept, and tells it each record a run begins with,
    /// so that a host keeps the run in its own store.
    pub fn keeper(&mut self, keeper: &'a mut dyn Keeper) -> &mut Self {
        self.keeper = Some(keeper);
        self
    }

    /// Runs a plan that has no problems, started with `asked`.
    pub fn run(&mut self, plan: &Plan, asked: &str) -> Record {
        let started = self.clock.now();
        let id = self.new_id(started);
        let version = Version {
            plan: plan.clone(),
            approved_by: None,
            from: None,
            at: started,
        };
        self.go(id, vec![version], asked, started, Vec::new())
    }

    /// Goes on with a run from its record: from where it stands, with the replies it was given since and the
    /// last version of its plan, asking nothing again that it was given before.
    pub fn resume(&mut self, record: &Record) -> Record {
        if record.versions.is_empty() {
            let mut record = record.clone();
            record.outcome = Outcome::Stopped(
                "the run keeps no version of its plan, so it cannot go on".to_owned(),
            );
            return record;
        }
        self.name.clone_from(&record.plan);
        self.go(
            record.id.clone(),
            record.versions.clone(),
            &record.asked,
            record.started,
            record.journal.clone(),
        )
    }

    /// A new run's id: when it started and the plan's name, not yet kept in the folder.
    fn new_id(&self, started: Timestamp) -> String {
        let stamp = started.to_string().replace(':', "-");
        let name = self.name.as_deref().unwrap_or("plan");
        let mut id = format!("{stamp}-{name}");
        let mut count = 1;
        while self.name.is_some() && runs(&self.folder).join(format!("{id}.json")).exists() {
            count += 1;
            id = format!("{stamp}-{name}-{count}");
        }
        id
    }

    fn go(
        &mut self,
        id: String,
        versions: Vec<Version>,
        asked: &str,
        started: Timestamp,
        journal: Vec<Entry>,
    ) -> Record {
        let plan = versions
            .last()
            .map(|version| version.plan.clone())
            .expect("a run has a plan");
        let fresh = journal.is_empty();
        let limits = plan.limits();
        self.end = limits
            .deadline
            .as_deref()
            .and_then(Moment::read)
            .map(|deadline| deadline.from(started));
        if let Some(cap) = self.time_cap {
            let cap = self
                .clock
                .now()
                .saturating_add(
                    jiff::SignedDuration::try_from(cap).unwrap_or(jiff::SignedDuration::MAX),
                )
                .unwrap_or(Timestamp::MAX);
            self.end = Some(self.end.map_or(cap, |end| end.min(cap)));
        }
        self.repeats = limits.repeats.unwrap_or(3).max(1);
        self.cost = 0.0;
        self.cost_limit = limits.cost;
        self.unmeasured = false;
        self.told_unmeasured = false;
        self.held = Vec::new();
        self.failures = HashMap::new();
        self.asked = HashSet::new();

        let draft = Record {
            id,
            plan: self.name.clone(),
            wish: fill(
                &plan.wish,
                &Values::from([("asked".to_owned(), asked.to_owned())]),
            ),
            asked: asked.to_owned(),
            started,
            ended: started,
            outcome: Outcome::Waiting(Vec::new()),
            cost: 0.0,
            cost_unmeasured: false,
            steps: Vec::new(),
            decisions: Vec::new(),
            versions,
            journal: Vec::new(),
        };
        self.draft = self.name.is_some().then(|| draft.clone());
        self.handed = journal
            .iter()
            .map(|entry| (entry.key.clone(), entry.clone()))
            .collect();
        if let Some(keeper) = self.keeper.as_deref_mut() {
            let mut begun = draft.clone();
            begun.journal.clone_from(&journal);
            keeper.begin(&begun);
        }

        let spent = match (&self.name, limits.month) {
            (Some(name), Some(_)) if fresh => spent_this_month(&self.folder, name, started),
            _ => 0.0,
        };
        let (ended, steps) = match limits.month {
            Some(month) if spent >= month => {
                self.journal = Journal::new(journal, started);
                let reason = format!(
                    "this month's runs of the plan have spent {spent}, which reaches its limit of {month} for the month"
                );
                (Err(Halt::Stop(reason)), Vec::new())
            }
            _ => self.waves(&plan, asked, started, journal),
        };
        self.told();
        let outcome = match ended {
            Ok(_) => Outcome::Done,
            Err(Halt::Stop(reason)) => Outcome::Stopped(reason),
            Err(Halt::Failed(why)) => Outcome::Stopped(why),
            Err(Halt::Pause) => Outcome::Waiting(std::mem::take(&mut self.waiting)),
        };
        let journal = self.journal.entries();
        let record = self.as_it_stands(draft, outcome, steps, journal);
        if let Some(name) = self.name.clone() {
            if let Err(error) = record.keep(&self.folder) {
                self.person.tell(&format!(
                    "The record of this run could not be kept: {error}"
                ));
            } else {
                // How work that cannot be undone ended is in the record now.
                let _ = fs::remove_dir_all(runs(&self.folder).join(format!("{}.out", record.id)));
            }
            if let Some(month) = limits.month {
                let total = spent_this_month(&self.folder, &name, started);
                if total >= month * 0.8 {
                    self.person.tell(&format!(
                        "The runs of this plan have spent {total} of its {month} for the month: four fifths or more."
                    ));
                }
            }
        }
        record
    }

    /// Goes over the run again and again, from the start, with what it was given so far, until it ends or waits for
    /// people or a time: each time over, it starts the agents and commands the steps would ask now, at once, and
    /// goes over it again when one of them answers.
    fn waves(
        &mut self,
        plan: &Plan,
        asked: &str,
        started: Timestamp,
        mut entries: Vec<Entry>,
    ) -> (Result<String, Halt>, Vec<StepRecord>) {
        let agent = self.agent;
        let folder = self.folder.clone();
        thread::scope(|scope| {
            let (send, receive) = mpsc::channel::<(String, Finished)>();
            // The guard of each agent that may only read and works now, and the folder before they began.
            let mut readers: HashMap<String, String> = HashMap::new();
            let mut before: Option<u64> = None;
            // Whether work that cannot be undone was out when the run went over it last.
            let mut was_out = false;
            loop {
                self.journal = Journal::new(entries.clone(), started);
                self.cost = 0.0;
                self.unmeasured = false;
                self.decisions = Vec::new();
                self.stack = self.name.iter().cloned().collect();
                self.waiting = Vec::new();
                self.jobs = Vec::new();
                self.soonest = None;
                self.out = Vec::new();
                let mut steps = Vec::new();
                let ended = self
                    .steps(plan, asked, &mut steps, "")
                    .map_err(Halt::out_of_work);
                entries = self.journal.entries();
                // Whenever the run was given something new, while work that cannot be undone is out, and once more
                // when it ends, the record is kept, so that a run that stops meanwhile goes on from there, and asks
                // whether work that cannot be undone was done instead of doing it again.
                let given = self.hand_out(&entries);
                if given || was_out || !self.out.is_empty() {
                    self.keep_meanwhile(&steps, &entries);
                }
                was_out = !self.out.is_empty();

                if !matches!(ended, Err(Halt::Stop(_))) {
                    for (key, job) in std::mem::take(&mut self.jobs) {
                        if self.working.len() >= self.at_once || self.working.contains(&key) {
                            continue;
                        }
                        let guard = job.guard();
                        // An agent that may only read works only while nothing writes, so that what it changes
                        // is known to be its own.
                        let writing = self.working.len() > readers.len();
                        if guard.is_some() && writing || guard.is_none() && !readers.is_empty() {
                            continue;
                        }
                        if let Some(guard) = guard {
                            if readers.is_empty() {
                                before = Some(folder::digest(&folder));
                            }
                            readers.insert(key.clone(), guard.to_owned());
                        }
                        self.working.insert(key.clone());
                        let send = send.clone();
                        let deadline = self.instant();
                        let cost_left = self
                            .cost_limit
                            .filter(|_| !self.unmeasured)
                            .map(|limit| (limit - self.cost).max(0.0));
                        let folder = &folder;
                        scope.spawn(move || {
                            let finished = job.run(&key, agent, folder, deadline, cost_left);
                            let _ = send.send((key, finished));
                        });
                    }
                }
                if self.working.is_empty() || matches!(ended, Err(Halt::Stop(_))) {
                    if let (Err(Halt::Pause), Some((at, step)), false) =
                        (&ended, self.soonest.clone(), self.detach)
                    {
                        if self.working.is_empty() {
                            self.tell(&format!("Waiting until {} for the step {step}.", words(at)));
                            self.told();
                            self.clock
                                .wait_until(self.end.map_or(at, |end| end.min(at)));
                            continue;
                        }
                    }
                    self.working.clear();
                    return (ended, steps);
                }
                let mut finished = Vec::new();
                let first = match self.soonest.as_ref().map(|(at, _)| *at) {
                    Some(at) => {
                        let left = Duration::try_from(at.duration_since(self.clock.now()))
                            .unwrap_or(Duration::ZERO);
                        receive
                            .recv_timeout(left.max(Duration::from_millis(10)))
                            .ok()
                    }
                    None => receive.recv().ok(),
                };
                finished.extend(first);
                finished.extend(receive.try_iter());
                for (key, done) in finished {
                    self.finish(key, done, &mut entries, &mut readers, &mut before, &folder);
                }
                self.hand_out(&entries);
            }
        })
    }

    /// Keeps the record of the run as it stands while it goes on, waiting for the person to say whether each work
    /// that cannot be undone and is out was done, should the run stop before it ends.
    fn keep_meanwhile(&mut self, steps: &[StepRecord], entries: &[Entry]) {
        let Some(draft) = self.draft.clone() else {
            return;
        };
        let waiting = Outcome::Waiting(self.out.clone());
        let record = self.as_it_stands(draft, waiting, steps.to_vec(), entries.to_vec());
        if let Err(error) = record.keep(&self.folder) {
            self.person.tell(&format!(
                "The record of this run could not be kept: {error}"
            ));
        }
    }

    /// Hands the keeper each entry it was not handed yet, or that changed since. Whether there was any.
    fn hand_out(&mut self, entries: &[Entry]) -> bool {
        let mut any = false;
        for entry in entries {
            if self.handed.get(&entry.key) == Some(entry) {
                continue;
            }
            any = true;
            if let Some(keeper) = self.keeper.as_deref_mut() {
                keeper.kept(entry);
            }
            self.handed.insert(entry.key.clone(), entry.clone());
        }
        any
    }

    /// The record of the run as it stands now, from its record as it started.
    fn as_it_stands(
        &self,
        mut record: Record,
        outcome: Outcome,
        steps: Vec<StepRecord>,
        journal: Vec<Entry>,
    ) -> Record {
        record.ended = self.clock.now();
        record.outcome = outcome;
        record.cost = self.cost;
        record.cost_unmeasured = self.unmeasured;
        record.steps = steps;
        record.decisions.clone_from(&self.decisions);
        record.journal = journal;
        record
    }

    /// Keeps what an agent or a command gave when it ended: its answer for the journal, the error of an agent, or
    /// why the run stops. An agent that may only read and changed the folder stops the run, whatever it gave.
    fn finish(
        &mut self,
        key: String,
        done: Finished,
        entries: &mut Vec<Entry>,
        readers: &mut HashMap<String, String>,
        before: &mut Option<u64>,
        folder: &Path,
    ) {
        self.working.remove(&key);
        match done {
            Finished::Agent(Err(error)) => entries.push(Entry {
                key: key.clone(),
                at: self.clock.now(),
                by: None,
                value: serde_json::to_value(AgentError { error }).unwrap_or_default(),
            }),
            done => match done.value() {
                Ok(value) => entries.push(Entry {
                    key: key.clone(),
                    at: self.clock.now(),
                    by: None,
                    value,
                }),
                Err(why) => {
                    self.failures.insert(key.clone(), why);
                }
            },
        }
        if let Some(guard) = readers.remove(&key) {
            if readers.is_empty() && before.take() != Some(folder::digest(folder)) {
                self.failures.insert(key, guard);
            }
        }
    }

    /// Now: the computer's clock, or while the run goes over what it was given before, the time of the last of it.
    fn now(&self) -> Timestamp {
        if self.journal.live {
            self.clock.now()
        } else {
            self.journal.time
        }
    }

    /// Tells the person, when the run does something new: what leads only to what the run was given before, the
    /// person heard then.
    fn tell(&mut self, text: &str) {
        self.held.push(text.to_owned());
    }

    /// Tells the person what is held.
    fn told(&mut self) {
        for text in std::mem::take(&mut self.held) {
            self.person.tell(&text);
        }
    }

    /// The run does something new: from here on it asks and reads the clock for itself, and what it would have
    /// told since the last thing it was given before is told now.
    fn go_live(&mut self) {
        self.journal.live = true;
        self.told();
    }

    /// What the run was given before under `key`, and who gave it. What led to it was told then.
    fn recall<T: DeserializeOwned>(&mut self, key: &str) -> Option<(T, Option<String>)> {
        let found = self.journal.recall(key)?;
        self.held.clear();
        Some(found)
    }

    fn keep<T: Serialize>(&mut self, key: String, value: &T) {
        let now = self.clock.now();
        self.journal.keep(key, value, now);
    }

    /// The time kept under `key`, or now, kept.
    fn moment(&mut self, key: String) -> Timestamp {
        if let Some((at, _)) = self.recall(&key) {
            return at;
        }
        self.go_live();
        let now = self.clock.now();
        self.keep(key, &now);
        now
    }

    /// The person's reply under `key`, and who gave it: given before, or asked now. When no one answers now, or
    /// the run asks no one, the step waits for it.
    fn reply(
        &mut self,
        key: String,
        step: &str,
        wait: Wait,
    ) -> Result<(Reply, Option<String>), Halt> {
        if let Some(found) = self.recall::<Reply>(&key) {
            return Ok(found);
        }
        if !self.detach {
            self.go_live();
            let reply = match &wait {
                Wait::Answer(ask) => self.person.answer(ask).map(Reply::Text),
                Wait::Approval(ask) => self.person.approve(ask).map(|verdict| match verdict {
                    Verdict::Yes => Reply::Yes,
                    Verdict::No { points, back } => Reply::No { points, back },
                }),
                Wait::Decision(question) => self.person.decide(question).map(|yes| {
                    if yes {
                        Reply::Yes
                    } else {
                        Reply::No {
                            points: String::new(),
                            back: Vec::new(),
                        }
                    }
                }),
                Wait::Choice { question, options } => {
                    self.person.choose(question, options).map(Reply::Option)
                }
                Wait::Time(_) => None,
            };
            if let Some(reply) = reply {
                self.keep(key, &reply);
                return Ok((reply, None));
            }
        }
        self.waiting.push(Waiting {
            step: step.to_owned(),
            key,
            wait,
        });
        Err(Halt::Pause)
    }

    /// A text the person gives under `key`.
    fn text(
        &mut self,
        key: String,
        step: &str,
        ask: Ask,
    ) -> Result<(String, Option<String>), Halt> {
        let (reply, by) = self.reply(key, step, Wait::Answer(ask))?;
        Ok((
            match reply {
                Reply::Text(text) => text,
                _ => String::new(),
            },
            by,
        ))
    }

    /// Runs the steps of a plan, each when the steps it waits for are done and its time has come. The answer of
    /// the last step when they are all done.
    fn steps(
        &mut self,
        plan: &Plan,
        asked: &str,
        records: &mut Vec<StepRecord>,
        base: &str,
    ) -> Result<String, Halt> {
        let started = self.moment(format!("{base}@start"));
        let graph = Graph::of(plan);
        let mut progress = vec![Progress::default(); plan.steps.len()];
        records.extend(plan.steps.iter().map(|step| StepRecord::new(&step.id)));
        let ended = self.order(plan, asked, &graph, &mut progress, records, base, started);
        for (record, step) in records.iter_mut().zip(&progress) {
            record.ended = step.state.ended();
        }
        ended?;
        Ok(progress
            .last()
            .map(|last| last.answer.clone())
            .unwrap_or_default())
    }

    #[allow(clippy::too_many_arguments)]
    fn order(
        &mut self,
        plan: &Plan,
        asked: &str,
        graph: &Graph<'_>,
        progress: &mut [Progress],
        records: &mut [StepRecord],
        base: &str,
        started: Timestamp,
    ) -> Result<(), Halt> {
        loop {
            self.within_limits()?;
            match self.look(plan, graph, progress, records, started) {
                Look::Start(number) => {
                    self.start(plan, asked, graph, progress, records, base, number)?;
                }
                Look::Again => {}
                Look::Wait(at, number) => self.wait(&plan.steps[number], base, at)?,
                Look::Done => return Ok(()),
                Look::Stuck if progress.iter().any(|step| step.state == State::Parked) => {
                    return Err(Halt::Pause);
                }
                Look::Stuck => return Err("no step can start".to_owned().into()),
            }
        }
    }

    /// Starts a step and keeps how it ended. A step that waits for an answer is parked, and the run goes on with
    /// the steps that do not wait for it.
    #[allow(clippy::too_many_arguments)]
    fn start(
        &mut self,
        plan: &Plan,
        asked: &str,
        graph: &Graph<'_>,
        progress: &mut [Progress],
        records: &mut [StepRecord],
        base: &str,
        number: usize,
    ) -> Result<(), Halt> {
        let id = &plan.steps[number].id;
        let skipped: HashSet<String> = progress
            .iter()
            .zip(&plan.steps)
            .filter(|(step, _)| step.state == State::Skipped)
            .map(|(_, step)| step.id.clone())
            .collect();
        let mut values = Values::from([("asked".to_owned(), asked.to_owned())]);
        for &wait in &graph.all_waits[number] {
            values.insert(plan.steps[wait].id.clone(), progress[wait].answer.clone());
        }
        let round = progress[number].rounds;
        progress[number].rounds += 1;
        let started = self.moment(format!("{base}{id}@start{round}"));
        let place = Place {
            base,
            round,
            started,
        };
        let ended = match self.step(
            plan,
            number,
            &values,
            &skipped,
            &mut progress[number],
            &mut records[number],
            &place,
        ) {
            Ok(ended) => ended,
            Err(Halt::Pause) => {
                progress[number].state = State::Parked;
                return Ok(());
            }
            Err(halt) => return Err(halt),
        };
        let now = self.moment(format!("{base}{id}@done{round}"));
        if let Some(told) = settle(graph, progress, &mut records[number], number, ended, now) {
            self.tell(&told);
        }
        Ok(())
    }

    /// Waits for a step's time: the step waits, and the run waits for the soonest time once nothing else can go
    /// on. A run going over what it was given before does not wait for a time that has passed.
    fn wait(&mut self, step: &Step, base: &str, at: Timestamp) -> Result<(), Halt> {
        if !self.journal.live && at <= self.clock.now() {
            self.journal.time = self.journal.time.max(at);
            return Ok(());
        }
        if self
            .soonest
            .as_ref()
            .is_none_or(|(soonest, _)| at < *soonest)
        {
            self.soonest = Some((at, step.id.clone()));
        }
        self.waiting.push(Waiting {
            step: step.id.clone(),
            key: format!("{base}{}@time", step.id),
            wait: Wait::Time(at),
        });
        Err(Halt::Pause)
    }

    /// Finds the first step that may start, skipping the steps whose path was not taken on the way.
    fn look(
        &mut self,
        plan: &Plan,
        graph: &Graph,
        progress: &mut [Progress],
        records: &mut [StepRecord],
        started: Timestamp,
    ) -> Look {
        let now = self.now();
        let mut soonest: Option<(Timestamp, usize)> = None;
        let mut changed = false;
        for (number, step) in plan.steps.iter().enumerate() {
            if progress[number].state != State::Open
                || graph.waits[number]
                    .iter()
                    .any(|&wait| !progress[wait].state.ended())
            {
                continue;
            }
            if let Some((on, answer)) = step.when.as_ref().and_then(|when| when.iter().next()) {
                let chose = &progress[graph.index[on.as_str()]];
                if chose.state == State::Skipped || chose.answer != *answer {
                    progress[number] = Progress {
                        state: State::Skipped,
                        done: Some(now),
                        ..Progress::default()
                    };
                    records[number].skipped = true;
                    self.tell(&format!(
                        "Step {} · {}: skipped, since {on} did not answer {answer}.",
                        number + 1,
                        step.id
                    ));
                    changed = true;
                    continue;
                }
            }
            if let Some(at) = not_before(step, &graph.waits[number], progress, started) {
                if at > now {
                    if soonest.is_none_or(|(soonest, _)| at < soonest) {
                        soonest = Some((at, number));
                    }
                    continue;
                }
            }
            return Look::Start(number);
        }
        if changed {
            Look::Again
        } else if progress.iter().all(|step| step.state.ended()) {
            Look::Done
        } else if let Some((at, number)) = soonest {
            Look::Wait(at, number)
        } else {
            Look::Stuck
        }
    }

    fn within_limits(&self) -> Result<(), Halt> {
        // The run's time is over when it is over now, even while the run goes over what it was given before.
        if self.end.is_some_and(|end| self.clock.now() >= end) {
            return Err(Self::time_over().into());
        }
        match self.cost_limit {
            Some(limit) if self.cost >= limit => Err(format!(
                "the run has cost {}, which reaches its limit of {limit}",
                self.cost
            )
            .into()),
            _ => Ok(()),
        }
    }

    fn time_over() -> String {
        "the run reached its deadline, or the runner's own time limit".to_owned()
    }

    /// When the run's time is over, on the computer's own clock, for commands and agents to stop by.
    fn instant(&self) -> Option<Instant> {
        let left = self.end?.duration_since(self.clock.now());
        Some(Instant::now() + Duration::try_from(left).unwrap_or(Duration::ZERO))
    }

    /// Does one step, for each of its items when it has them.
    #[allow(clippy::too_many_arguments)]
    fn step(
        &mut self,
        plan: &Plan,
        number: usize,
        values: &Values,
        skipped: &HashSet<String>,
        progress: &mut Progress,
        record: &mut StepRecord,
        place: &Place<'_>,
    ) -> Result<Ended, Halt> {
        let step = &plan.steps[number];
        let header = |values: &Values| {
            let item = values
                .get("item")
                .map(|item| format!(" ({item})"))
                .unwrap_or_default();
            format!(
                "Step {} · {}{item}: {}",
                number + 1,
                step.id,
                fill(&step.what, values)
            )
        };
        let scope = format!("{}{}/", place.base, step.id);
        let Some(list) = &step.for_each else {
            let header = header(values);
            // A person's step is its own question, and so is work that cannot be undone, so it is not told twice.
            if step.by != By::Person && !step.irreversible() {
                self.tell(&header);
            }
            let again = progress.again.take();
            return self.work_until_proven(
                plan,
                step,
                &header,
                values,
                skipped,
                again,
                &mut progress.refused,
                place.started,
                &scope,
                &mut record.attempts,
            );
        };

        let items = items(values.get(list).map_or("", String::as_str));
        if items.len() > MANY_ITEMS {
            let asked = format!(
                "The step {} is done for each of {} items. Go on?",
                step.id,
                items.len()
            );
            let key = format!("{}{}@many{}", place.base, step.id, place.round);
            if !self.decide(key, &step.id, asked)? {
                return Err(format!(
                    "the person did not go on with the {} items of the step {}",
                    items.len(),
                    step.id
                )
                .into());
            }
        }
        // Work sent back to this step goes to every item, with the points against it.
        let again = progress.again.take().map(|(_, points)| points);
        let mut answers = Vec::new();
        let mut paused = false;
        for (at, item) in items.into_iter().enumerate() {
            let mut values = values.clone();
            values.insert("item".to_owned(), item.clone());
            let header = header(&values);
            if step.by != By::Person && !step.irreversible() {
                self.tell(&header);
            }
            // An item done again keeps its earlier attempts.
            if record.items.get(at).is_none_or(|kept| kept.item != item) {
                record.items.truncate(at);
                record.items.push(ItemRecord {
                    item,
                    answer: None,
                    attempts: Vec::new(),
                });
            }
            let done = &mut record.items[at];
            let sent_back = again
                .clone()
                .map(|points| (done.answer.take().unwrap_or_default(), points));
            let mut refused = 0;
            let ended = self.work_until_proven(
                plan,
                step,
                &header,
                &values,
                skipped,
                sent_back,
                &mut refused,
                place.started,
                &format!("{scope}{}#{at}/", place.round),
                &mut done.attempts,
            );
            match ended {
                Ok(Ended::Passed(answer)) => {
                    done.answer = Some(answer.clone());
                    answers.push(serde_json::Value::String(answer));
                }
                Ok(Ended::LeftOut | Ended::Back { .. }) => return Ok(Ended::LeftOut),
                // Items one by one wait for the one before; the others go on while one waits.
                Err(Halt::Pause) if step.one_by_one() => return Err(Halt::Pause),
                Err(Halt::Pause) => paused = true,
                Err(halt) => return Err(halt),
            }
        }
        if paused {
            return Err(Halt::Pause);
        }
        Ok(Ended::Passed(serde_json::Value::Array(answers).to_string()))
    }

    /// Does a step's work, or an item's, until its proofs pass, the person goes on without it, or a proof sends
    /// the work back to earlier steps.
    #[allow(clippy::too_many_arguments)]
    fn work_until_proven(
        &mut self,
        plan: &Plan,
        step: &Step,
        header: &str,
        values: &Values,
        skipped: &HashSet<String>,
        mut last: Option<(String, String)>,
        refused: &mut u32,
        started: Timestamp,
        scope: &str,
        attempts: &mut Vec<Attempt>,
    ) -> Result<Ended, Halt> {
        let mut fixing: Option<String> = None;
        let mut deadline = step
            .deadline
            .as_deref()
            .and_then(Moment::read)
            .map(|deadline| deadline.from(started));
        loop {
            self.within_limits()?;
            let at = format!("{scope}{}/", attempts.len());
            if let Some(end) = deadline.filter(|end| self.now() >= *end) {
                match self.late(step, end, &at)? {
                    Some(later) => deadline = Some(later),
                    None => return Ok(Ended::LeftOut),
                }
            }
            let mut attempt = Attempt::by(by_name(step.by));
            let out = self.undone(plan, step, header, values, skipped, &at)?;
            if let Out::Back(to, points) = out {
                attempt.back.clone_from(&to);
                attempts.push(attempt);
                return Ok(Ended::Back { to, points });
            }
            let worker = self.worker(step, values, &at)?;
            attempt.conversation = self.begin_work(step, &at, &out, attempts);
            let work = match out {
                Out::Done(answer) => Ok(answer),
                Out::NotDone => Err(Halt::Failed(NOT_DONE.to_owned())),
                Out::Fresh | Out::Back(..) => self.work(
                    plan,
                    step,
                    header,
                    values,
                    worker.as_deref(),
                    last.as_ref(),
                    fixing.as_deref(),
                    &at,
                    &mut attempt,
                ),
            };
            if work.is_ok() && step.by != By::Plan {
                attempt.changed = self.changed(&at);
            }
            let judged = work.and_then(|answer| {
                let answer = match &step.choices {
                    Some(choices) => chosen(&answer, choices),
                    None => answer,
                };
                let points = self.judge(
                    plan,
                    step,
                    values,
                    skipped,
                    &answer,
                    worker.as_deref(),
                    &at,
                    &mut attempt,
                )?;
                Ok((answer, points))
            });
            let (answer, points) = match judged {
                Ok(judged) => judged,
                // The agent's error is the point against this work alone, and the rest of the run goes on.
                Err(Halt::Failed(points)) => {
                    (String::new(), Some(attempt.failed.insert(points).clone()))
                }
                Err(reason) => {
                    attempts.push(attempt);
                    return Err(reason);
                }
            };
            self.before.remove(&at);
            let back = attempt.back.clone();
            attempts.push(attempt);
            let Some(points) = points else {
                return Ok(Ended::Passed(answer));
            };

            self.tell(&format!("Refused: {points}"));
            *refused += 1;
            if *refused >= self.repeats {
                let asked = format!(
                    "The step {} was refused {} times. The last points against it: {points}\nGo on?",
                    step.id, *refused
                );
                if !self.decide(format!("{at}repeat"), &step.id, asked)? {
                    return Err(format!(
                        "the person did not go on after the step {} was refused {} times",
                        step.id, *refused
                    )
                    .into());
                }
                *refused = 0;
            }
            if !back.is_empty() {
                return Ok(Ended::Back { to: back, points });
            }
            if step.by == By::Algorithm && step.on_fail == Some(OnFail::Agent) {
                fixing = Some(points.clone());
            }
            last = Some((answer, points));
        }
    }

    /// The points against an attempt's answer, or `None` when it stands: the command of an algorithm, the
    /// choices, then each proof in order until one refuses. A refusal that names earlier steps keeps them in the
    /// attempt.
    #[allow(clippy::too_many_arguments)]
    fn judge(
        &mut self,
        plan: &Plan,
        step: &Step,
        values: &Values,
        skipped: &HashSet<String>,
        answer: &str,
        worker: Option<&str>,
        at: &str,
        attempt: &mut Attempt,
    ) -> Result<Option<String>, Halt> {
        if let Some(points) = attempt
            .proofs
            .iter()
            .find(|proof| !proof.passed)
            .and_then(|proof| proof.points.clone())
        {
            return Ok(Some(points));
        }
        if let Some(choices) = step
            .choices
            .as_ref()
            .filter(|choices| !choices.iter().any(|choice| choice == answer))
        {
            let listed = choices.join(", ");
            let against = format!("The answer must be exactly one of: {listed}. It was: {answer}");
            attempt.proofs.push(ProofRecord {
                by: "algorithm".to_owned(),
                asked: format!("The answer is one of: {listed}"),
                passed: false,
                points: Some(against.clone()),
                skipped: false,
                reason: None,
            });
            return Ok(Some(against));
        }
        let mut own = values.clone();
        own.insert(step.id.clone(), answer.to_owned());
        let mut passed: Vec<String> = attempt
            .proofs
            .iter()
            .map(|proof| format!("The command `{}` ended with 0.", proof.asked))
            .collect();
        for (count, proof) in step.proofs().iter().enumerate() {
            let other_path = proof.when.as_ref().is_some_and(|when| {
                when.iter()
                    .any(|(id, answer)| own.get(id).is_none_or(|given| given != answer))
            });
            if other_path {
                attempt.proofs.push(ProofRecord {
                    by: prover_name(proof.by).to_owned(),
                    asked: proof_asked(proof, &own),
                    passed: false,
                    points: None,
                    skipped: true,
                    reason: proof
                        .when
                        .as_ref()
                        .map(|when| path_words(when, &own, skipped)),
                });
                continue;
            }
            let offered: Vec<String> = proof
                .back_to
                .iter()
                .flatten()
                .filter(|id| !skipped.contains(*id))
                .cloned()
                .collect();
            let key = format!(
                "{at}proof{count}:{}",
                stamp(&serde_json::to_string(proof).unwrap_or_default())
            );
            let asked = Asked {
                proof,
                values: &own,
                answer,
                worker,
                offered: &offered,
                key,
                at,
                passed: &passed,
            };
            let (proved, back) = self.prove(plan, step, &asked)?;
            let against = (!proved.passed).then(|| proved.points.clone().unwrap_or_default());
            if proved.passed {
                passed.push(passed_words(proof, &proved.asked));
            }
            attempt.proofs.push(proved);
            if against.is_some() {
                attempt.back = back;
                return Ok(against);
            }
        }
        Ok(None)
    }

    /// For work that cannot be undone: the person's yes first, then whether it was done when the run stopped while
    /// it was out.
    fn undone(
        &mut self,
        plan: &Plan,
        step: &Step,
        header: &str,
        values: &Values,
        skipped: &HashSet<String>,
        at: &str,
    ) -> Result<Out, Halt> {
        if !step.irreversible() {
            return Ok(Out::Fresh);
        }
        if let Some((to, points)) = self.approve_undone(plan, step, header, values, skipped, at)? {
            return Ok(Out::Back(to, points));
        }
        self.out_before(step, header, values, at)
    }

    /// Asks the person who asked whether to start work that cannot be undone, telling them what it does with its
    /// references filled. A no stops the run, unless it sends the work back to earlier steps: then those steps, with
    /// the points against the work.
    fn approve_undone(
        &mut self,
        plan: &Plan,
        step: &Step,
        header: &str,
        values: &Values,
        skipped: &HashSet<String>,
        at: &str,
    ) -> Result<Option<(Vec<String>, String)>, Halt> {
        let mut question = header.to_owned();
        match step.by {
            By::Algorithm => {
                let line = fill(step.run.as_deref().unwrap_or_default(), values);
                let _ = write!(question, "\nIt runs `{line}`.");
            }
            By::Plan => {
                let _ = write!(
                    question,
                    "\nIt runs the plan `{}`.",
                    step.plan.as_deref().unwrap_or_default()
                );
            }
            By::Agent | By::Person => {}
        }
        question.push_str("\nIt cannot be undone. Start it?");
        let offered = if step.for_each.is_some() {
            Vec::new()
        } else {
            let graph = Graph::of(plan);
            let waits = &graph.all_waits[graph.index[step.id.as_str()]];
            plan.steps
                .iter()
                .enumerate()
                .filter(|(number, earlier)| {
                    waits.contains(number)
                        && !earlier.irreversible()
                        && !skipped.contains(&earlier.id)
                })
                .map(|(_, earlier)| earlier.id.clone())
                .collect()
        };
        let ask = Ask {
            question: question.clone(),
            people: Vec::new(),
            choices: Vec::new(),
            back_to: offered.clone(),
        };
        let (reply, by) = self.reply(format!("{at}start"), &step.id, Wait::Approval(ask))?;
        let refused = match reply {
            Reply::No { points, back } => Some((points, back)),
            _ => None,
        };
        self.decisions.push(Decision {
            step: step.id.clone(),
            asked: question,
            answer: if refused.is_some() { "no" } else { "yes" }.to_owned(),
            by,
        });
        let Some((points, back)) = refused else {
            return Ok(None);
        };
        let back: Vec<String> = back.into_iter().filter(|id| offered.contains(id)).collect();
        if back.is_empty() {
            let why = if points.trim().is_empty() {
                String::new()
            } else {
                format!(": {}", points.trim())
            };
            return Err(format!(
                "the person did not start the step {}, which cannot be undone{why}",
                step.id
            )
            .into());
        }
        let points = if points.trim().is_empty() {
            "The person said no.".to_owned()
        } else {
            points
        };
        self.tell(&format!("Refused: {points}"));
        Ok(Some((back, points)))
    }

    /// Where work that cannot be undone stands as an attempt begins. Work by an agent or a command that began
    /// before the run stopped, with no end kept, is not done again on its own: a command still running is waited
    /// for, and one that ended is taken as it ended; otherwise the person says whether it was done, and what it
    /// answered. Work that is out is listed, so that the record kept meanwhile asks the same.
    fn out_before(
        &mut self,
        step: &Step,
        header: &str,
        values: &Values,
        at: &str,
    ) -> Result<Out, Halt> {
        let end = match step.by {
            By::Agent => "work",
            By::Algorithm => "run",
            By::Person | By::Plan => return Ok(Out::Fresh),
        };
        let (begun, end) = (format!("{at}begun"), format!("{at}{end}"));
        if self.journal.knows(&end) {
            return Ok(Out::Fresh);
        }
        let key = format!("{at}done");
        let question = format!(
            "{header}\nThis work cannot be undone. It began before the run stopped, and how it ended was not kept: \
             was it done? Yes goes on to its proofs; no does it again."
        );
        if self.journal.knows(&begun) && !self.asked.contains(&end) {
            if let Some(dir) = self.out_dir(at).filter(|_| step.by == By::Algorithm) {
                if let Some(pid) = still_running(&dir) {
                    self.tell(&format!(
                        "{header}\nIts work, which cannot be undone, is still running from before the run stopped \
                         (process {pid}): the run waits for it to end."
                    ));
                    self.go_live();
                    while still_running(&dir).is_some() {
                        thread::sleep(Duration::from_millis(200));
                    }
                }
                if let Some(ended) = command::kept(&dir) {
                    self.go_live();
                    self.keep(end, &ended);
                    return Ok(Out::Fresh);
                }
            }
            // Its commands that prove it, when they need not its answer, may tell that it was done.
            match self.proven_done(step, values, at)? {
                Ok(()) => {}
                Err(found) => {
                    let question = match found {
                        Some(points) => format!(
                            "{question}\nIts proof by a command found: {}",
                            points.trim()
                        ),
                        None => question,
                    };
                    if !self.decide(key, &step.id, question)? {
                        return Ok(Out::NotDone);
                    }
                }
            }
            let ask = Ask {
                question: format!(
                    "{header}\nWhat did it answer? Leave it empty when it does not matter."
                ),
                ..Ask::default()
            };
            let (answer, _) = self.text(format!("{at}said"), &step.id, ask)?;
            return Ok(Out::Done(answer.trim().to_owned()));
        }
        if !self.journal.knows(&begun) {
            self.go_live();
            self.keep(begun, &true);
        }
        self.out.push(Waiting {
            step: step.id.clone(),
            key,
            wait: Wait::Decision(question),
        });
        Ok(Out::Fresh)
    }

    /// Whether the proofs of a step by commands and needs, those that do not name its own answer and are for every
    /// path, all pass now: then its work, whose end was lost, was done. Otherwise what the first that refused found,
    /// or nothing when it has none.
    fn proven_done(
        &mut self,
        step: &Step,
        values: &Values,
        at: &str,
    ) -> Result<Result<(), Option<String>>, Halt> {
        let mut marked = values.clone();
        marked.insert(step.id.clone(), "\0".to_owned());
        let proofs: Vec<&Proof> = step
            .proofs()
            .iter()
            .filter(|proof| proof.by == Prover::Algorithm && proof.when.is_none())
            .filter(|proof| {
                !fill(&serde_json::to_string(proof).unwrap_or_default(), &marked).contains('\0')
            })
            .collect();
        if proofs.is_empty() {
            return Ok(Err(None));
        }
        for (count, proof) in proofs.into_iter().enumerate() {
            let key = format!("{at}check{count}");
            let points = match &proof.run {
                Some(run) => {
                    let line = fill(run, values);
                    let ended = self.command(key, &line)?;
                    (!ended.passed).then(|| ended.points(&line))
                }
                None => self.needs(key, proof, values).1,
            };
            if points.is_some() {
                return Ok(Err(points));
            }
        }
        self.tell("Its proofs by commands pass now, so it was done.");
        Ok(Ok(()))
    }

    /// Where the command of work that cannot be undone at `at` writes its process, its output and how it ended, so
    /// that a run that stopped meanwhile finds them: only for a run whose record is kept.
    fn out_dir(&self, at: &str) -> Option<PathBuf> {
        let draft = self.draft.as_ref()?;
        Some(
            runs(&self.folder)
                .join(format!("{}.out", draft.id))
                .join(stamp(at)),
        )
    }

    /// The agent that does an attempt of a step by an agent.
    fn worker(&mut self, step: &Step, values: &Values, at: &str) -> Result<Option<String>, Halt> {
        if step.by != By::Agent {
            return Ok(None);
        }
        let key = format!("{at}agent");
        self.agent_named(step, step.agent.as_deref(), values, None, key)
    }

    /// Keeps the folder as it is before an attempt's work begins, to tell its proofs what changed. The conversation
    /// the step's last refused work went on in, which its agent is told and may go on in.
    fn begin_work(
        &mut self,
        step: &Step,
        at: &str,
        out: &Out,
        attempts: &[Attempt],
    ) -> Option<String> {
        if step.by != By::Plan && !self.before.contains_key(at) && !self.work_begun(at) {
            self.before
                .insert(at.to_owned(), folder::snapshot(&self.folder));
        }
        let fresh = step.by == By::Agent && matches!(out, Out::Fresh);
        fresh.then(|| last_conversation(attempts)).flatten()
    }

    /// The files the work of an attempt changed, kept when its work ended, or recalled. Nothing when the run did
    /// not see its work begin.
    fn changed(&mut self, at: &str) -> Vec<String> {
        let key = format!("{at}changed");
        if let Some((paths, _)) = self.recall(&key) {
            return paths;
        }
        let Some(before) = self.before.get(at) else {
            return Vec::new();
        };
        let paths = folder::changed(before, &folder::snapshot(&self.folder));
        self.go_live();
        self.keep(key, &paths);
        paths
    }

    /// Whether the work of an attempt began: an agent, a command or a person was asked for it.
    fn work_begun(&self, at: &str) -> bool {
        ["work", "fix", "run", "answer"]
            .iter()
            .any(|end| self.journal.knows(&format!("{at}{end}")))
    }

    /// Asks the person a yes or no question about a step, and keeps what they decided.
    fn decide(&mut self, key: String, step: &str, asked: String) -> Result<bool, Halt> {
        let (reply, by) = self.reply(key, step, Wait::Decision(asked.clone()))?;
        let yes = reply == Reply::Yes;
        self.decisions.push(Decision {
            step: step.to_owned(),
            asked,
            answer: if yes { "yes" } else { "no" }.to_owned(),
            by,
        });
        Ok(yes)
    }

    /// Asks the person what to do with a step past its deadline: a later deadline, `None` to go on without it, or
    /// a stop.
    fn late(&mut self, step: &Step, end: Timestamp, at: &str) -> Result<Option<Timestamp>, Halt> {
        let asked = format!(
            "The step {} reached its deadline, {}, before it passed. What now?",
            step.id,
            words(end)
        );
        let options: Vec<String> = LATE.map(str::to_owned).to_vec();
        let mut count = 0;
        loop {
            let wait = Wait::Choice {
                question: asked.clone(),
                options: options.clone(),
            };
            let (reply, by) = self.reply(format!("{at}late{count}"), &step.id, wait)?;
            let chosen = match reply {
                Reply::Option(chosen) => Some(chosen),
                _ => None,
            };
            self.decisions.push(Decision {
                step: step.id.clone(),
                asked: asked.clone(),
                answer: chosen
                    .and_then(|chosen| LATE.get(chosen))
                    .map_or("none", |chosen| *chosen)
                    .to_owned(),
                by,
            });
            match chosen {
                Some(0) => {
                    let until = Ask {
                        question: "Until when? A date such as 2027-03-10T18:00-03:00, or a wait such as P2D."
                            .to_owned(),
                        ..Ask::default()
                    };
                    let (text, _) = self.text(format!("{at}late{count}/until"), &step.id, until)?;
                    let now = self.now();
                    let later = Moment::read(&text)
                        .map(|later| later.from(now))
                        .filter(|later| *later > now);
                    if let Some(later) = later {
                        return Ok(Some(later));
                    }
                    self.tell("That is not a later time.");
                }
                Some(1) => return Ok(None),
                _ => {
                    return Err(format!(
                        "the step {} reached its deadline and the person stopped the run",
                        step.id
                    )
                    .into());
                }
            }
            count += 1;
        }
    }

    /// The agent a step or proof names, filled. When a reference gives nothing, or the agent would judge its own
    /// work, the person is asked whom to give it to.
    fn agent_named(
        &mut self,
        step: &Step,
        named: Option<&str>,
        values: &Values,
        worker: Option<&str>,
        key: String,
    ) -> Result<Option<String>, Halt> {
        let Some(named) = named else {
            return Ok(None);
        };
        let filled = fill(named, values).trim().to_owned();
        let question = if filled.is_empty() {
            format!(
                "The step {} names its agent by “{named}”, which gives nothing. Which agent should it go to? \
                 Leave it empty to stop.",
                step.id
            )
        } else if worker.is_some_and(|worker| worker == filled) {
            format!(
                "The agent {filled} would judge its own work in the step {}. Which agent should judge it? \
                 Leave it empty to stop.",
                step.id
            )
        } else {
            return Ok(Some(filled));
        };
        let ask = Ask {
            question: question.clone(),
            ..Ask::default()
        };
        let (answer, by) = self.text(key, &step.id, ask)?;
        let answer = answer.trim().to_owned();
        self.decisions.push(Decision {
            step: step.id.clone(),
            asked: question,
            answer: if answer.is_empty() {
                "none".to_owned()
            } else {
                answer.clone()
            },
            by,
        });
        if answer.is_empty() || worker.is_some_and(|worker| worker == answer) {
            return Err(format!("the person named no agent for the step {}", step.id).into());
        }
        Ok(Some(answer))
    }

    /// The people a step or proof names, filled. When a reference gives nothing, the person is asked.
    fn people(
        &mut self,
        step: &Step,
        ids: Option<&vpf::Ids>,
        values: &Values,
        key: &str,
    ) -> Result<Vec<String>, Halt> {
        let mut people = Vec::new();
        for (count, id) in ids
            .map(vpf::Ids::list)
            .unwrap_or_default()
            .iter()
            .enumerate()
        {
            let filled = fill(id, values).trim().to_owned();
            if !filled.is_empty() {
                people.push(filled);
                continue;
            }
            let question = format!(
                "The step {} names a person by “{id}”, which gives nothing. Whom should it go to? Leave it empty \
                 to stop.",
                step.id
            );
            let ask = Ask {
                question: question.clone(),
                ..Ask::default()
            };
            let (answer, by) = self.text(format!("{key}person{count}"), &step.id, ask)?;
            let answer = answer.trim().to_owned();
            self.decisions.push(Decision {
                step: step.id.clone(),
                asked: question,
                answer: if answer.is_empty() {
                    "none".to_owned()
                } else {
                    answer.clone()
                },
                by,
            });
            if answer.is_empty() {
                return Err(format!("the person named no one for the step {}", step.id).into());
            }
            people.push(answer);
        }
        Ok(people)
    }

    /// Does the work of one attempt. For an algorithm, the command is recorded as the attempt's first proof.
    #[allow(clippy::too_many_arguments)]
    fn work(
        &mut self,
        plan: &Plan,
        step: &Step,
        header: &str,
        values: &Values,
        worker: Option<&str>,
        last: Option<&(String, String)>,
        fixing: Option<&str>,
        at: &str,
        attempt: &mut Attempt,
    ) -> Result<String, Halt> {
        match step.by {
            By::Agent => {
                let prompt = work_prompt(plan, step, values, last);
                let tools: Vec<&'static str> = match &step.tools {
                    Some(tools) => tools.iter().copied().map(tool_name).collect(),
                    None => ALL_TOOLS.to_vec(),
                };
                let may_write = tools.contains(&"write");
                let request = Request {
                    role: Role::Work,
                    step: step.id.clone(),
                    conversation: attempt.conversation.take(),
                    prompt,
                    agent: worker.map(str::to_owned),
                    model: step.model.clone(),
                    tools,
                    guard: (!may_write).then(|| {
                        format!(
                            "the agent of the step {} changed the folder, but its step does not give it write",
                            step.id
                        )
                    }),
                };
                let answer = self.ask(format!("{at}work"), request)?;
                attempt.answer = Some(answer.text.clone());
                attempt.conversation = answer.conversation;
                Ok(answer.text)
            }
            By::Person => {
                let people = self.people(step, step.person.as_ref(), values, at)?;
                let mut question = header.to_owned();
                if let Some((answer, points)) = last {
                    let _ = write!(
                        question,
                        "\nYour last answer, “{answer}”, was refused: {points}"
                    );
                }
                let ask = Ask {
                    question,
                    people,
                    choices: step.choices.clone().unwrap_or_default(),
                    back_to: Vec::new(),
                };
                let (answer, _) = self.text(format!("{at}answer"), &step.id, ask)?;
                attempt.answer = Some(answer.clone());
                Ok(answer)
            }
            By::Plan => {
                let answer = self.other_plan(step, values, at, attempt)?;
                attempt.answer = Some(answer.clone());
                Ok(answer)
            }
            By::Algorithm => {
                let line = fill(step.run.as_deref().unwrap_or_default(), values);
                if let Some(points) = fixing {
                    "agent".clone_into(&mut attempt.by);
                    let request = Request {
                        role: Role::Fix,
                        step: step.id.clone(),
                        conversation: None,
                        prompt: fix_prompt(plan, step, &line, points),
                        agent: None,
                        model: None,
                        tools: ALL_TOOLS.to_vec(),
                        guard: None,
                    };
                    let fixed = self.ask(format!("{at}fix"), request)?;
                    attempt.answer = Some(fixed.text);
                }
                let keep = if step.irreversible() {
                    self.out_dir(at)
                } else {
                    None
                };
                let ended: command::Ended = self.answered(format!("{at}run"), || Job::Command {
                    line: line.clone(),
                    keep,
                })?;
                attempt.proofs.push(ProofRecord {
                    by: "algorithm".to_owned(),
                    points: (!ended.passed).then(|| ended.points(&line)),
                    asked: line,
                    passed: ended.passed,
                    skipped: false,
                    reason: None,
                });
                if fixing.is_none() {
                    attempt.answer = Some(ended.out.trim().to_owned());
                }
                Ok(ended.out.trim().to_owned())
            }
        }
    }

    /// Runs a command line in the folder, or recalls how it ended when the run was given that before.
    fn command(&mut self, key: String, line: &str) -> Result<command::Ended, Halt> {
        self.answered(key, || Job::Command {
            line: line.to_owned(),
            keep: None,
        })
    }

    /// What an agent or command answered under `key`, when it has. Otherwise it is started, or keeps working, and
    /// the step waits for it.
    fn answered<T: DeserializeOwned>(
        &mut self,
        key: String,
        job: impl FnOnce() -> Job,
    ) -> Result<T, Halt> {
        if let Some(why) = self.failures.get(&key) {
            return Err(Halt::Stop(why.clone()));
        }
        if let Some((AgentError { error }, _)) = self.recall(&key) {
            return Err(Halt::Failed(format!("{AGENT_ERROR}{error}")));
        }
        if let Some((answer, _)) = self.recall(&key) {
            return Ok(answer);
        }
        if self.asked.contains(&key) {
            // What led to it was told when it was first asked.
            self.held.clear();
            self.journal.live = true;
        } else {
            self.go_live();
            self.asked.insert(key.clone());
        }
        if !self.working.contains(&key) {
            self.jobs.push((key, job()));
        }
        Err(Halt::Pause)
    }

    /// Asks the agent, or recalls its answer when the run was given it before. With a guard, the agent may not
    /// change the folder, and the run stops with the guard if it does.
    fn ask(&mut self, key: String, request: Request) -> Result<AgentAnswer, Halt> {
        let answer: AgentAnswer = self.answered(key, || Job::Agent(request))?;
        if let Some(cost) = answer.cost {
            self.cost += cost;
        } else {
            self.unmeasured = true;
            if self.cost_limit.is_some() && !self.told_unmeasured {
                self.told_unmeasured = true;
                self.tell(
                    "The agent did not say what it cost, so this run's cost is not measured against its limit.",
                );
            }
        }
        Ok(answer)
    }

    /// Asks one proof of the work: what it found, and the earlier steps its refusal sends the work back to.
    fn prove(
        &mut self,
        plan: &Plan,
        step: &Step,
        asked: &Asked<'_>,
    ) -> Result<(ProofRecord, Vec<String>), Halt> {
        let Asked {
            proof,
            values,
            answer,
            offered,
            ref key,
            ..
        } = *asked;
        let by = prover_name(proof.by);
        let result = |asked: String, points: Option<String>| ProofRecord {
            by: by.to_owned(),
            asked,
            passed: points.is_none(),
            points,
            skipped: false,
            reason: None,
        };
        match proof.by {
            Prover::Algorithm => {
                if let Some(run) = &proof.run {
                    let line = fill(run, values);
                    let ended = self.command(key.clone(), &line)?;
                    if ended.passed {
                        return Ok((result(line, None), Vec::new()));
                    }
                    let (back, points) = named_first(&ended.points(&line), offered);
                    Ok((result(line, Some(points)), back))
                } else {
                    let (asked, points) = self.needs(key.clone(), proof, values);
                    Ok((result(asked, points), Vec::new()))
                }
            }
            Prover::Agent => {
                let (check, points, back) = self.prove_by_agent(plan, step, asked)?;
                Ok((result(check, points), back))
            }
            Prover::Person => {
                let people =
                    self.people(step, proof.person.as_ref(), values, &format!("{key}/"))?;
                let question = match &proof.ask {
                    Some(ask) if !ask.trim().is_empty() && answer.trim().is_empty() => {
                        fill(ask, values)
                    }
                    Some(ask) if !ask.trim().is_empty() => format!(
                        "{}\nThe answer of the step {}:\n{}\n",
                        fill(ask, values),
                        step.id,
                        answer.trim()
                    ),
                    _ => format!(
                        "Do you approve the step {}, “{}”? Its answer:\n{answer}\n",
                        step.id,
                        fill(&step.what, values)
                    ),
                };
                let ask = Ask {
                    question: question.clone(),
                    people,
                    choices: Vec::new(),
                    back_to: offered.to_vec(),
                };
                match self.reply(key.clone(), &step.id, Wait::Approval(ask))?.0 {
                    Reply::No { points, back } => {
                        let points = if points.trim().is_empty() {
                            "The person said no.".to_owned()
                        } else {
                            points
                        };
                        let back = back.into_iter().filter(|id| offered.contains(id)).collect();
                        Ok((result(question, Some(points)), back))
                    }
                    _ => Ok((result(question, None), Vec::new())),
                }
            }
        }
    }

    /// Asks another agent to prove the work: what it was asked to find true, its points against the work, and the
    /// earlier steps they send it back to.
    fn prove_by_agent(
        &mut self,
        plan: &Plan,
        step: &Step,
        asked: &Asked<'_>,
    ) -> Result<(String, Option<String>, Vec<String>), Halt> {
        let Asked {
            proof,
            values,
            answer,
            worker,
            offered,
            ref key,
            at,
            passed,
        } = *asked;
        let named = format!("{key}/agent");
        let judge = self.agent_named(step, proof.agent.as_deref(), values, worker, named)?;
        let check = fill(proof.check.as_deref().unwrap_or_default(), values);
        let changed = if self.journal.knows(key) {
            None
        } else {
            self.before.get(at).map(|before| {
                let now = folder::snapshot(&self.folder);
                let paths = folder::changed(before, &now);
                let lines = folder::changes(before, &now, &paths);
                (paths, lines)
            })
        };
        let witness = Witness {
            answer,
            passed,
            changed: changed.as_ref().map(|(paths, _)| paths.as_slice()),
            changes: changed.as_ref().map_or("", |(_, lines)| lines.as_str()),
        };
        let request = Request {
            role: Role::Judge,
            step: step.id.clone(),
            conversation: None,
            prompt: judge_prompt(plan, step, values, &witness, &check, offered),
            agent: judge,
            model: proof.model.clone(),
            tools: proof.tools.as_deref().map_or_else(
                || vec!["read"],
                |tools| tools.iter().copied().map(tool_name).collect(),
            ),
            guard: Some(format!(
                "the agent that proved the step {} changed the folder, but it may only read",
                step.id
            )),
        };
        let said = self.ask(key.clone(), request)?.text;
        let points = verdict(&said);
        let back = points
            .as_deref()
            .map(|points| named_in_points(points, offered))
            .unwrap_or_default();
        Ok((check, points, back))
    }

    /// Checks the needs of a proof in the folder, or recalls what was missing when the run was given that before:
    /// the needs in words, and what is missing.
    fn needs(&mut self, key: String, proof: &Proof, values: &Values) -> (String, Option<String>) {
        let needs: Vec<vpf::Need> = proof
            .needs()
            .iter()
            .map(|need| fill_need(need, values))
            .collect();
        let asked = needs.iter().map(describe).collect::<Vec<_>>().join("; ");
        let missing: Vec<String> = if let Some((missing, _)) = self.recall(&key) {
            missing
        } else {
            self.go_live();
            let missing: Vec<String> = needs
                .iter()
                .filter_map(|need| meets(&self.folder, need).err())
                .collect();
            self.keep(key, &missing);
            missing
        };
        (asked, (!missing.is_empty()).then(|| missing.join("\n")))
    }

    /// Runs the plan a step names, as that step.
    fn other_plan(
        &mut self,
        step: &Step,
        values: &Values,
        at: &str,
        attempt: &mut Attempt,
    ) -> Result<String, Halt> {
        let name = step.plan.clone().unwrap_or_default();
        if self.stack.contains(&name) {
            return Err(format!("the plan {name} runs itself, in a loop").into());
        }
        let key = format!("{at}plan");
        let text = if let Some((text, _)) = self.recall::<String>(&key) {
            text
        } else {
            self.go_live();
            let file = self.plans.join(format!("{name}.vpf.json"));
            let text = fs::read_to_string(&file)
                .map_err(|_| format!("cannot find the plan {name}, in {}", file.display()))?;
            self.keep(key, &text);
            text
        };
        let report = vpf::check(&text);
        let Some(other) = report.plan.filter(|_| report.problems.is_empty()) else {
            let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
            return Err(format!("the plan {name} has problems: {}", problems.join("; ")).into());
        };
        self.stack.push(name);
        let asked = match &step.asked {
            None => fill(&step.what, values),
            Some(vpf::Asked::Text(text)) => fill(text, values),
            Some(vpf::Asked::Fields(fields)) => serde_json::Value::Object(
                fields
                    .iter()
                    .map(|(name, value)| (name.clone(), fill_json(value, values)))
                    .collect(),
            )
            .to_string(),
        };
        attempt.steps.clear();
        let ended = self.steps(&other, &asked, &mut attempt.steps, at);
        self.stack.pop();
        ended
    }
}

/// Where a step runs: under which keys of the journal, its round, and when it started.
struct Place<'k> {
    base: &'k str,
    round: u32,
    started: Timestamp,
}

/// The conversation the last refused work of a step went on in, which its agent is told and may go on in.
fn last_conversation(attempts: &[Attempt]) -> Option<String> {
    attempts
        .iter()
        .rev()
        .find_map(|earlier| earlier.conversation.clone())
}

/// What an agent is asked, before the runner adds the folder and the time left.
struct Request {
    role: Role,
    /// The step it is asked for.
    step: String,
    /// The conversation of the step's refused work.
    conversation: Option<String>,
    prompt: String,
    agent: Option<String>,
    model: Option<String>,
    tools: Vec<&'static str>,
    /// When the agent may not change the folder: why the run stops if it does.
    guard: Option<String>,
}

/// An agent or a command a step asks, to work while the run goes on.
enum Job {
    Agent(Request),
    /// A command line, and where it keeps its process, its output and how it ended, for work that cannot be
    /// undone.
    Command {
        line: String,
        keep: Option<PathBuf>,
    },
}

/// The error an agent ended with, as the journal keeps it: the work it was given is refused with it.
#[derive(Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct AgentError {
    error: String,
}

/// What an agent or a command gave when it ended.
enum Finished {
    Agent(Result<AgentAnswer, String>),
    Command(Result<command::Ended, TimeOver>),
}

impl Job {
    /// Why the run stops when this agent changes the folder, for an agent that may only read.
    fn guard(&self) -> Option<&str> {
        match self {
            Self::Agent(request) => request.guard.as_deref(),
            Self::Command { .. } => None,
        }
    }

    fn run(
        self,
        key: &str,
        agent: &dyn Agent,
        folder: &Path,
        deadline: Option<Instant>,
        cost_left: Option<f64>,
    ) -> Finished {
        match self {
            Self::Agent(request) => Finished::Agent(agent.ask(&AgentRequest {
                role: request.role,
                step: &request.step,
                key,
                conversation: request.conversation.as_deref(),
                cost_left,
                prompt: request.prompt,
                agent: request.agent.as_deref(),
                model: request.model.as_deref(),
                tools: request.tools,
                folder,
                deadline,
            })),
            Self::Command { line, keep: None } => {
                Finished::Command(command::run(&line, folder, &[], "", deadline))
            }
            Self::Command {
                line,
                keep: Some(keep),
            } => Finished::Command(command::run_kept(&line, folder, &keep, deadline)),
        }
    }
}

impl Finished {
    /// What to keep in the journal, or why the run stops.
    fn value(self) -> Result<serde_json::Value, String> {
        let kept = match self {
            Self::Agent(answer) => serde_json::to_value(answer?),
            Self::Command(ended) => {
                serde_json::to_value(ended.map_err(|TimeOver| Runner::time_over())?)
            }
        };
        kept.map_err(|error| error.to_string())
    }
}

/// One proof to ask of an answer.
struct Asked<'a> {
    proof: &'a Proof,
    values: &'a Values,
    answer: &'a str,
    worker: Option<&'a str>,
    offered: &'a [String],
    key: String,
    /// The key of the attempt the proof is asked of.
    at: &'a str,
    /// The proofs of this attempt that passed before this one, in words.
    passed: &'a [String],
}

/// What an agent that proves work is shown of it.
struct Witness<'a> {
    answer: &'a str,
    /// The proofs that passed before, in words.
    passed: &'a [String],
    /// The files the work changed, when the runner knows.
    changed: Option<&'a [String]>,
    /// The lines the work removed and added in the text files it changed, as a unified diff.
    changes: &'a str,
}

/// A proof that passed, in words, for the proofs asked after it.
/// The process of a command of work that cannot be undone that still runs in `dir`, from before the run stopped.
fn still_running(dir: &Path) -> Option<u32> {
    if command::kept(dir).is_some() {
        return None;
    }
    let pid: u32 = fs::read_to_string(dir.join("pid"))
        .ok()?
        .trim()
        .parse()
        .ok()?;
    command::alive(pid).then_some(pid)
}

/// Why a proof for one path was not asked: the answer it is for, and what was given.
fn path_words(
    when: &std::collections::BTreeMap<String, String>,
    values: &Values,
    skipped: &HashSet<String>,
) -> String {
    when.iter()
        .map(|(id, answer)| {
            let given = if skipped.contains(id) {
                "it was skipped".to_owned()
            } else {
                format!(
                    "it answered “{}”",
                    values.get(id).map_or("", String::as_str)
                )
            };
            format!("Only when {id} answers “{answer}”; {given}.")
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// What a proof asks, with references filled, for the record of a proof that was not asked.
fn proof_asked(proof: &Proof, values: &Values) -> String {
    let text = match proof.by {
        Prover::Algorithm => proof.run.as_deref(),
        Prover::Agent => proof.check.as_deref(),
        Prover::Person => proof.ask.as_deref(),
    };
    match text {
        Some(text) => fill(text, values),
        None if proof.by == Prover::Algorithm => "Its needs".to_owned(),
        None => "Whether the work is good".to_owned(),
    }
}

fn passed_words(proof: &Proof, asked: &str) -> String {
    match proof.by {
        Prover::Algorithm if proof.run.is_some() => format!("The command `{asked}` ended with 0."),
        Prover::Algorithm => format!("These are there: {asked}."),
        Prover::Agent => format!("Another agent found this true: “{asked}”"),
        Prover::Person => format!(
            "A person approved: {}",
            asked.lines().next().unwrap_or_default()
        ),
    }
}

/// What the run knows of the order of a plan's steps.
struct Graph<'p> {
    index: HashMap<&'p str, usize>,
    /// The steps each step waits for itself.
    waits: Vec<Vec<usize>>,
    /// The steps each step waits for, and the steps those wait for.
    all_waits: Vec<HashSet<usize>>,
}

impl<'p> Graph<'p> {
    fn of(plan: &'p Plan) -> Self {
        let index: HashMap<&str, usize> = plan
            .steps
            .iter()
            .enumerate()
            .map(|(number, step)| (step.id.as_str(), number))
            .collect();
        let waits: Vec<Vec<usize>> = (0..plan.steps.len())
            .map(|number| direct_waits(plan, number, &index))
            .collect();
        let all_waits = transitive(&waits);
        Self {
            index,
            waits,
            all_waits,
        }
    }
}

/// What the run may do next.
enum Look {
    /// Start this step.
    Start(usize),
    /// Look again: steps were skipped.
    Again,
    /// Wait until this time, when this step may start.
    Wait(Timestamp, usize),
    /// Every step is done.
    Done,
    /// No step can start and none waits for a time.
    Stuck,
}

/// Keeps how a step ended. When its work went back to earlier steps, opens them again with the points, and every
/// step between them and it, and says so.
fn settle(
    graph: &Graph<'_>,
    progress: &mut [Progress],
    record: &mut StepRecord,
    number: usize,
    ended: Ended,
    now: Timestamp,
) -> Option<String> {
    match ended {
        Ended::Passed(answer) => {
            record.answer = Some(answer.clone());
            let step = &mut progress[number];
            step.state = State::Passed;
            step.answer = answer;
            step.done = Some(now);
            step.again = None;
            None
        }
        Ended::LeftOut => {
            record.skipped = true;
            let step = &mut progress[number];
            step.state = State::Skipped;
            step.answer = String::new();
            step.done = Some(now);
            None
        }
        Ended::Back { to, points } => {
            let chosen: Vec<usize> = to.iter().map(|id| graph.index[id.as_str()]).collect();
            for (other, again) in progress.iter_mut().enumerate() {
                let between = graph.all_waits[number].contains(&other)
                    && chosen
                        .iter()
                        .any(|&one| graph.all_waits[other].contains(&one));
                if chosen.contains(&other) {
                    again.state = State::Open;
                    again.again = Some((again.answer.clone(), points.clone()));
                } else if between {
                    again.state = State::Open;
                    again.again = None;
                }
            }
            Some(format!("The work goes back to {}.", to.join(", ")))
        }
    }
}

/// When a step may start, when it has `not_before`: a date, or a wait from when the steps it waits for are done,
/// or from the start of the run.
fn not_before(
    step: &Step,
    waits: &[usize],
    progress: &[Progress],
    started: Timestamp,
) -> Option<Timestamp> {
    let moment = Moment::read(step.not_before.as_deref()?)?;
    let from = waits
        .iter()
        .filter_map(|&wait| progress[wait].done)
        .max()
        .unwrap_or(started);
    Some(moment.from(from))
}

/// The steps a step waits for itself: its `after`, or the step written before it.
fn direct_waits(plan: &Plan, number: usize, index: &HashMap<&str, usize>) -> Vec<usize> {
    match &plan.steps[number].after {
        Some(after) => after
            .iter()
            .filter_map(|id| index.get(id.as_str()).copied())
            .collect(),
        None => number.checked_sub(1).into_iter().collect(),
    }
}

/// For each step, every step it waits for, and every step those wait for.
fn transitive(waits: &[Vec<usize>]) -> Vec<HashSet<usize>> {
    let mut all: Vec<HashSet<usize>> = Vec::with_capacity(waits.len());
    // A step waits only for steps written before it, so theirs are known first.
    for direct in waits {
        let mut set = HashSet::new();
        for &wait in direct {
            set.insert(wait);
            set.extend(all[wait].iter().copied());
        }
        all.push(set);
    }
    all
}

/// The items of an answer: the items of a JSON array, or each line that is not blank.
fn items(answer: &str) -> Vec<String> {
    if let Ok(serde_json::Value::Array(list)) = serde_json::from_str(answer.trim()) {
        return list.iter().map(text).collect();
    }
    answer
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(str::to_owned)
        .collect()
}

/// A command's refusal: the offered steps it names, one per line, at the start of what it wrote, and the rest.
fn named_first(said: &str, offered: &[String]) -> (Vec<String>, String) {
    let mut back = Vec::new();
    let mut lines = said.lines().peekable();
    while let Some(line) = lines.peek() {
        let id = line.trim();
        if offered.iter().any(|offered| offered == id) {
            if !back.iter().any(|named: &String| named == id) {
                back.push(id.to_owned());
            }
            lines.next();
        } else {
            break;
        }
    }
    let rest = lines.collect::<Vec<_>>().join("\n").trim().to_owned();
    if back.is_empty() || rest.is_empty() {
        (back, said.to_owned())
    } else {
        (back, rest)
    }
}

/// A proving agent's refusal: the offered steps it names on a line `Back to: a, b`.
fn named_in_points(points: &str, offered: &[String]) -> Vec<String> {
    let mut back = Vec::new();
    for line in points.lines() {
        let line = line.trim();
        let Some(rest) = line
            .get(..8)
            .filter(|start| start.eq_ignore_ascii_case("back to:"))
            .map(|_| &line[8..])
        else {
            continue;
        };
        for id in rest.split([',', ' ']).map(str::trim) {
            if offered.iter().any(|offered| offered == id) && !back.iter().any(|named| named == id)
            {
                back.push(id.to_owned());
            }
        }
    }
    back
}

/// The choice an answer gives: the answer itself, or the choice on its last line when the words before explain it.
fn chosen(answer: &str, choices: &[String]) -> String {
    let answer = answer.trim();
    let last = answer.lines().next_back().unwrap_or_default().trim();
    if !choices.iter().any(|choice| choice == answer) && choices.iter().any(|choice| choice == last)
    {
        return last.to_owned();
    }
    answer.to_owned()
}

/// A JSON value with the references in every text inside it filled.
fn fill_json(value: &serde_json::Value, values: &Values) -> serde_json::Value {
    use serde_json::Value;
    match value {
        Value::String(text) => Value::String(fill(text, values)),
        Value::Array(list) => {
            Value::Array(list.iter().map(|value| fill_json(value, values)).collect())
        }
        Value::Object(fields) => Value::Object(
            fields
                .iter()
                .map(|(name, value)| (name.clone(), fill_json(value, values)))
                .collect(),
        ),
        other => other.clone(),
    }
}

fn fill_need(need: &vpf::Need, values: &Values) -> vpf::Need {
    use vpf::Need;
    match need {
        Need::Files { path, at_least } => Need::Files {
            path: fill(path, values),
            at_least: *at_least,
        },
        Need::Folder { path } => Need::Folder {
            path: fill(path, values),
        },
        Need::Names { path, files } => Need::Names {
            path: fill(path, values),
            files: fill(files, values),
        },
        Need::Headings { path, headings } => Need::Headings {
            path: fill(path, values),
            headings: headings.clone(),
        },
        Need::Repository { path, branch } => Need::Repository {
            path: fill(path, values),
            branch: branch.clone(),
        },
    }
}

/// `None` when a proving agent's answer passes the work, or the points against it.
fn verdict(said: &str) -> Option<String> {
    let mut lines = said.trim().lines();
    let first = lines.next().unwrap_or_default().trim().to_uppercase();
    let rest = lines.collect::<Vec<_>>().join("\n").trim().to_owned();
    if first.starts_with("PASS") {
        None
    } else if first.starts_with("FAIL") {
        Some(if rest.is_empty() {
            "The proving agent gave no points.".to_owned()
        } else {
            rest
        })
    } else {
        Some(format!(
            "The proving agent did not answer PASS or FAIL: {}",
            said.trim()
        ))
    }
}

/// What will prove a step's work, one line per proof, in order.
fn proofs_in_words(step: &Step, values: &Values) -> String {
    let mut lines = String::new();
    let mut number = 0;
    let mut line = |text: String| {
        number += 1;
        let _ = writeln!(lines, "{number}. {text}");
    };
    if step.by == By::Algorithm {
        line(format!(
            "The command `{}` must pass.",
            fill(step.run.as_deref().unwrap_or_default(), values)
        ));
    }
    if let Some(choices) = &step.choices {
        line(format!(
            "The answer must be exactly one of: {}.",
            choices.join(", ")
        ));
    }
    for proof in step.proofs() {
        line(match proof.by {
            Prover::Algorithm => match &proof.run {
                Some(run) => format!("The command `{}` must pass.", fill(run, values)),
                None => format!(
                    "The folder must hold {}.",
                    proof
                        .needs()
                        .iter()
                        .map(|need| describe(&fill_need(need, values)))
                        .collect::<Vec<_>>()
                        .join("; ")
                ),
            },
            Prover::Agent => format!(
                "Another agent must find this true: “{}”",
                fill(proof.check.as_deref().unwrap_or_default(), values)
            ),
            Prover::Person => match &proof.ask {
                Some(ask) if !ask.trim().is_empty() => {
                    format!("A person must answer yes to: “{}”", fill(ask, values))
                }
                _ => "A person must approve your work.".to_owned(),
            },
        });
    }
    lines
}

fn work_prompt(
    plan: &Plan,
    step: &Step,
    values: &Values,
    last: Option<&(String, String)>,
) -> String {
    let mut prompt = format!(
        "The wish: {}\n\nYour step, {}: {}\n\nWhat will prove your work, in this order:\n{}",
        plan.wish,
        step.id,
        fill(&step.what, values),
        proofs_in_words(step, values)
    );
    if let Some((answer, points)) = last {
        let _ = write!(
            prompt,
            "\nYour last answer was refused.\n\nYour last answer:\n{answer}\n\nThe points against it:\n{points}\n"
        );
    }
    match &step.choices {
        Some(choices) => {
            let _ = writeln!(
                prompt,
                "\nDo the work, then answer with exactly one of: {}. Write nothing else.",
                choices.join(", ")
            );
        }
        None => prompt.push_str("\nDo the work, then answer with what you did.\n"),
    }
    prompt
}

fn fix_prompt(plan: &Plan, step: &Step, line: &str, points: &str) -> String {
    format!(
        "The wish: {}\n\nThe step {}: {}\n\nThe command `{line}` failed in the folder. What it wrote:\n{points}\n\n\
         Fix what stands in its way. Then the command runs again as the proof of your work, followed by the \
         step's own proofs:\n{}\nAnswer with what you changed.\n",
        plan.wish,
        step.id,
        step.what,
        proofs_in_words(step, &HashMap::new())
    )
}

/// How many changed files a proving agent is shown by name.
const SHOWN_FILES: usize = 40;

fn judge_prompt(
    plan: &Plan,
    step: &Step,
    values: &Values,
    witness: &Witness<'_>,
    check: &str,
    offered: &[String],
) -> String {
    let mut prompt = format!(
        "You prove another agent's work. Only read: do not change the folder.\n\nThe wish: {}\n\nThe step {}: {}\n\n\
         Its answer:\n{}\n\n",
        plan.wish,
        step.id,
        fill(&step.what, values),
        witness.answer
    );
    if !witness.passed.is_empty() {
        prompt.push_str("Already passed, before you:\n");
        for passed in witness.passed {
            let _ = writeln!(prompt, "- {passed}");
        }
        prompt.push('\n');
    }
    match witness.changed {
        Some([]) => prompt.push_str("The work changed no file in the folder.\n\n"),
        Some(changed) => {
            prompt.push_str(
                "Files the work changed, added or removed (steps working at the same time may have changed some):\n",
            );
            for path in changed.iter().take(SHOWN_FILES) {
                let _ = writeln!(prompt, "- {path}");
            }
            if changed.len() > SHOWN_FILES {
                let _ = writeln!(prompt, "- and {} more", changed.len() - SHOWN_FILES);
            }
            prompt.push('\n');
        }
        None => {}
    }
    if !witness.changes.is_empty() {
        prompt.push_str("The lines it removed (-) and added (+) in the text files:\n");
        prompt.push_str(witness.changes);
        prompt.push('\n');
    }
    let _ = write!(
        prompt,
        "Judge only whether this is true: “{check}”\n\
         What already passed is settled: do not judge it again.\n\n\
         Answer PASS or FAIL on the first line. After FAIL, give the points against the work.\n"
    );
    if !offered.is_empty() {
        let _ = writeln!(
            prompt,
            "When the fault is in the work of earlier steps, end with a line `Back to:` naming them, among: {}.",
            offered.join(", ")
        );
    }
    prompt
}

#[cfg(test)]
mod tests {
    use super::{items, named_first, named_in_points, transitive};

    fn ids(list: &[&str]) -> Vec<String> {
        list.iter().map(|&id| id.to_owned()).collect()
    }

    #[test]
    fn a_step_waits_for_what_its_waits_wait_for() {
        let all = transitive(&[vec![], vec![0], vec![], vec![1, 2]]);
        assert!(all[3].contains(&0) && all[3].contains(&1) && all[3].contains(&2));
        assert!(all[2].is_empty());
    }

    #[test]
    fn items_come_from_a_json_list_or_from_lines() {
        assert_eq!(items("a\n\n  b \n"), ["a", "b"]);
        assert_eq!(
            items(r#"["a", 2, {"x":1}, null]"#),
            ["a", "2", r#"{"x":1}"#, ""]
        );
        assert_eq!(items(""), Vec::<String>::new());
        assert_eq!(items("[]"), Vec::<String>::new());
    }

    #[test]
    fn refusals_name_the_steps_to_send_back() {
        let offered = ids(&["intro", "numbers"]);
        assert_eq!(
            named_first("numbers\nintro\nnumbers\nThe totals are missing.", &offered),
            (
                ids(&["numbers", "intro"]),
                "The totals are missing.".to_owned()
            )
        );
        assert_eq!(
            named_first("ending\nNo.", &offered),
            (Vec::new(), "ending\nNo.".to_owned())
        );
        assert_eq!(
            named_in_points("They disagree.\nback to: numbers, ending", &offered),
            ids(&["numbers"])
        );
        assert_eq!(
            named_in_points("The numbers are wrong.", &offered),
            Vec::<String>::new()
        );
    }
}