aidaemon-work 0.27.0

Goals, mandates, tasks and work coordination with a SQLite store; internal to aidaemon, no stability promise
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
//! Persistent Task Plans for reliable multi-step task execution.
//!
//! This module provides a planning system that:
//! - Persists multi-step task state to SQLite
//! - Keeps a task's checklist across a restart (the resume itself is built
//!   from the event log, see `agent/runtime/resume.rs`)
//! - Provides explicit step-by-step progress tracking
//! - Supports resume capability for long-running tasks

pub mod checklist_args;
mod store;

pub use store::{PlanStore, migrate_task_plans};

/// Start of the user-facing render in this tool's output. The agent loop
/// locates it to lift the checklist onto the live status surface, so any
/// model-only notice must precede it.
pub const CHECKLIST_HEADER: &str = "Checklist updated";

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

use crate::traits::ToolMutationEffects;
pub use aidaemon_core::card::StepEvidence;
use aidaemon_events::text::truncate_str;

/// A persistent multi-step task plan.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskPlan {
    /// Unique identifier (UUID)
    pub id: String,

    /// Session this plan belongs to
    pub session_id: String,

    /// Human-readable description (from user request)
    pub description: String,

    /// The original user message that triggered this plan
    pub trigger_message: String,

    /// Ordered list of steps
    pub steps: Vec<PlanStep>,

    /// Index of current step (0-based)
    pub current_step: usize,

    /// Overall plan status
    pub status: PlanStatus,

    /// Arbitrary checkpoint data (tool outputs, intermediate results)
    pub checkpoint: JsonValue,

    /// Why the plan was created (complexity heuristic result)
    pub creation_reason: String,

    /// Task ID from event store (links plan to events)
    pub task_id: Option<String>,

    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl TaskPlan {
    /// Create a new task plan with the given steps.
    pub fn new(
        session_id: impl Into<String>,
        trigger_message: impl Into<String>,
        description: impl Into<String>,
        steps: Vec<String>,
        creation_reason: impl Into<String>,
    ) -> Self {
        let now = Utc::now();
        let plan_steps: Vec<PlanStep> = steps
            .into_iter()
            .enumerate()
            .map(|(index, description)| PlanStep {
                index,
                description,
                depends_on: index.checked_sub(1).into_iter().collect(),
                required_mutation_effects: ToolMutationEffects::NONE,
                requires_observation: false,
                expected_targets: Vec::new(),
                owner_units: Vec::new(),
                evidence_receipt_ids: Vec::new(),
                background_jobs: Vec::new(),
                waited_jobs: Vec::new(),
                made_folders: Vec::new(),
                not_done: None,
                evidence: StepEvidence::Settled,
                status: if index == 0 {
                    StepStatus::InProgress
                } else {
                    StepStatus::Pending
                },
                tool_call_ids: Vec::new(),
                result_summary: None,
                error: None,
                retry_count: 0,
                started_at: if index == 0 { Some(now) } else { None },
                completed_at: None,
            })
            .collect();

        Self {
            id: uuid::Uuid::new_v4().to_string(),
            session_id: session_id.into(),
            description: description.into(),
            trigger_message: trigger_message.into(),
            steps: plan_steps,
            current_step: 0,
            status: PlanStatus::InProgress,
            checkpoint: JsonValue::Object(serde_json::Map::new()),
            creation_reason: creation_reason.into(),
            task_id: None,
            created_at: now,
            updated_at: now,
        }
    }

    /// Get the current step, if any.
    pub fn current_step_ref(&self) -> Option<&PlanStep> {
        self.steps.get(self.current_step)
    }

    /// Get the current step mutably, if any.
    pub fn current_step_mut(&mut self) -> Option<&mut PlanStep> {
        self.steps.get_mut(self.current_step)
    }

    /// Keep the user-facing execution pointer aligned with checklist state.
    /// While work remains, exactly one pending step is promoted to in-progress.
    pub fn sync_active_step(&mut self) {
        if let Some(index) = self
            .steps
            .iter()
            .position(|step| step.status == StepStatus::InProgress)
        {
            self.current_step = index;
            return;
        }

        if let Some(index) = self
            .ready_step_indices()
            .ok()
            .and_then(|indices| indices.into_iter().next())
        {
            self.current_step = index;
            if self.status == PlanStatus::InProgress {
                let step = &mut self.steps[index];
                step.status = StepStatus::InProgress;
                step.started_at.get_or_insert_with(Utc::now);
            }
        } else if self.is_finished() {
            self.status = self.resolved_status();
        }
        self.updated_at = Utc::now();
    }

    /// Calculate total duration in seconds.
    pub fn duration_secs(&self) -> u64 {
        (self.updated_at - self.created_at).num_seconds().max(0) as u64
    }

    /// Count completed steps.
    pub fn completed_steps(&self) -> usize {
        self.steps
            .iter()
            .filter(|s| s.status == StepStatus::Completed)
            .count()
    }

    /// Completed action steps no receipt verified: the only steps the card
    /// flags ([`PlanStep::unverified`]).
    pub fn unverified_steps(&self) -> usize {
        self.steps.iter().filter(|s| s.unverified()).count()
    }

    /// The steps at `indices` were confirmed by typed evidence (the run's
    /// receipts proved their checklist items): no longer said done only.
    /// Returns whether any step changed.
    pub fn confirm_steps(&mut self, indices: &std::collections::BTreeSet<usize>) -> bool {
        let mut changed = false;
        for step in &mut self.steps {
            if step.evidence == StepEvidence::ModelSaid && indices.contains(&step.index) {
                step.evidence = StepEvidence::Settled;
                changed = true;
            }
        }
        if changed {
            self.updated_at = Utc::now();
        }
        changed
    }

    /// The helper meant for the steps at `indices` never started (its
    /// `spawn_agent` call failed): nothing works on them, so they are not
    /// done, and the card says they didn't run. A step already done or set
    /// aside is left alone. Returns whether any step changed.
    pub fn helper_did_not_start(&mut self, indices: &[usize], reason: &str) -> bool {
        let now = Utc::now();
        let mut changed = false;
        for &index in indices {
            let Some(step) = self.steps.get_mut(index) else {
                continue;
            };
            if matches!(
                step.status,
                StepStatus::Completed | StepStatus::Skipped | StepStatus::Deferred
            ) || (step.status == StepStatus::Background && !step.background_jobs.is_empty())
            {
                continue;
            }
            step.status = StepStatus::Failed;
            step.evidence = StepEvidence::HelperNotStarted;
            step.waited_jobs.clear();
            step.error = Some(reason.to_string());
            step.completed_at = Some(now);
            changed = true;
        }
        if changed {
            if self.is_finished() {
                self.status = self.resolved_status();
            } else {
                self.sync_active_step();
            }
            self.updated_at = now;
        }
        changed
    }

    /// Check if all steps are done (completed, failed, or skipped).
    pub fn is_finished(&self) -> bool {
        self.steps.iter().all(|s| {
            matches!(
                s.status,
                StepStatus::Completed
                    | StepStatus::Failed
                    | StepStatus::Skipped
                    | StepStatus::Deferred
            )
        })
    }

    /// Derive the terminal plan state from typed step outcomes. A deferred
    /// item is resolved for scheduling purposes but is not successful work.
    pub fn resolved_status(&self) -> PlanStatus {
        if self
            .steps
            .iter()
            .any(|step| step.status == StepStatus::Failed)
        {
            PlanStatus::Failed
        } else if self
            .steps
            .iter()
            .any(|step| step.status == StepStatus::Deferred)
        {
            PlanStatus::PartiallyCompleted
        } else {
            PlanStatus::Completed
        }
    }

    /// Validate the persisted step dependency graph.
    pub fn validate_graph(&self) -> Result<(), String> {
        self.step_graph().map(|_| ())
    }

    /// Pending steps whose prerequisites have reached accepted terminal state.
    /// The current executor selects one deterministically; task-level workers
    /// can use the same graph shape for actual parallel branches.
    pub fn ready_step_indices(&self) -> Result<Vec<usize>, String> {
        let graph = self.step_graph()?;
        Ok(self
            .steps
            .iter()
            .filter(|step| {
                step.status == StepStatus::Pending
                    && graph.dependencies_satisfied(&plan_step_node_id(step.index))
            })
            .map(|step| step.index)
            .collect())
    }

    fn step_graph(&self) -> Result<aidaemon_events::execution_graph::ExecutionGraph, String> {
        use aidaemon_events::execution_graph::{
            ExecutionEdgeKind, ExecutionGraph, ExecutionNodeKind, ExecutionNodeState,
        };

        let mut graph = ExecutionGraph::default();
        for (position, step) in self.steps.iter().enumerate() {
            if step.index != position {
                return Err(format!(
                    "plan step index {} does not match position {}",
                    step.index, position
                ));
            }
            let state = match step.status {
                StepStatus::Pending => ExecutionNodeState::Pending,
                StepStatus::InProgress | StepStatus::Background => ExecutionNodeState::Running,
                StepStatus::Completed | StepStatus::Skipped | StepStatus::Deferred => {
                    ExecutionNodeState::Satisfied
                }
                StepStatus::Failed => ExecutionNodeState::Failed,
            };
            graph.add_node(
                plan_step_node_id(step.index),
                ExecutionNodeKind::PlanStep,
                state,
            )?;
        }
        for step in &self.steps {
            let mut unique_dependencies = std::collections::BTreeSet::new();
            for dependency in &step.depends_on {
                if !unique_dependencies.insert(*dependency) {
                    return Err(format!(
                        "plan step {} lists dependency {} more than once",
                        step.index, dependency
                    ));
                }
                if *dependency >= self.steps.len() {
                    return Err(format!(
                        "plan step {} depends on missing step {}",
                        step.index, dependency
                    ));
                }
                graph.add_edge(
                    &plan_step_node_id(step.index),
                    &plan_step_node_id(*dependency),
                    ExecutionEdgeKind::DependsOn,
                    None,
                )?;
            }
        }
        Ok(graph)
    }

    /// Advance to the next step. Returns true if there was a next step.
    pub fn advance_to_next_step(&mut self) -> bool {
        if let Some(next_index) = self
            .ready_step_indices()
            .ok()
            .and_then(|indices| indices.into_iter().next())
        {
            self.current_step = next_index;
            if let Some(step) = self.steps.get_mut(self.current_step) {
                step.status = StepStatus::InProgress;
                step.started_at = Some(Utc::now());
            }
            self.updated_at = Utc::now();
            true
        } else if self.is_finished() {
            self.status = self.resolved_status();
            self.updated_at = Utc::now();
            false
        } else {
            self.updated_at = Utc::now();
            false
        }
    }

    /// Mark the current step as completed with a summary.
    pub fn complete_current_step(&mut self, summary: Option<String>) {
        if let Some(step) = self.current_step_mut() {
            step.status = StepStatus::Completed;
            step.completed_at = Some(Utc::now());
            step.result_summary = summary;
        }
        self.updated_at = Utc::now();
    }

    /// Mark the current step as failed with an error message.
    pub fn fail_current_step(&mut self, error: String) {
        if let Some(step) = self.current_step_mut() {
            step.status = StepStatus::Failed;
            step.completed_at = Some(Utc::now());
            step.error = Some(error);
        }
        self.updated_at = Utc::now();
    }

    /// Increment retry count for current step and reset to in-progress.
    pub fn retry_current_step(&mut self) {
        if let Some(step) = self.current_step_mut() {
            step.retry_count += 1;
            step.status = StepStatus::InProgress;
            step.error = None;
            step.started_at = Some(Utc::now());
            step.completed_at = None;
        }
        self.updated_at = Utc::now();
    }

    /// Steps still requiring action (not completed/deferred/failed/skipped).
    pub fn unchecked_steps(&self) -> Vec<&PlanStep> {
        self.steps
            .iter()
            .filter(|s| matches!(s.status, StepStatus::Pending | StepStatus::InProgress))
            .collect()
    }

    /// Whether a background job is still working on any step.
    pub fn has_background_steps(&self) -> bool {
        self.steps
            .iter()
            .any(|step| step.status == StepStatus::Background)
    }

    /// Hand the steps at `indices` to the background job `job_id`. A step
    /// owns its runs in order and its outcome is its latest run's: a step
    /// an earlier run failed or stopped short on is taken over by this one
    /// (a retry), and only this job's end settles it. A step already done
    /// or skipped is left alone. Returns whether any step changed.
    pub fn link_background_job(&mut self, indices: &[usize], job_id: &str) -> bool {
        let mut changed = false;
        for &index in indices {
            let Some(step) = self.steps.get_mut(index) else {
                continue;
            };
            if matches!(step.status, StepStatus::Completed | StepStatus::Skipped) {
                continue;
            }
            step.evidence = StepEvidence::Settled;
            step.error = None;
            step.not_done = None;
            // Its own run now: the jobs it waited on no longer settle it.
            step.waited_jobs.clear();
            step.status = StepStatus::Background;
            step.started_at.get_or_insert_with(Utc::now);
            step.completed_at = None;
            if !step.background_jobs.iter().any(|job| job == job_id) {
                step.background_jobs.push(job_id.to_string());
            }
            changed = true;
        }
        changed |= self.wait_on_runs_of_taken_units();
        if changed {
            // A step whose helper didn't start may have resolved the plan;
            // it is being worked on again.
            if !self.status.is_incomplete() {
                self.status = PlanStatus::InProgress;
            }
            self.updated_at = Utc::now();
        }
        changed
    }

    /// The steps a launch takes on: the steps it names that the plan lists,
    /// and each step whose owner units all fall within the units the launch
    /// says it carries out (`owner_units`). Typed links only: a launch
    /// whose named item is not a step of this plan, but which names the
    /// owner's unit, takes on the plan's own step for that unit, never a
    /// new row.
    ///
    /// A unit one of its named steps already carries is taken on through
    /// that step: the launch's own row for the unit, not every row of it.
    /// Several steps can share one unit ("install both sites"); a batch's
    /// children each name their own, and expanding the shared unit gave
    /// every child every row, so each row read both children's folders
    /// (live 2026-11-14: "Install Drupal … (made claude-company-wordpress-2,
    /// claude-company-drupal-2)").
    pub fn launch_steps(&self, named: &[usize], owner_units: &[usize]) -> Vec<usize> {
        let mut steps: Vec<usize> = named
            .iter()
            .copied()
            .filter(|index| *index < self.steps.len())
            .collect();
        let through_named: Vec<usize> = steps
            .iter()
            .flat_map(|index| self.steps[*index].owner_units.iter().copied())
            .collect();
        if !owner_units.is_empty() {
            for step in &self.steps {
                if !step.owner_units.is_empty()
                    && step
                        .owner_units
                        .iter()
                        .all(|unit| owner_units.contains(unit))
                    && !step
                        .owner_units
                        .iter()
                        .any(|unit| through_named.contains(unit))
                    && !steps.contains(&step.index)
                {
                    steps.push(step.index);
                }
            }
        }
        steps.sort_unstable();
        steps
    }

    /// A step still open whose every owner unit a run took on (through the
    /// steps those runs were handed) is being done by those runs: it waits
    /// on each of them and settles from their ends, never left open or
    /// called unattempted while they do its units (a screenshot of both
    /// sites, done by the two helpers installing them). Returns whether
    /// anything changed.
    fn wait_on_runs_of_taken_units(&mut self) -> bool {
        let taken: Vec<(Vec<usize>, Vec<String>)> = self
            .steps
            .iter()
            .filter(|step| {
                step.status == StepStatus::Background && !step.background_jobs.is_empty()
            })
            .map(|step| (step.owner_units.clone(), step.background_jobs.clone()))
            .collect();
        let mut changed = false;
        for step in &mut self.steps {
            let open = matches!(step.status, StepStatus::Pending | StepStatus::InProgress)
                || (step.status == StepStatus::Background && step.background_jobs.is_empty());
            if !open || step.owner_units.is_empty() {
                continue;
            }
            let covered = step
                .owner_units
                .iter()
                .all(|unit| taken.iter().any(|(units, _)| units.contains(unit)));
            if !covered {
                continue;
            }
            for (units, jobs) in &taken {
                if !units.iter().any(|unit| step.owner_units.contains(unit)) {
                    continue;
                }
                for job in jobs {
                    if !step.waited_jobs.contains(job) {
                        step.waited_jobs.push(job.clone());
                        changed = true;
                    }
                }
            }
            if step.status != StepStatus::Background {
                step.status = StepStatus::Background;
                step.completed_at = None;
                changed = true;
            }
        }
        changed
    }

    /// The steps a new helper would do that a helper still running already
    /// does, each with the running jobs on it. `indices` are the steps the
    /// new launch names (`checklist_items`). A launch that names none is
    /// judged against every open step: it is covered only when each of them
    /// is already being done (live 2026-11-14: the turn launched a WordPress
    /// and a Drupal helper, then a third helper for the WordPress install
    /// while the first still ran). A step whose helpers all ended is not
    /// covered, whatever its status still says, so a step an earlier helper
    /// ended without finishing can be launched again. `running` says whether
    /// a job is still running (the run records know that, not the plan).
    pub fn steps_covered_by_running_jobs(
        &self,
        indices: &[usize],
        running: impl Fn(&str) -> bool,
    ) -> Vec<CoveredStep> {
        let covered = |step: &PlanStep| -> Option<CoveredStep> {
            if step.status != StepStatus::Background {
                return None;
            }
            let jobs: Vec<String> = step
                .background_jobs
                .iter()
                .filter(|job| running(job))
                .cloned()
                .collect();
            (!jobs.is_empty()).then(|| CoveredStep {
                index: step.index,
                description: step.description.clone(),
                jobs,
            })
        };
        if !indices.is_empty() {
            return indices
                .iter()
                .filter_map(|index| self.steps.get(*index))
                .filter_map(covered)
                .collect();
        }
        let open: Vec<&PlanStep> = self
            .steps
            .iter()
            .filter(|step| {
                !matches!(
                    step.status,
                    StepStatus::Completed
                        | StepStatus::Skipped
                        | StepStatus::Failed
                        | StepStatus::Deferred
                )
            })
            .collect();
        let all: Vec<CoveredStep> = open.iter().filter_map(|step| covered(step)).collect();
        if open.is_empty() || all.len() < open.len() {
            return Vec::new();
        }
        all
    }

    /// The turn handed its work to background jobs `job_ids` without naming
    /// the steps they do (`checklist_items`): every step still open (marked
    /// handed off with no job yet, or already waiting on an earlier job)
    /// waits on them, so the card reads "continuing in the background", never
    /// "stopped short", while they run. Their typed ends settle such a step
    /// ([`PlanStep::waited_jobs`]). Returns whether anything changed.
    pub fn wait_on_background_jobs(&mut self, job_ids: &[String]) -> bool {
        if job_ids.is_empty() {
            return false;
        }
        let mut changed = false;
        for step in &mut self.steps {
            // A step already waiting on an earlier job waits on this one too
            // (live 2026-11-13: two helpers started by one turn; the second
            // was never on the plan, so the first's end settled the steps
            // while the second still ran, and its own end found no plan).
            // A step the model marked handed off ("background") before any
            // launch took it waits on the launches too: the mark says it
            // delegated, the jobs are what it delegated to (live 2026-11-13:
            // two such steps were skipped here, no run was ever linked to
            // them, and the turn's end set them aside as "not done" while
            // both helpers went on to succeed).
            let open = matches!(step.status, StepStatus::Pending | StepStatus::InProgress)
                || (step.status == StepStatus::Deferred && step.not_done.is_none())
                || (step.status == StepStatus::Background && step.background_jobs.is_empty());
            if !open {
                continue;
            }
            step.status = StepStatus::Background;
            step.completed_at = None;
            for job in job_ids {
                if !step.waited_jobs.contains(job) {
                    step.waited_jobs.push(job.clone());
                }
            }
            changed = true;
        }
        if changed {
            if self.is_finished() {
                self.status = self.resolved_status();
            }
            self.updated_at = Utc::now();
        }
        changed
    }

    /// A step the checklist marked "background" that no run took on or
    /// waits on is not running: it is open again, judged like any open step
    /// (a launch takes it, the turn's end settles it). The mark alone never
    /// leaves a row "running in the background" with nothing running.
    /// Returns whether anything changed.
    pub fn unmark_runless_background_steps(&mut self) -> bool {
        let mut changed = false;
        for step in &mut self.steps {
            if step.status == StepStatus::Background && !step.has_background_jobs() {
                step.status = StepStatus::Pending;
                changed = true;
            }
        }
        if changed {
            self.sync_active_step();
            self.updated_at = Utc::now();
        }
        changed
    }

    /// The folders background job `job_id` made (its claim evidence), on
    /// the steps it took on, before its end settles them. Returns whether
    /// any step changed.
    pub fn note_job_folders(&mut self, job_id: &str, folders: &[String]) -> bool {
        let mut changed = false;
        for step in &mut self.steps {
            if !step.background_jobs.iter().any(|job| job == job_id) {
                continue;
            }
            for folder in folders {
                if !step.made_folders.contains(folder) {
                    step.made_folders.push(folder.clone());
                    changed = true;
                }
            }
        }
        if changed {
            self.updated_at = Utc::now();
        }
        changed
    }

    /// Record the end of background job `job_id`, as its run record says.
    /// A step handed to several jobs (or waiting on them) settles once the
    /// last of them ended, from all their typed ends: completed when every
    /// one succeeded, failed when one failed (a step handed to it; a step
    /// that only waited on it is not done, with that reason), and not done
    /// when one stopped before finishing or ended short because the owner
    /// declined one of its steps. While others still run it stays in the
    /// background, so a later run's success is never lost (live 2026-11-13:
    /// the WordPress helper's end marked steps both helpers shared as not
    /// done, the Drupal helper then finished them, and the card read "1 of
    /// 5 done" above its helpers' finished lines). The plan resolves once
    /// nothing is left to run. Returns whether any step changed.
    pub fn settle_background_job(&mut self, job_id: &str, end: JobEnd) -> bool {
        let now = Utc::now();
        let mut changed = false;
        let short = match end {
            JobEnd::Succeeded => None,
            JobEnd::Declined => Some(NotDoneReason::OwnerDeclined),
            JobEnd::StoppedByOwner => Some(NotDoneReason::OwnerStopped),
            JobEnd::Stopped => Some(NotDoneReason::HelperStopped),
            JobEnd::Failed => Some(NotDoneReason::WaitedOnFailed),
        };
        // The worse of two ends: a failure, then a stop, then a decline.
        let rank = |reason: NotDoneReason| match reason {
            NotDoneReason::WaitedOnFailed => 3,
            NotDoneReason::HelperStopped => 2,
            _ => 1,
        };
        for step in &mut self.steps {
            let took_on = step.background_jobs.iter().any(|job| job == job_id);
            let waited = step.waited_jobs.iter().any(|job| job == job_id);
            if step.status != StepStatus::Background || !(took_on || waited) {
                continue;
            }
            changed = true;
            step.background_jobs.retain(|job| job != job_id);
            step.waited_jobs.retain(|job| job != job_id);
            // A step a job of its own took on settles from its own runs
            // only: an end it merely waited on is not its outcome (live
            // 2026-11-14: Drupal's success marked the WordPress step done).
            if !took_on && !step.background_jobs.is_empty() {
                continue;
            }
            if let Some(short) = short {
                step.not_done = Some(match step.not_done {
                    Some(earlier) if rank(earlier) >= rank(short) => earlier,
                    _ => short,
                });
            }
            if !step.background_jobs.is_empty() || (!took_on && !step.waited_jobs.is_empty()) {
                continue;
            }
            // Live 2026-11-13: a step that only waited on a background job
            // read "(not done)" after the job succeeded. Its runs' typed
            // ends are what settle it.
            step.waited_jobs.clear();
            step.completed_at = Some(now);
            match step.not_done {
                None => {
                    step.status = StepStatus::Completed;
                    step.evidence = StepEvidence::Settled;
                }
                Some(NotDoneReason::WaitedOnFailed) if took_on => {
                    step.status = StepStatus::Failed;
                    step.not_done = None;
                }
                Some(_) => step.status = StepStatus::Deferred,
            }
        }
        if changed {
            if self.is_finished() {
                self.status = self.resolved_status();
            } else {
                self.sync_active_step();
            }
            self.updated_at = now;
        }
        changed
    }

    /// Its turn is over and nothing it handed work to is still running: a
    /// step still open (pending, in progress, or waiting on a job no longer
    /// running) can no longer be done by anything, so it settles as not done
    /// ([`NotDoneReason::LeftOpen`]) and the plan resolves. A card never
    /// stays "working" on a step nothing is working on (live 2026-11-13: a
    /// "Report each helper's measured time" step held a card on "Working ·
    /// step 4 of 4" for 14 minutes after both helpers ended). Returns
    /// whether anything changed.
    ///
    /// While a job a launch handed a step to has not ended (it is still
    /// listed on the step), the plan's work is still going and nothing
    /// settles: that job's own end settles its step
    /// ([`Self::settle_background_job`]) and then the rest, however the
    /// card's runs were counted when this settle ran. Live 2026-11-13: the
    /// first helper's end settled the card while the second, launched for
    /// the WordPress step, was not yet counted on it; the card read
    /// "Stopped short · 1 of 3 (not done: nothing was left working on it)",
    /// then "Continuing", then "Stopped".
    pub fn settle_open_steps(&mut self) -> bool {
        if self
            .steps
            .iter()
            .any(|step| step.status == StepStatus::Background && step.has_background_jobs())
        {
            return false;
        }
        let now = Utc::now();
        let mut changed = false;
        for step in &mut self.steps {
            if matches!(
                step.status,
                StepStatus::Pending | StepStatus::InProgress | StepStatus::Background
            ) {
                step.status = StepStatus::Deferred;
                step.waited_jobs.clear();
                step.background_jobs.clear();
                step.not_done = Some(NotDoneReason::LeftOpen);
                step.completed_at = Some(now);
                changed = true;
            }
        }
        // Every step already has its outcome (the request's last turn did
        // the rest): the plan's own state follows them, so its header never
        // reads "Working" over rows that are all settled.
        let resolved = self.resolved_status();
        if changed || self.status != resolved {
            self.status = resolved;
            self.updated_at = now;
            changed = true;
        }
        changed
    }

    /// The run's ledger says nothing ever took on the steps at `indices`
    /// ([`NotDoneReason::NotAttempted`]): each settles as not done with that
    /// reason, unless it is done or skipped. A step that only waited on the
    /// turn's jobs without being handed to one waits no longer: no job is
    /// doing it. Returns whether anything changed.
    pub fn mark_not_attempted(&mut self, indices: &std::collections::BTreeSet<usize>) -> bool {
        let now = Utc::now();
        let mut changed = false;
        for &index in indices {
            let Some(step) = self.steps.get_mut(index) else {
                continue;
            };
            if matches!(step.status, StepStatus::Completed | StepStatus::Skipped)
                || (step.status == StepStatus::Background && !step.background_jobs.is_empty())
            {
                continue;
            }
            step.status = StepStatus::Deferred;
            step.waited_jobs.clear();
            step.background_jobs.clear();
            step.not_done = Some(NotDoneReason::NotAttempted);
            step.completed_at = Some(now);
            changed = true;
        }
        if changed {
            if self.is_finished() {
                self.status = self.resolved_status();
            } else {
                self.sync_active_step();
            }
            self.updated_at = now;
        }
        changed
    }

    /// Record that the steps not done in this plan were held back because
    /// the turn could not make changes: a failed or deferred step becomes a
    /// deferred step with [`NotDoneReason::ChangesOff`], which the card shows
    /// as correctly not done. Returns whether anything changed.
    pub fn hold_back_unfinished_steps(&mut self, reason: NotDoneReason) -> bool {
        let mut changed = false;
        for step in &mut self.steps {
            if matches!(step.status, StepStatus::Failed | StepStatus::Deferred)
                && step.not_done.is_none()
            {
                step.status = StepStatus::Deferred;
                step.not_done = Some(reason);
                step.completed_at.get_or_insert_with(Utc::now);
                changed = true;
            }
        }
        if changed {
            if self.is_finished() {
                self.status = self.resolved_status();
            }
            self.updated_at = Utc::now();
        }
        changed
    }

    /// The reason every step left undone shares, when all of them were held
    /// back for a known reason (and at least one was).
    fn shared_hold_reason(&self) -> Option<NotDoneReason> {
        let mut reason = None;
        for step in &self.steps {
            match (step.status, step.not_done) {
                (StepStatus::Completed | StepStatus::Skipped, _) => {}
                (StepStatus::Deferred, Some(found)) if reason.is_none_or(|r| r == found) => {
                    reason = Some(found);
                }
                _ => return None,
            }
        }
        reason
    }

    /// The plan as the card shows it: [`Self::render_compact_checklist`] and
    /// its step count, which decides whether the card is kept.
    pub fn card(&self) -> aidaemon_core::card::PlanCard {
        aidaemon_core::card::PlanCard {
            text: self.render_compact_checklist(),
            steps: self.steps.len(),
            done: self.completed_steps(),
            finished_steps: self
                .steps
                .iter()
                .filter(|step| matches!(step.status, StepStatus::Completed | StepStatus::Skipped))
                .map(|step| step.index)
                .collect(),
            settled: !self
                .steps
                .iter()
                .any(|step| matches!(step.status, StepStatus::Pending | StepStatus::InProgress)),
        }
    }

    /// Compact, channel-friendly checklist for the live status card.
    ///
    /// One header line carries the state and the count; the steps follow, a
    /// blank line apart so wrapped descriptions stay readable on a phone. A
    /// one-step plan is just that step (a header and a "1 of 1" would only
    /// repeat it). A fully completed card starts with ✅
    /// ([`is_completed_checklist`]), so the card drops the turn's own step
    /// line. A step that turned out not to be
    /// needed, or that was held back for a known reason, is never shown as a
    /// failure.
    pub fn render_compact_checklist(&self) -> String {
        let total = self.steps.len();
        let unverified = self.unverified_steps();
        let in_background = self.has_background_steps();
        let finished = !matches!(
            self.status,
            PlanStatus::Planning | PlanStatus::InProgress | PlanStatus::Paused
        );
        // Every completed step counts as done; the action steps nothing
        // verified are said once, in plain words, on the final card only.
        let done = self.completed_steps();
        let said_note = if unverified > 0 && finished && !in_background {
            format!("; I couldn't verify {unverified}")
        } else {
            String::new()
        };
        let not_needed = self
            .steps
            .iter()
            .filter(|step| step.status == StepStatus::Skipped)
            .count();
        let held = self.shared_hold_reason();
        if total == 1 && (self.status != PlanStatus::PartiallyCompleted || held.is_some()) {
            let step = &self.steps[0];
            let mark = match (self.status, step.status) {
                (_, StepStatus::Completed) if step.unverified() => "☑️",
                (_, StepStatus::Completed) => "✅",
                (_, StepStatus::Skipped) => "✅",
                _ if held.is_some() => "⏭️",
                (PlanStatus::Failed, _) | (_, StepStatus::Failed) => "❌",
                (PlanStatus::Abandoned, _) => "⏹️",
                (PlanStatus::Paused, _) => "⏸️",
                _ => "⏳",
            };
            let described = step.described();
            return match (step.status, held) {
                (StepStatus::Completed, _) if step.unverified() => {
                    format!("{mark} {described} ({UNVERIFIED})")
                }
                (StepStatus::Failed, _) if step.helper_not_started() => {
                    format!("{mark} {described} ({HELPER_NOT_STARTED})")
                }
                (StepStatus::Background, _) => {
                    format!("{mark} {described} (running in the background)")
                }
                (StepStatus::Skipped, _) => format!("{mark} {described} (not needed)"),
                (_, Some(reason)) => {
                    format!("{mark} {described} (not done: {})", reason.plain())
                }
                _ => format!("{mark} {described}"),
            };
        }
        let header = match self.status {
            // Work handed to a job that reports back is still being done:
            // never "stopped short" while it runs.
            _ if in_background => {
                format!("⏳ Continuing in the background · {done} of {total} done{said_note}")
            }
            // Everything left was held back for a known reason: the turn did
            // what it was allowed to, which is not a failure.
            _ if finished && held.is_some() => {
                let reason = held.map(NotDoneReason::plain).unwrap_or_default();
                format!("⏭️ Not done: {reason} · {done} of {total} done{said_note}")
            }
            PlanStatus::Planning => "🧭 Planning…".to_string(),
            PlanStatus::InProgress => {
                let position = self.current_step.saturating_add(1).min(total);
                format!("⚙️ Working · step {position} of {total}")
            }
            PlanStatus::Paused => format!("⏸️ Paused · {done} of {total} done{said_note}"),
            // Every step resolved, and an action step only on the model's
            // word: never a ✅ the evidence does not back.
            PlanStatus::Completed if unverified > 0 => {
                let needed_note = if not_needed > 0 {
                    format!(", {not_needed} not needed")
                } else {
                    String::new()
                };
                format!("☑️ Finished · {done} of {total} done{said_note}{needed_note}")
            }
            // The execution plan is resolved; the reply is still on its way,
            // which the typing indicator shows. Never claim the task is over.
            PlanStatus::Completed if not_needed > 0 => {
                format!("✅ Done · {done} done, {not_needed} not needed")
            }
            PlanStatus::Completed => format!("✅ Done · {done} of {total} steps"),
            PlanStatus::PartiallyCompleted => {
                format!("⚠️ Stopped short · {done} of {total} done{said_note}")
            }
            PlanStatus::Failed => format!("❌ Stopped · {done} of {total} done{said_note}"),
            PlanStatus::Abandoned => {
                format!("⏹️ Cancelled · {done} of {total} done{said_note}")
            }
        };
        let mut out = header;
        for step in &self.steps {
            let line = match (step.status, step.not_done) {
                (StepStatus::Completed, _) if step.unverified() => {
                    format!("☑️ {} ({UNVERIFIED})", step.described())
                }
                (StepStatus::Completed, _) => format!("✅ {}", step.described()),
                // Its row says only that it didn't run; why is said once,
                // under the rows, however many steps it applies to.
                (StepStatus::Failed, _) if step.helper_not_started() => {
                    format!("⚠️ {} (didn't run)", step.described())
                }
                (StepStatus::InProgress, _) => format!("▶️ {}", step.described()),
                (StepStatus::Background, _) => {
                    format!("⏳ {} (running in the background)", step.described())
                }
                (StepStatus::Deferred, Some(reason)) => {
                    format!("⏭️ {} (not done: {})", step.described(), reason.plain())
                }
                // `deferred` is the model's typed "set aside": the owner
                // reads what it means for them.
                (StepStatus::Deferred, None) => format!("⏭️ {} (not done)", step.described()),
                (StepStatus::Failed, _) => format!("⚠️ {} (couldn't be done)", step.described()),
                (StepStatus::Skipped, _) => format!("➖ {} (not needed)", step.described()),
                (StepStatus::Pending, _) => format!("○ {}", step.described()),
            };
            // A blank line between steps: descriptions wrap on a phone, and
            // without a gap the wrapped lines run into the next step.
            out.push_str("\n\n");
            out.push_str(&line);
        }
        if self.status == PlanStatus::PartiallyCompleted && !in_background && held.is_none() {
            out.push_str("\n\nThe reply below says what was left undone and why.");
        }
        // Why the steps marked "didn't run" never ran: said once, not on
        // each row (live 2026-11-14: "(didn't run: its helper didn't
        // start)" twice on one card, then the same steps again below).
        if self
            .steps
            .iter()
            .any(|step| step.status == StepStatus::Failed && step.helper_not_started())
        {
            out.push_str("\n\nDidn't run: its helper didn't start.");
        }
        out
    }

    /// End-of-turn recap of what got done vs what remains/deferred.
    pub fn render_recap(&self) -> String {
        let mut out = String::new();
        for step in &self.steps {
            let mark = match step.status {
                StepStatus::Completed => "✅",
                StepStatus::Deferred => "⏭️ (not done)",
                StepStatus::Failed => "⚠️ (failed)",
                StepStatus::Background => "⏳ (running in the background)",
                _ => "☐ (not done)",
            };
            out.push_str(&format!("{} {}\n", mark, step.description));
        }
        out.trim_end().to_string()
    }

    /// Format the plan for system prompt injection.
    pub fn format_for_prompt(&self) -> String {
        let mut lines = vec![
            "## Incomplete Task Plan".to_string(),
            format!("**Task:** {}", self.description),
            format!(
                "**Status:** {} ({}/{} steps complete)",
                self.status.as_str(),
                self.completed_steps(),
                self.steps.len()
            ),
            "**Steps:**".to_string(),
        ];

        for step in &self.steps {
            let marker = match step.status {
                StepStatus::Completed => "[x]",
                StepStatus::InProgress => "[>]",
                StepStatus::Failed => "[!]",
                StepStatus::Skipped => "[-]",
                StepStatus::Deferred => "[~]",
                StepStatus::Background => "[bg]",
                StepStatus::Pending => "[ ]",
            };
            let mut line = format!("  {} {}. {}", marker, step.index + 1, step.description);
            if let Some(ref error) = step.error {
                line.push_str(&format!(" (Error: {})", truncate_str(error, 50)));
            }
            lines.push(line);
        }

        lines.push(String::new());
        lines.push(
            "If the user wants to continue this task, resume from the current step.".to_string(),
        );
        lines.push(
            "If the user provides NEW REQUIREMENTS or CHANGES (e.g., 'use X instead', 'also add Y'), \
             use plan_manager with action='revise' to update the remaining steps accordingly."
                .to_string(),
        );
        lines.push(
            "If they want to start over or do something else, use plan_manager to abandon it first."
                .to_string(),
        );

        lines.join("\n")
    }
}

/// A checklist step a running helper already does
/// ([`TaskPlan::steps_covered_by_running_jobs`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoveredStep {
    pub index: usize,
    pub description: String,
    /// The running jobs (launch ids) on it.
    pub jobs: Vec<String>,
}

/// A single step in a task plan.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlanStep {
    /// Step index (0-based)
    pub index: usize,

    /// Human-readable description
    pub description: String,

    /// Indices of prerequisite steps. Missing on legacy rows means the steps
    /// are independent; newly generated plans persist explicit serial edges.
    #[serde(default)]
    pub depends_on: Vec<usize>,

    /// Typed evidence contract for automatic completion. If empty/false, only
    /// an explicit checklist update may complete the step.
    #[serde(default)]
    pub required_mutation_effects: ToolMutationEffects,
    #[serde(default)]
    pub requires_observation: bool,
    /// Exact canonical targets (path, URL, or resource ID), never prose.
    #[serde(default)]
    pub expected_targets: Vec<String>,
    /// The owner's units of work this step carries out (`owner_units` on
    /// its checklist item): the typed identity a re-declaration and a
    /// launch find the step by, wherever it sits in the list.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub owner_units: Vec<usize>,
    /// Tool-call receipt IDs that proved this step.
    #[serde(default)]
    pub evidence_receipt_ids: Vec<String>,

    /// Background jobs (their launch ids) that took this step on and still
    /// work on it: a launch named it in its typed `checklist_items`. Each
    /// job's end settles the step ([`TaskPlan::settle_background_job`]), and
    /// only these make a new helper for the step a duplicate.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub background_jobs: Vec<String>,

    /// Background jobs this step only waits on: it was left open while the
    /// turn's jobs ran, and no launch named it. It reads as running while
    /// they do and, while no job of its own took it on, settles from their
    /// typed ends: done once every one succeeded, not done (with the reason)
    /// once one failed or stopped. Waiting on a job is not being done by it:
    /// it never makes a launch for the step a duplicate.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub waited_jobs: Vec<String>,

    /// The folders the runs that took this step on made for it, from their
    /// claim evidence (what each found absent and then created), recorded
    /// as each run ended. The card names them, so a run that made another
    /// folder than the step's words named shows the real one (live
    /// 2026-11-14: the card read claude-drupal-12, the site was made in
    /// claude-company-drupal-5879).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub made_folders: Vec<String>,

    /// Why a step that was not done was left undone, when the daemon knows it
    /// from typed state (never from the step's text). Such a step was held
    /// back correctly, so the card does not show it as a failure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub not_done: Option<NotDoneReason>,

    /// How its state is known: settled by typed evidence, completed on the
    /// executing model's word alone (its checklist update said done and no
    /// receipt or helper's result proved it; evidence clears it), or handed
    /// to a helper that never started (a later launch takes it again).
    #[serde(default, skip_serializing_if = "StepEvidence::is_settled")]
    pub evidence: StepEvidence,

    /// Step status
    pub status: StepStatus,

    /// Tool calls made during this step (event IDs or tool:timestamp)
    pub tool_call_ids: Vec<String>,

    /// Summary of what was accomplished
    pub result_summary: Option<String>,

    /// Error message if step failed
    pub error: Option<String>,

    /// Number of retry attempts
    pub retry_count: u32,

    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone)]
pub struct ChecklistItem {
    pub description: String,
    pub status: StepStatus,
    pub depends_on: Vec<usize>,
    pub required_mutation_effects: ToolMutationEffects,
    pub requires_observation: bool,
    pub expected_targets: Vec<String>,
    /// The owner's units of work the item carries out.
    pub owner_units: Vec<usize>,
}

fn plan_step_node_id(index: usize) -> String {
    format!("plan-step:{index}")
}

impl PlanStep {
    /// Its words on the card, with the folders its runs made that its words
    /// do not already name: the real folder, from the claim evidence.
    pub fn described(&self) -> String {
        let unnamed: Vec<&str> = self
            .made_folders
            .iter()
            .map(|folder| {
                std::path::Path::new(folder)
                    .file_name()
                    .and_then(|name| name.to_str())
                    .unwrap_or(folder)
            })
            .filter(|name| !self.description.contains(name))
            .collect();
        match unnamed.as_slice() {
            [] => self.description.clone(),
            [one] => format!("{} (made {one})", self.description),
            many => format!("{} (made {})", self.description, many.join(", ")),
        }
    }

    /// Completed on the model's word alone, and a step that declared a
    /// side effect: the one kind of step the card flags. A step that
    /// changes nothing (a check, a read) needs no receipt: the reply says
    /// what it found.
    pub fn unverified(&self) -> bool {
        self.status == StepStatus::Completed
            && self.evidence == StepEvidence::ModelSaid
            && !self.required_mutation_effects.is_empty()
    }

    /// Any background job is still listed on it: one that took it on, or
    /// one it waits on.
    pub fn has_background_jobs(&self) -> bool {
        !self.background_jobs.is_empty() || !self.waited_jobs.is_empty()
    }

    /// It was handed to a helper that never started.
    pub fn helper_not_started(&self) -> bool {
        self.evidence == StepEvidence::HelperNotStarted
    }

    /// Calculate step duration in seconds (if completed).
    pub fn duration_secs(&self) -> Option<u64> {
        match (self.started_at, self.completed_at) {
            (Some(start), Some(end)) => Some((end - start).num_seconds().max(0) as u64),
            _ => None,
        }
    }
}

/// Overall plan status.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Serialize,
    Deserialize,
    strum::IntoStaticStr,
    strum::EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PlanStatus {
    /// LLM is generating steps
    Planning,
    /// Executing steps
    InProgress,
    /// Paused (session ended, waiting for user, or interrupted)
    Paused,
    /// All steps completed successfully
    Completed,
    /// Scheduling is resolved, but one or more requested steps were deferred.
    PartiallyCompleted,
    /// Unrecoverable failure
    Failed,
    /// User explicitly cancelled
    Abandoned,
}

impl PlanStatus {
    pub fn as_str(&self) -> &'static str {
        (*self).into()
    }

    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        s.parse().ok()
    }

    /// Check if this status represents an incomplete/active plan.
    pub fn is_incomplete(&self) -> bool {
        matches!(
            self,
            PlanStatus::Planning | PlanStatus::InProgress | PlanStatus::Paused
        )
    }
}

/// Status of a single step.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Serialize,
    Deserialize,
    strum::IntoStaticStr,
    strum::EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum StepStatus {
    /// Not yet started
    Pending,
    /// Currently executing
    InProgress,
    /// Completed successfully
    Completed,
    /// Failed (may retry)
    Failed,
    /// Skipped (dependency failed or user skipped)
    Skipped,
    /// Explicitly abandoned by the model (counts as resolved, not unchecked).
    Deferred,
    /// Handed to a background job that reports back: still being worked on,
    /// outside this run. Only the job's end moves it to completed or failed.
    Background,
}

impl StepStatus {
    pub fn as_str(&self) -> &'static str {
        (*self).into()
    }

    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        s.parse().ok()
    }
}

/// How the card marks an action step nothing verified.
const UNVERIFIED: &str = "I couldn't verify this one";
/// How the card marks a step whose helper never started.
const HELPER_NOT_STARTED: &str = "didn't run: its helper didn't start";

/// Why a step was correctly left undone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NotDoneReason {
    /// The turn could not change anything (read-only access or a request
    /// that forbids changes), and this step needed a change.
    ChangesOff,
    /// The background helper it was handed ended before finishing it (its
    /// run record says stopped: not a failure).
    HelperStopped,
    /// Its turn ended and nothing was left working on it.
    LeftOpen,
    /// A background job it waited on failed (its run record says so).
    WaitedOnFailed,
    /// The owner declined a step the helper it was handed asked to take,
    /// and it ended without finishing (its run record says so): the
    /// owner's answer, never a failure.
    OwnerDeclined,
    /// The owner stopped the helper it was handed before it finished: a
    /// stop, never a failure.
    OwnerStopped,
    /// Nothing ever took it on: no call did it, no job was launched for it,
    /// and the owner was not asked (the run's ledger says so).
    NotAttempted,
}

impl NotDoneReason {
    fn plain(self) -> &'static str {
        match self {
            Self::ChangesOff => "read-only is on",
            Self::HelperStopped => "its helper stopped before it finished",
            Self::LeftOpen => "nothing was left working on it",
            Self::WaitedOnFailed => "the work it waited on failed",
            Self::OwnerDeclined => "you declined a step its helper asked to take",
            Self::OwnerStopped => "you stopped its helper",
            Self::NotAttempted => "not attempted",
        }
    }
}

/// How a background job ended, as its run record says: what its steps
/// become. Only `Failed` marks a step as couldn't be done.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JobEnd {
    Succeeded,
    Stopped,
    /// It stopped short because the owner declined one of its steps.
    Declined,
    /// The owner stopped it before it finished.
    StoppedByOwner,
    Failed,
}

/// Whether a card from [`TaskPlan::render_compact_checklist`] shows every
/// step finished (the channel's live status reads cards the same way).
pub use aidaemon_channels::live_status::is_completed_checklist;

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

    fn two_sites() -> TaskPlan {
        TaskPlan::new(
            "session_123",
            "Install two sites",
            "Two sites",
            vec![
                "Install WordPress".to_string(),
                "Install Drupal".to_string(),
            ],
            "low",
        )
    }

    /// A step a running helper does is covered: a second launch for it is
    /// a duplicate. Once that helper ended without finishing it, it is open
    /// to a retry again.
    #[test]
    fn a_step_a_running_helper_does_is_covered_until_it_ends() {
        let mut plan = two_sites();
        plan.link_background_job(&[0], "job-wp");
        plan.link_background_job(&[1], "job-drupal");
        let running = |job: &str| job == "job-wp" || job == "job-drupal";

        let covered = plan.steps_covered_by_running_jobs(&[0], running);
        assert_eq!(
            covered,
            vec![CoveredStep {
                index: 0,
                description: "Install WordPress".to_string(),
                jobs: vec!["job-wp".to_string()],
            }]
        );
        // Every open step is being done: a launch naming none covers nothing new.
        assert_eq!(plan.steps_covered_by_running_jobs(&[], running).len(), 2);

        // The WordPress helper stopped short: its step may be launched again.
        plan.settle_background_job("job-wp", JobEnd::Stopped);
        let only_drupal = |job: &str| job == "job-drupal";
        assert!(
            plan.steps_covered_by_running_jobs(&[0], only_drupal)
                .is_empty()
        );
        // A retry names its step: unnamed, it reads as more of what still runs.
        let unnamed = plan.steps_covered_by_running_jobs(&[], only_drupal);
        assert_eq!(
            unnamed.iter().map(|step| step.index).collect::<Vec<_>>(),
            [1]
        );
    }

    /// A step whose helper is gone (a restart lost its run record) is not
    /// covered, even while its status still reads as in the background.
    #[test]
    fn a_step_whose_helper_is_gone_is_not_covered() {
        let mut plan = two_sites();
        plan.link_background_job(&[0, 1], "job-lost");
        assert!(
            plan.steps_covered_by_running_jobs(&[0], |_| false)
                .is_empty()
        );
        assert!(
            plan.steps_covered_by_running_jobs(&[], |_| false)
                .is_empty()
        );
    }

    /// A launch that names no steps is covered only when every open step
    /// already has a running helper: with one step free, it may be that one.
    #[test]
    fn an_unnamed_launch_with_a_free_step_is_not_covered() {
        let mut plan = two_sites();
        plan.link_background_job(&[0], "job-wp");
        assert!(
            plan.steps_covered_by_running_jobs(&[], |job| job == "job-wp")
                .is_empty()
        );
        // Naming the covered step is still a duplicate.
        assert_eq!(
            plan.steps_covered_by_running_jobs(&[0, 1], |job| job == "job-wp")
                .len(),
            1
        );
    }

    /// A step a launch left waiting on the turn's jobs (no `checklist_items`)
    /// is not being done by them: it waits, and a launch for it is not a
    /// duplicate (live 2026-11-14: the WordPress helper was refused because
    /// its step waited on the Drupal job).
    #[test]
    fn steps_waiting_on_unnamed_launches_are_not_covered() {
        let mut plan = two_sites();
        plan.wait_on_background_jobs(&["job-a".to_string(), "job-b".to_string()]);
        assert!(plan.steps_covered_by_running_jobs(&[], |_| true).is_empty());
        assert!(
            plan.steps_covered_by_running_jobs(&[0], |_| true)
                .is_empty()
        );
    }

    /// A step owns its runs in order and its outcome is its latest run's:
    /// a step an earlier helper failed or stopped short on is taken over by
    /// a later one for the same step, and that run's success completes it.
    #[test]
    fn a_retried_step_settles_from_its_latest_run() {
        for first_end in [JobEnd::Stopped, JobEnd::Failed] {
            let mut plan = TaskPlan::new(
                "session_123",
                "Install two sites",
                "Two sites",
                vec![
                    "Install WordPress".to_string(),
                    "Install Drupal".to_string(),
                ],
                "low",
            );
            assert!(plan.link_background_job(&[1], "job-1"));
            assert!(plan.settle_background_job("job-1", first_end));
            assert_ne!(plan.steps[1].status, StepStatus::Completed);
            assert!(plan.link_background_job(&[1], "job-2"), "{first_end:?}");
            assert_eq!(plan.steps[1].status, StepStatus::Background);
            assert_eq!(plan.steps[1].not_done, None);
            assert!(plan.settle_background_job("job-2", JobEnd::Succeeded));
            assert_eq!(plan.steps[1].status, StepStatus::Completed);
        }
    }

    #[test]
    fn test_create_plan() {
        let plan = TaskPlan::new(
            "session_123",
            "Deploy the app to production",
            "Production deployment",
            vec![
                "Run tests".to_string(),
                "Build container".to_string(),
                "Deploy".to_string(),
            ],
            "high_stakes",
        );

        assert_eq!(plan.steps.len(), 3);
        assert_eq!(plan.current_step, 0);
        assert_eq!(plan.status, PlanStatus::InProgress);
        assert_eq!(plan.steps[0].status, StepStatus::InProgress);
        assert_eq!(plan.steps[1].status, StepStatus::Pending);
        assert_eq!(plan.steps[2].status, StepStatus::Pending);
    }

    #[test]
    fn test_advance_steps() {
        let mut plan = TaskPlan::new(
            "session_123",
            "test",
            "Test task",
            vec!["Step 1".to_string(), "Step 2".to_string()],
            "test",
        );

        plan.complete_current_step(Some("Done".to_string()));
        assert_eq!(plan.steps[0].status, StepStatus::Completed);

        assert!(plan.advance_to_next_step());
        assert_eq!(plan.current_step, 1);
        assert_eq!(plan.steps[1].status, StepStatus::InProgress);

        plan.complete_current_step(None);
        assert!(!plan.advance_to_next_step());
        assert_eq!(plan.status, PlanStatus::Completed);
    }

    #[test]
    fn sync_active_step_promotes_the_next_pending_item() {
        let mut plan = TaskPlan::new(
            "session_123",
            "test",
            "Test task",
            vec!["First".to_string(), "Second".to_string()],
            "test",
        );
        plan.steps[0].status = StepStatus::Completed;
        plan.steps[1].status = StepStatus::Pending;
        plan.current_step = 0;

        plan.sync_active_step();

        assert_eq!(plan.current_step, 1);
        assert_eq!(plan.steps[1].status, StepStatus::InProgress);
    }

    #[test]
    fn dependency_graph_supports_parallel_branches_and_a_join() {
        let mut plan = TaskPlan::new(
            "session_123",
            "test",
            "Graph task",
            vec!["Left".into(), "Right".into(), "Join".into()],
            "test",
        );
        for step in &mut plan.steps {
            step.status = StepStatus::Pending;
        }
        plan.steps[0].depends_on.clear();
        plan.steps[1].depends_on.clear();
        plan.steps[2].depends_on = vec![0, 1];

        assert_eq!(plan.ready_step_indices().unwrap(), vec![0, 1]);
        plan.steps[0].status = StepStatus::Completed;
        assert_eq!(plan.ready_step_indices().unwrap(), vec![1]);
        plan.steps[1].status = StepStatus::Completed;
        assert_eq!(plan.ready_step_indices().unwrap(), vec![2]);
    }

    /// A second job a turn starts joins the steps already waiting on the
    /// first; once both ended, a step left open settles as not done and the
    /// plan resolves: nothing reads "working" with nothing working.
    #[test]
    fn open_steps_settle_once_nothing_runs() {
        let mut plan = TaskPlan::new(
            "session_123",
            "test",
            "Two installs",
            vec!["Install one".into(), "Install two".into()],
            "test",
        );
        for step in &mut plan.steps {
            step.status = StepStatus::Pending;
        }
        assert!(plan.wait_on_background_jobs(&["job-1".to_string()]));
        assert!(plan.wait_on_background_jobs(&["job-2".to_string()]));
        assert_eq!(plan.steps[0].waited_jobs, vec!["job-1", "job-2"]);
        plan.settle_background_job("job-1", JobEnd::Succeeded);
        assert_eq!(plan.steps[0].status, StepStatus::Background);
        plan.steps.push(PlanStep {
            status: StepStatus::InProgress,
            description: "Report each time".into(),
            background_jobs: Vec::new(),
            waited_jobs: Vec::new(),
            ..plan.steps[0].clone()
        });
        plan.settle_background_job("job-2", JobEnd::Succeeded);
        assert!(!plan.is_finished());
        assert!(plan.settle_open_steps());
        assert!(plan.is_finished());
        assert_eq!(plan.steps[2].not_done, Some(NotDoneReason::LeftOpen));
        assert!(
            plan.render_compact_checklist()
                .contains("nothing was left working on it")
        );
    }

    /// Live 2026-11-13: two helpers launched, one per site. The first one's
    /// end settled the card before the second was counted on it, and its
    /// step read "nothing was left working on it" while it ran. A step a
    /// launch took on waits for that launch's own end.
    #[test]
    fn a_step_a_launch_took_on_is_never_left_open() {
        let mut plan = TaskPlan::new(
            "session_123",
            "test",
            "Two screenshots",
            vec![
                "Drupal homepage screenshot".into(),
                "WordPress homepage screenshot".into(),
                "Report each time".into(),
            ],
            "test",
        );
        assert!(plan.link_background_job(&[0], "job-drupal"));
        assert!(plan.link_background_job(&[1], "job-wordpress"));
        assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
        assert!(!plan.settle_open_steps());
        assert_eq!(plan.steps[1].status, StepStatus::Background);
        assert_eq!(plan.steps[2].not_done, None);
        assert_eq!(plan.steps[1].not_done, None);
        assert!(!plan.is_finished());
        let card = plan.render_compact_checklist();
        assert!(!card.contains("Stopped short"), "{card}");
        assert!(!card.contains("nothing was left working on it"), "{card}");
        assert!(plan.settle_background_job("job-wordpress", JobEnd::Succeeded));
        assert_eq!(plan.steps[1].status, StepStatus::Completed);
    }

    #[test]
    fn dependency_graph_rejects_cycles() {
        let mut plan = TaskPlan::new(
            "session_123",
            "test",
            "Cyclic task",
            vec!["One".into(), "Two".into()],
            "test",
        );
        plan.steps[0].depends_on = vec![1];
        plan.steps[1].depends_on = vec![0];

        assert!(plan.validate_graph().unwrap_err().contains("cycle"));
    }

    #[test]
    fn test_format_for_prompt() {
        let mut plan = TaskPlan::new(
            "session_123",
            "Deploy",
            "Deploy to production",
            vec![
                "Run tests".to_string(),
                "Build".to_string(),
                "Deploy".to_string(),
            ],
            "test",
        );

        plan.complete_current_step(Some("Tests passed".to_string()));
        plan.advance_to_next_step();

        let formatted = plan.format_for_prompt();
        assert!(formatted.contains("Incomplete Task Plan"));
        assert!(formatted.contains("[x] 1. Run tests"));
        assert!(formatted.contains("[>] 2. Build"));
        assert!(formatted.contains("[ ] 3. Deploy"));
    }

    #[test]
    fn test_deferred_status_round_trip() {
        assert_eq!(StepStatus::Deferred.as_str(), "deferred");
        assert_eq!(StepStatus::from_str("deferred"), Some(StepStatus::Deferred));
    }

    #[test]
    fn test_unchecked_steps_excludes_completed_and_deferred() {
        let mut plan = TaskPlan::new(
            "s",
            "t",
            "d",
            vec!["a".into(), "b".into(), "c".into()],
            "track_requirements",
        );
        plan.steps[0].status = StepStatus::Completed;
        plan.steps[1].status = StepStatus::Deferred;
        plan.steps[2].status = StepStatus::Pending;
        let unchecked = plan.unchecked_steps();
        assert_eq!(unchecked.len(), 1);
        assert_eq!(unchecked[0].description, "c");
    }

    #[test]
    fn test_render_compact_checklist_and_recap() {
        let mut plan = TaskPlan::new(
            "s",
            "t",
            "d",
            vec!["create script".into(), "send the file".into()],
            "track_requirements",
        );
        plan.steps[0].status = StepStatus::Completed;
        plan.steps[1].status = StepStatus::InProgress;
        plan.current_step = 1;
        let checklist = plan.render_compact_checklist();
        assert_eq!(
            checklist,
            "⚙️ Working · step 2 of 2\n\n✅ create script\n\n▶️ send the file"
        );
        assert!(!is_completed_checklist(&checklist));
        assert!(checklist.contains("create script"));
        assert!(checklist.contains("send the file"));
        let recap = plan.render_recap();
        assert!(recap.contains("create script"));
        assert!(recap.contains("send the file"));
        assert!(recap.contains("not done"));
    }

    #[test]
    fn completed_plan_does_not_announce_durable_task_completion() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec!["observe result".into()],
            "track_requirements",
        );
        plan.steps[0].status = StepStatus::Completed;
        plan.status = PlanStatus::Completed;

        let checklist = plan.render_compact_checklist();
        // One step: the step itself, no header or "1 of 1".
        assert_eq!(checklist, "✅ observe result");
        assert!(is_completed_checklist(&checklist));
        assert!(!checklist.contains("Task complete"));

        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec!["first".into(), "second".into()],
            "track_requirements",
        );
        for step in &mut plan.steps {
            step.status = StepStatus::Completed;
        }
        plan.status = PlanStatus::Completed;
        let checklist = plan.render_compact_checklist();
        assert_eq!(checklist, "✅ Done · 2 of 2 steps\n\n✅ first\n\n✅ second");
        assert!(is_completed_checklist(&checklist));
        assert!(!checklist.contains("Finalizing"));
    }

    /// Steps handed to background jobs read as still being done: the card
    /// never says "stopped short" or "not done" while they run, whatever
    /// verdict the run itself recorded.
    #[test]
    fn handed_off_steps_render_as_running_in_the_background() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec![
                "inspect".into(),
                "first setup".into(),
                "second setup".into(),
                "report both".into(),
            ],
            "track_requirements",
        );
        plan.steps[0].status = StepStatus::Completed;
        assert!(plan.link_background_job(&[1, 3], "job-a"));
        assert!(plan.link_background_job(&[2, 3], "job-b"));
        // The run itself ends partial: work continues elsewhere.
        plan.status = PlanStatus::PartiallyCompleted;

        let card = plan.render_compact_checklist();
        assert_eq!(
            card,
            "⏳ Continuing in the background · 1 of 4 done\n\n✅ inspect\n\n\
             ⏳ first setup (running in the background)\n\n\
             ⏳ second setup (running in the background)\n\n\
             ⏳ report both (running in the background)"
        );
        assert!(!is_completed_checklist(&card));

        // One job done: its own step is done; the shared one waits for both.
        assert!(plan.settle_background_job("job-a", JobEnd::Succeeded));
        assert_eq!(plan.steps[1].status, StepStatus::Completed);
        assert_eq!(plan.steps[3].status, StepStatus::Background);
        assert!(
            plan.render_compact_checklist()
                .starts_with("⏳ Continuing in the background · 2 of 4 done")
        );

        // The other fails: its step and the shared one failed, never done.
        assert!(plan.settle_background_job("job-b", JobEnd::Failed));
        assert_eq!(plan.steps[2].status, StepStatus::Failed);
        assert_eq!(plan.steps[3].status, StepStatus::Failed);
        assert_eq!(plan.status, PlanStatus::Failed);
        assert!(
            plan.render_compact_checklist()
                .starts_with("❌ Stopped · 2 of 4 done")
        );
        // A job nothing waits on changes nothing.
        assert!(!plan.settle_background_job("job-c", JobEnd::Succeeded));
    }

    /// A turn that hands work to background jobs without linking its open
    /// steps never reads "stopped short" or "not done" while they run, and
    /// once every job succeeded the steps waiting on them are done.
    #[test]
    fn open_steps_wait_on_the_turns_background_jobs_and_settle_from_their_ends() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec![
                "check tools".into(),
                "install site a".into(),
                "install site b".into(),
            ],
            "track_requirements",
        );
        plan.steps[0].status = StepStatus::Completed;
        plan.steps[1].status = StepStatus::Deferred;
        plan.steps[2].status = StepStatus::Deferred;
        plan.status = PlanStatus::PartiallyCompleted;
        assert!(
            plan.render_compact_checklist()
                .starts_with("⚠️ Stopped short")
        );

        let jobs = vec!["job-a".to_string(), "job-b".to_string()];
        assert!(plan.wait_on_background_jobs(&jobs));
        let card = plan.render_compact_checklist();
        assert!(
            card.starts_with("⏳ Continuing in the background · 1 of 3 done"),
            "{card}"
        );
        assert!(
            !card.contains("Stopped short") && !card.contains("not done"),
            "{card}"
        );

        assert!(plan.settle_background_job("job-a", JobEnd::Succeeded));
        assert!(
            plan.render_compact_checklist()
                .starts_with("⏳ Continuing in the background")
        );
        assert!(plan.settle_background_job("job-b", JobEnd::Succeeded));
        assert_eq!(plan.steps[1].status, StepStatus::Completed);
        assert_eq!(plan.steps[2].status, StepStatus::Completed);
        assert_eq!(plan.status, PlanStatus::Completed);
        let card = plan.render_compact_checklist();
        assert!(!card.contains("not done"), "{card}");
        assert!(is_completed_checklist(&card), "{card}");
    }

    /// A step waiting on runs settles once the last of them ended: not
    /// done, with the plain reason, when one of them failed, even though
    /// another succeeded.
    #[test]
    fn a_step_waiting_on_a_failed_run_is_not_done_with_the_reason() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec!["wait for the build".into()],
            "track_requirements",
        );
        let jobs = vec!["job-a".to_string(), "job-b".to_string()];
        assert!(plan.wait_on_background_jobs(&jobs));
        assert!(plan.settle_background_job("job-a", JobEnd::Failed));
        assert_eq!(plan.steps[0].status, StepStatus::Background);
        assert!(!plan.is_finished());
        assert!(plan.settle_background_job("job-b", JobEnd::Succeeded));
        assert_eq!(plan.steps[0].status, StepStatus::Deferred);
        assert_eq!(plan.steps[0].not_done, Some(NotDoneReason::WaitedOnFailed));
        assert!(plan.is_finished());
        let card = plan.render_compact_checklist();
        assert!(
            card.contains("wait for the build (not done: the work it waited on failed)"),
            "{card}"
        );
    }

    /// Live 2026-11-13: the owner declined the WordPress helper's password
    /// rotation; it ended short while the Drupal helper still ran, and the
    /// card read "Not done: its helper stopped before it finished · 1 of 5
    /// done" above its helpers' finished lines. A step both helpers shared
    /// waits for both; the WordPress step reads why it was not done; the
    /// header's count is the rows' count.
    #[test]
    fn a_declined_helper_reads_as_declined_and_shared_steps_wait_for_every_run() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec![
                "Install Drupal".into(),
                "Install WordPress".into(),
                "Screenshot both homepages".into(),
            ],
            "track_requirements",
        );
        assert!(plan.link_background_job(&[0, 2], "job-drupal"));
        assert!(plan.link_background_job(&[1, 2], "job-wordpress"));
        assert!(plan.settle_background_job("job-wordpress", JobEnd::Declined));
        assert_eq!(plan.steps[1].not_done, Some(NotDoneReason::OwnerDeclined));
        assert_eq!(plan.steps[2].status, StepStatus::Background);
        assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
        assert_eq!(plan.steps[0].status, StepStatus::Completed);
        assert_eq!(plan.steps[2].status, StepStatus::Deferred);
        assert_eq!(plan.steps[2].not_done, Some(NotDoneReason::OwnerDeclined));
        let card = plan.render_compact_checklist();
        assert!(
            card.starts_with(
                "⏭️ Not done: you declined a step its helper asked to take · 1 of 3 done"
            ),
            "{card}"
        );
        let done_rows = card.lines().filter(|line| line.starts_with('✅')).count();
        assert_eq!(done_rows, plan.card().done, "{card}");
    }

    /// Live 2026-11-14: the Drupal step read claude-drupal-12, but its
    /// helper made claude-company-drupal-5879. The folder a job's claim
    /// evidence recorded goes on the steps it took on, and the card names
    /// it when the step's words don't; a step that already names it reads
    /// as before, and a step the job never took on gets nothing.
    #[test]
    fn a_step_names_the_folder_its_run_really_made() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec![
                "Install Drupal in claude-drupal-12".into(),
                "Install WordPress in claude-wordpress-1".into(),
            ],
            "track_requirements",
        );
        assert!(plan.link_background_job(&[0], "job-drupal"));
        assert!(plan.link_background_job(&[1], "job-wordpress"));
        assert!(plan.note_job_folders(
            "job-drupal",
            &["/Users/x/projects/claude-company-drupal-5879".to_string()]
        ));
        assert!(plan.note_job_folders(
            "job-wordpress",
            &["/Users/x/projects/claude-wordpress-1".to_string()]
        ));
        assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
        assert!(plan.settle_background_job("job-wordpress", JobEnd::Succeeded));
        let card = plan.render_compact_checklist();
        assert!(
            card.contains(
                "✅ Install Drupal in claude-drupal-12 (made claude-company-drupal-5879)"
            ),
            "{card}"
        );
        assert!(
            card.contains("✅ Install WordPress in claude-wordpress-1\n")
                || card.ends_with("✅ Install WordPress in claude-wordpress-1"),
            "{card}"
        );
    }

    /// Live 2026-11-13: one helper launched for the Drupal step; the
    /// WordPress step was never taken on. The card says so with its typed
    /// reason, and the running helper still settles its own step.
    #[test]
    fn a_step_nothing_took_on_reads_not_attempted() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec!["Install Drupal".into(), "Install WordPress".into()],
            "track_requirements",
        );
        plan.link_background_job(&[0], "job-a");
        assert!(plan.mark_not_attempted(&std::collections::BTreeSet::from([1])));
        assert_eq!(plan.steps[1].not_done, Some(NotDoneReason::NotAttempted));
        assert_eq!(plan.steps[0].status, StepStatus::Background);
        let card = plan.render_compact_checklist();
        assert!(
            card.contains("Install WordPress (not done: not attempted)"),
            "{card}"
        );
        assert!(plan.settle_background_job("job-a", JobEnd::Succeeded));
        assert_eq!(plan.steps[0].status, StepStatus::Completed);
        assert_eq!(plan.steps[1].not_done, Some(NotDoneReason::NotAttempted));
    }

    #[test]
    fn background_steps_that_all_finish_complete_the_plan() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec!["first".into(), "second".into()],
            "track_requirements",
        );
        plan.link_background_job(&[0, 1], "job-a");
        plan.status = PlanStatus::PartiallyCompleted;
        assert!(plan.settle_background_job("job-a", JobEnd::Succeeded));
        assert_eq!(plan.status, PlanStatus::Completed);
        assert!(is_completed_checklist(&plan.render_compact_checklist()));
    }

    #[test]
    fn deferred_steps_resolve_to_partial_plan_with_visible_blocker_requirement() {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec!["first action".into(), "second action".into()],
            "track_requirements",
        );
        for step in &mut plan.steps {
            step.status = StepStatus::Deferred;
        }
        plan.sync_active_step();

        assert_eq!(plan.status, PlanStatus::PartiallyCompleted);
        let checklist = plan.render_compact_checklist();
        assert!(checklist.starts_with("⚠️ Stopped short · 0 of 2 done"));
        assert!(checklist.contains("⏭️ first action (not done)"));
        assert!(
            !checklist.contains("deferred"),
            "no internal status word: {checklist}"
        );
        assert!(!is_completed_checklist(&checklist));
        assert!(checklist.contains("what was left undone and why"));
        // The footer speaks to the user; it is not an instruction to the model.
        assert!(!checklist.contains("must"));
    }

    #[test]
    fn test_plan_status_is_incomplete() {
        assert!(PlanStatus::Planning.is_incomplete());
        assert!(PlanStatus::InProgress.is_incomplete());
        assert!(PlanStatus::Paused.is_incomplete());
        assert!(!PlanStatus::Completed.is_incomplete());
        assert!(!PlanStatus::PartiallyCompleted.is_incomplete());
        assert!(!PlanStatus::Failed.is_incomplete());
        assert!(!PlanStatus::Abandoned.is_incomplete());
    }

    fn parallel_installs() -> TaskPlan {
        let mut plan = TaskPlan::new(
            "synthetic-session",
            "synthetic-task",
            "description",
            vec![
                "install the drupal site".into(),
                "install the wordpress site".into(),
                "report both".into(),
            ],
            "track_requirements",
        );
        // The model marked both installs handed off before either launch.
        plan.steps[0].status = StepStatus::Background;
        plan.steps[1].status = StepStatus::Background;
        plan
    }

    /// Live 2026-11-14: two parallel helpers, Drupal and WordPress. The
    /// Drupal launch named only its own step, yet the WordPress step, left
    /// waiting on the turn's launches, counted as already being done by the
    /// Drupal job and the WordPress launch was refused. Waiting on a run is
    /// not being done by it.
    #[test]
    fn a_second_parallel_launch_is_accepted_when_the_first_named_only_its_own_step() {
        let mut plan = parallel_installs();
        assert!(plan.link_background_job(&[0], "job-drupal"));
        // The checklist is posted again while Drupal runs: the open steps
        // wait on the turn's launch.
        plan.wait_on_background_jobs(&["job-drupal".to_string()]);
        let running = |_: &str| true;
        assert!(
            plan.steps_covered_by_running_jobs(&[1], running).is_empty(),
            "the WordPress step only waits on Drupal: {:?}",
            plan.steps[1]
        );
        assert_eq!(
            plan.steps_covered_by_running_jobs(&[0], running)
                .iter()
                .map(|covered| covered.index)
                .collect::<Vec<_>>(),
            vec![0],
            "Drupal's own step is still guarded"
        );
        assert!(plan.link_background_job(&[1], "job-wordpress"));
        // Drupal's end settles only its own step; WordPress's is its run's.
        assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
        assert_eq!(plan.steps[0].status, StepStatus::Completed);
        assert_eq!(plan.steps[1].status, StepStatus::Background);
        assert!(plan.settle_background_job("job-wordpress", JobEnd::Failed));
        assert_eq!(plan.steps[1].status, StepStatus::Failed);
    }

    /// A step that only waits on a running job never blocks a launch, named
    /// or not.
    #[test]
    fn a_step_that_only_waits_never_blocks_a_launch() {
        let mut plan = parallel_installs();
        plan.steps[0].status = StepStatus::Pending;
        plan.steps[1].status = StepStatus::Pending;
        plan.wait_on_background_jobs(&["job-first".to_string()]);
        let running = |_: &str| true;
        assert!(plan.steps_covered_by_running_jobs(&[], running).is_empty());
        assert!(plan.steps_covered_by_running_jobs(&[1], running).is_empty());
    }

    /// The WordPress step's own helper never started while it waited on
    /// Drupal's: Drupal's success does not make it done, and the header
    /// counts it as not done (live 2026-11-14: "Done · 4 of 4 steps").
    #[test]
    fn a_waiting_step_whose_own_helper_never_started_is_not_done() {
        let mut plan = parallel_installs();
        assert!(plan.link_background_job(&[0], "job-drupal"));
        plan.wait_on_background_jobs(&["job-drupal".to_string()]);
        assert!(plan.helper_did_not_start(&[1], "the launch was refused"));
        assert!(plan.settle_background_job("job-drupal", JobEnd::Succeeded));
        assert_eq!(plan.steps[0].status, StepStatus::Completed);
        assert_ne!(plan.steps[1].status, StepStatus::Completed);
        let card = plan.render_compact_checklist();
        assert!(!card.contains("Done ·"), "{card}");
        assert!(!card.contains("3 of 3"), "{card}");
        assert!(card.contains("didn't run"), "{card}");
        assert!(!card.contains("running in the background"), "{card}");
    }
}