yardlet 0.8.0

Yardlet: a local AI workbench. Plan, queue, route, validate, and hand off long-running work using your already-installed Codex and Claude Code CLIs as hidden workers.
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
//! Planning gate.
//!
//! Turns a short natural-language request into canonical state: a worker writes
//! a structured `planning-result.json`, and Yardlet derives the
//! `intent-contract.yaml` + `work-queue.yaml` from it. Yardlet owns the canonical
//! files; the worker only authors plan content.

use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use chrono::Local;
use serde::Deserialize;

use crate::guard::{self, Readiness};
use crate::inspect;
use crate::schemas::{
    IntentContract, SelectionPolicy, Task, TaskState, WorkQueue, WorkerProfile, WorkersFile,
};
use crate::state::{self, write_str, Workspace};
use crate::{packet, workers, yaml};

// ---- worker-authored plan shape -------------------------------------------

#[derive(Debug, Default, Deserialize)]
struct PlanningResult {
    #[serde(default)]
    summary: String,
    #[serde(default)]
    allowed_scope: Vec<String>,
    #[serde(default)]
    out_of_scope: Vec<String>,
    #[serde(default)]
    acceptance: Vec<PlanAcceptance>,
    #[serde(default)]
    ambiguity: PlanAmbiguity,
    #[serde(default)]
    tasks: Vec<PlanTask>,
    #[serde(default)]
    questions_for_user: Vec<PlanQuestion>,
}

#[derive(Debug, Default, Deserialize)]
struct PlanAmbiguity {
    #[serde(default)]
    score: String,
    #[serde(default)]
    open_questions: Vec<String>,
}

#[derive(Debug, Default, Deserialize)]
struct PlanAcceptance {
    #[serde(default)]
    statement: String,
}

#[derive(Debug, Default, Deserialize)]
struct PlanTask {
    #[serde(default)]
    id: String,
    #[serde(default)]
    title: String,
    #[serde(default)]
    kind: String,
    #[serde(default)]
    risk: String,
    #[serde(default)]
    preferred_worker: String,
    #[serde(default)]
    model: String,
    #[serde(default)]
    effort: String,
    #[serde(default)]
    depends_on: Vec<String>,
    #[serde(default)]
    skills: Vec<String>,
    #[serde(default)]
    required_capabilities: Vec<String>,
    #[serde(default)]
    allowed_scope: Vec<String>,
    #[serde(default)]
    acceptance: Vec<String>,
    #[serde(default)]
    worker_rationale: Option<String>,
}

/// Keep only dependencies on tasks that come earlier (`prior_ids`). This drops
/// self-references, forward references, and cycles in one rule: a task may only
/// depend on work already planned before it.
fn sanitize_deps(depends_on: &[String], prior_ids: &[String]) -> Vec<String> {
    depends_on
        .iter()
        .filter(|d| prior_ids.iter().any(|p| p == *d))
        .cloned()
        .collect()
}

/// A worker may emit `questions_for_user` either as plain strings or as objects
/// (e.g. `{ "id": ..., "question": ..., "topic": ... }`) when it mirrors the
/// object style of the `acceptance` hint. Accept both shapes and keep only the
/// human-readable text — Yardlet surfaces just the question string.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum PlanQuestion {
    Text(String),
    Obj {
        #[serde(default)]
        question: String,
        #[serde(default)]
        statement: String,
    },
}

impl PlanQuestion {
    fn into_text(self) -> String {
        match self {
            PlanQuestion::Text(s) => s,
            PlanQuestion::Obj {
                question,
                statement,
            } => {
                if !question.trim().is_empty() {
                    question
                } else {
                    statement
                }
            }
        }
    }
}

// ---- plan-run metadata (crash recovery) ------------------------------------

/// Written when a plan run starts, so an interrupted session can still consume
/// the worker's result on the next startup.
#[derive(Debug, Default, serde::Serialize, Deserialize)]
struct PlanMeta {
    mode: String, // "new" | "amend"
    #[serde(default)]
    request: String,
}

/// Marker file written into a plan run dir once Yardlet has derived the canonical
/// intent/queue from its result. Absent + result present = unconsumed.
const CONSUMED_MARKER: &str = "consumed";

fn mark_consumed(run_dir: &std::path::Path) {
    let _ = write_str(&run_dir.join(CONSUMED_MARKER), "");
}

/// Reconstruct plan metadata for run dirs created before plan-meta.yaml
/// existed: the compiled packet carries the verbatim request, and follow-up
/// (amend) packets embed a recognizable FOLLOW-UP preamble.
fn legacy_plan_meta(run_dir: &std::path::Path) -> Option<PlanMeta> {
    let packet = std::fs::read_to_string(workers::packet_path(run_dir)).ok()?;
    let request = packet
        .split("## Request (verbatim)")
        .nth(1)?
        .split("\n## ")
        .next()
        .unwrap_or("")
        .trim()
        .to_string();
    let mode = if request.contains("This is a FOLLOW-UP") {
        "amend"
    } else {
        "new"
    };
    Some(PlanMeta {
        mode: mode.to_string(),
        request,
    })
}

// ---- report ---------------------------------------------------------------

pub struct PlanningReport {
    pub run_id: String,
    pub worker_id: String,
    pub intent_summary: String,
    pub task_count: usize,
    pub questions: Vec<String>,
    pub lines: Vec<String>,
}

/// Express lane (P2): skip the planning worker entirely and lay down a tiny
/// deterministic queue for a single goal. Builds task T1 (do the goal) and,
/// when a verify condition is given, a separate T2 (a reviewer that checks the
/// condition against the workspace — the verifier is never the doer). No
/// ambiguity gate (you accepted the goal by typing it). Returns the queue size.
pub fn plan_goal(
    ws: &Workspace,
    goal: &str,
    verify: Option<&str>,
    worker_override: Option<&str>,
    required_capabilities: &[String],
) -> Result<usize> {
    let goal = goal.trim();
    if goal.is_empty() {
        bail!("describe the goal, e.g. `yardlet goal \"fix the login redirect\"`");
    }
    let intent_id = format!("intent-{}", Local::now().format("%Y%m%d-%H%M%S"));
    let worker = worker_override.unwrap_or("").to_string();

    let mut tasks = vec![Task {
        id: "YARD-001".to_string(),
        title: goal.chars().take(80).collect(),
        state: TaskState::Queued,
        priority: 10,
        risk: "low".to_string(),
        kind: "implementation".to_string(),
        preferred_worker: worker.clone(),
        model: String::new(),
        effort: String::new(),
        depends_on: vec![],
        skills: vec![],
        required_capabilities: required_capabilities.to_vec(),
        allowed_scope: vec![],
        acceptance: vec![yaml::Value::String(goal.to_string())],
        validation: None,
        approval: None,
        interaction: None,
        worker_rationale: Some("express goal (yardlet goal)".to_string()),
        provenance: String::new(),
    }];
    // Express goals bypass the planner, so capability routing is explicit (no
    // magic keywords): pass `--requires <capability>` for a hard route, or
    // `--worker` to force a specific worker.

    if let Some(v) = verify.map(str::trim).filter(|v| !v.is_empty()) {
        // A separate reviewer task: a fresh pair of eyes, not the worker that
        // did the work. For visual goals this picks up the ui-review /
        // browser-evidence skills and must cite screenshot evidence.
        tasks.push(Task {
            id: "YARD-002".to_string(),
            title: "Verify the goal".to_string(),
            state: TaskState::Queued,
            priority: 20,
            risk: "low".to_string(),
            kind: "review".to_string(),
            preferred_worker: String::new(),
            model: String::new(),
            effort: String::new(),
            depends_on: vec!["YARD-001".to_string()],
            skills: vec![],
            required_capabilities: vec![],
            allowed_scope: vec![],
            acceptance: vec![yaml::Value::String(format!(
                "Verify against the actual workspace, with evidence: {v}"
            ))],
            validation: None,
            approval: None,
            interaction: None,
            worker_rationale: Some("verifier is never the doer".to_string()),
            provenance: String::new(),
        });
    }

    let intent = IntentContract {
        schema_version: 1,
        id: intent_id.clone(),
        source: "user".to_string(),
        raw_request: goal.to_string(),
        summary: goal.to_string(),
        allowed_scope: vec![],
        out_of_scope: vec![],
        acceptance: verify
            .map(str::trim)
            .filter(|v| !v.is_empty())
            .map(|v| vec![yaml::Value::String(v.to_string())])
            .unwrap_or_default(),
        images: vec![],
        ambiguity: "low".to_string(),
        open_questions: vec![],
        clarifications: vec![],
        interview_turns: 0,
        status: "accepted".to_string(),
    };
    let queue = WorkQueue {
        schema_version: 1,
        queue_id: format!("queue-{intent_id}"),
        intent_id,
        selection_policy: SelectionPolicy::default(),
        tasks,
    };
    let task_count = queue.tasks.len();
    let _ = crate::report::archive_intent(ws);
    state::save_yaml(&ws.intent_path(), &intent)?;
    ws.save_queue(&queue)?;
    let _ = crate::skills::auto_equip(ws, &inspect::summarize(&ws.root));
    Ok(task_count)
}

/// Run the planning gate for a natural-language request.
pub fn run_planning(
    ws: &Workspace,
    request: &str,
    worker_override: Option<&str>,
    explicit_images: &[String],
) -> Result<PlanningReport> {
    let workers = ws.load_workers()?;
    let billing = ws.load_billing()?;
    let config = ws.load_config()?;

    // Images: explicit --image plus any path detected in the request.
    let mut images: Vec<String> = explicit_images.to_vec();
    for d in packet::detect_images(request, &ws.root) {
        if !images.contains(&d) {
            images.push(d);
        }
    }

    plan_core(
        ws,
        &workers,
        &billing,
        &config,
        request,
        request,
        &images,
        worker_override,
        "new",
        true,
    )
}

/// Hard cap on interview turns; past it the gate opens (proceed on
/// recorded assumptions).
pub const INTERVIEW_CAP: u32 = 10;

/// Is this intent still gated on the planner's own ambiguity self-report?
pub fn intent_gated(intent: &IntentContract, gate_enabled: bool) -> bool {
    gate_enabled
        && intent.ambiguity == "high"
        && intent.interview_turns < INTERVIEW_CAP
        && !intent.open_questions.is_empty()
}

/// One interview turn (absorption.md A2): feed the user's answer back to the
/// planning worker and derive a REVISED plan in place — same intent id, no
/// archive (this is the same intent being refined before any work starts).
/// The new plan re-scores ambiguity; the gate opens when it drops below
/// "high", the user overrides, or `INTERVIEW_CAP` turns have run.
pub fn run_planning_interview(ws: &Workspace, answer: &str) -> Result<PlanningReport> {
    let Some(prev) = ws.load_intent()? else {
        bail!("no intent to interview \u{2014} plan first (n)");
    };
    let queue = ws.load_queue()?;
    let workers = ws.load_workers()?;
    let billing = ws.load_billing()?;
    let config = ws.load_config()?;

    let turns = prev.interview_turns + 1;
    let mut clarifications = prev.clarifications.clone();
    clarifications.push(format!(
        "Q: {}\nA: {}",
        prev.open_questions.join(" / "),
        answer.trim()
    ));

    let mut ctx = String::new();
    ctx.push_str(&format!("Original request:\n{}\n\n", prev.raw_request));
    ctx.push_str(&format!("Current plan summary: {}\n", prev.summary));
    if !queue.tasks.is_empty() {
        ctx.push_str("Current planned tasks (revise them freely):\n");
        for t in &queue.tasks {
            ctx.push_str(&format!("- {} {}\n", t.id, t.title));
        }
    }
    ctx.push_str("\nInterview so far:\n");
    for c in &clarifications {
        ctx.push_str(c);
        ctx.push_str("\n---\n");
    }
    ctx.push_str(&format!(
        "\nThis is interview turn {turns}/{cap}. RE-PLAN the whole intent with these \
         answers folded in: revise the summary, scope, acceptance, and tasks as needed. \
         Re-score `ambiguity` honestly \u{2014} drop it below \"high\" only when you are no \
         longer guessing about product behavior or architecture. If something essential \
         is still unclear, ask up to 3 NEW questions (never repeat an answered one).",
        cap = INTERVIEW_CAP
    ));

    let report = plan_core(
        ws,
        &workers,
        &billing,
        &config,
        &ctx,
        &prev.raw_request,
        &prev.images,
        None,
        "interview",
        false,
    )?;

    // plan_core derived a fresh intent; restore identity + interview bookkeeping.
    if let Some(mut intent) = ws.load_intent()? {
        intent.id = prev.id.clone();
        intent.raw_request = prev.raw_request.clone();
        intent.clarifications = clarifications;
        intent.interview_turns = turns;
        state::save_yaml(&ws.intent_path(), &intent)?;
        let mut q = ws.load_queue()?;
        q.intent_id = prev.id.clone();
        q.queue_id = format!("queue-{}", prev.id);
        ws.save_queue(&q)?;
    }
    Ok(report)
}

/// The planning machinery shared by fresh plans and interview re-plans.
/// `packet_request` goes to the worker; `store_request` is recorded as the
/// intent's raw request; `archive` controls whether the previous intent is
/// archived first (interview refines in place).
#[allow(clippy::too_many_arguments)]
fn plan_core(
    ws: &Workspace,
    workers: &WorkersFile,
    billing: &crate::schemas::BillingPolicy,
    config: &crate::schemas::YardConfig,
    packet_request: &str,
    store_request: &str,
    images: &[String],
    worker_override: Option<&str>,
    mode: &str,
    archive: bool,
) -> Result<PlanningReport> {
    let language = packet::resolve_language(&config.language, store_request);

    // Choose a ready planning worker.
    let (profile, bin, worker_id) = pick_ready_worker(workers, billing, worker_override)?;

    let run_id = format!("plan-{}", Local::now().format("%Y%m%d-%H%M%S"));
    let run_dir = ws.runs_dir().join(&run_id);
    std::fs::create_dir_all(run_dir.join("evidence"))?;
    let run_dir_rel = format!(".agents/runs/{run_id}");
    state::save_yaml(
        &run_dir.join("plan-meta.yaml"),
        &PlanMeta {
            mode: mode.to_string(),
            request: store_request.to_string(),
        },
    )?;

    let mut lines = Vec::new();

    // Evidence + packet.
    let summary = inspect::summarize(&ws.root);
    write_str(
        &run_dir.join("evidence").join("repo-summary.md"),
        &inspect::to_markdown(&summary),
    )?;
    // Auto-equip skills for this repo's detected presets before compiling the
    // packet, so the catalog the planner sees already includes them (S1).
    let equipped = crate::skills::auto_equip(ws, &summary);
    if !equipped.is_empty() {
        lines.push(format!("equipped skills: {}", equipped.join(", ")));
    }
    let pruned = crate::skills::auto_prune(ws);
    if !pruned.is_empty() {
        lines.push(format!("pruned weak skills: {}", pruned.join(", ")));
    }
    let worker_guidance = build_worker_guidance(workers);
    let harness = packet::discover_harness(&ws.root, config.harness_discovery);
    let packet_text = packet::compile_planning(
        packet_request,
        &summary,
        &run_dir_rel,
        &language,
        &worker_guidance,
        images,
        &harness,
        &worker_id,
    );
    write_str(&workers::packet_path(&run_dir), &packet_text)?;

    // For a fresh plan, archive the previous intent and CLEAR the queue now,
    // before the worker runs — otherwise the Home screen shows the old queue
    // for the whole planning run, which reads as stale. (Interview/amend keep
    // the live queue; they refine it in place.)
    if archive {
        let _ = crate::report::archive_intent(ws);
        let _ = ws.save_queue(&WorkQueue {
            schema_version: 1,
            queue_id: "planning".to_string(),
            intent_id: String::new(),
            selection_policy: SelectionPolicy::default(),
            tasks: Vec::new(),
        });
    }

    // Invoke the worker with a sanitized environment.
    let env = guard::sanitized_worker_env_for(billing, &profile.invocation.pass_env)
        .map_err(|e| anyhow!(e))?;
    let timeout = Duration::from_secs(profile.limits.max_wall_minutes as u64 * 60);
    let outcome = workers::spawn(
        &profile,
        &bin,
        &packet_text,
        &ws.root,
        &env,
        &run_dir.join("worker-output.log"),
        timeout,
        false, // planning never needs elevated access
        images,
        None,
        false,
    )?;
    lines.push(format!("worker outcome: {}", outcome.note));

    // Read the worker-authored plan.
    let result_path = run_dir.join("planning-result.json");
    let raw = std::fs::read_to_string(&result_path).with_context(|| {
        format!(
            "planning worker did not write {}. Inspect {}/worker-output.log",
            result_path.display(),
            run_dir_rel
        )
    })?;
    let plan: PlanningResult =
        serde_json::from_str(&raw).with_context(|| format!("parsing {}", result_path.display()))?;

    if plan.summary.trim().is_empty() || plan.tasks.is_empty() {
        bail!(
            "planning produced no usable plan (empty summary or no tasks). See {}",
            result_path.display()
        );
    }

    // Derive canonical state. Yardlet owns these files.
    let intent_id = format!("intent-{}", Local::now().format("%Y%m%d-%H%M%S"));
    let intent = build_intent(&intent_id, store_request, &plan, images);
    let mut queue = build_queue(&intent_id, &plan);
    // Ground capabilities against the real workers at creation: a task needing a
    // capability no worker has is parked now, not crashed into at run time.
    let parked = reconcile_queue_capabilities(&mut queue, workers);
    if !parked.is_empty() {
        lines.push(format!(
            "parked (no worker for required capability): {}",
            parked.join(", ")
        ));
    }

    // (Fresh plans already archived + cleared the prior queue before the
    // worker ran; here we just write the new canonical state.)
    state::save_yaml(&ws.intent_path(), &intent)?;
    ws.save_queue(&queue)?;
    mark_consumed(&run_dir);

    Ok(PlanningReport {
        run_id,
        worker_id,
        intent_summary: intent.summary,
        task_count: queue.tasks.len(),
        questions: plan
            .questions_for_user
            .into_iter()
            .map(PlanQuestion::into_text)
            .filter(|q| !q.trim().is_empty())
            .collect(),
        lines,
    })
}

/// Amend the current intent with follow-up tasks: keep the existing (done) work
/// and append new tasks derived from the user's continue request + the existing
/// context. Does not overwrite or archive — it extends the live queue.
pub fn run_planning_amend(ws: &Workspace, request: &str) -> Result<PlanningReport> {
    let existing_intent = ws.load_intent()?;
    let existing_queue = ws.load_queue()?;

    // Give the planner the existing context and ask for new tasks only.
    let mut ctx = String::new();
    if let Some(i) = &existing_intent {
        ctx.push_str(&format!(
            "This is a FOLLOW-UP to an existing intent.\nCurrent goal: {}\n\n",
            i.summary
        ));
    }
    if !existing_queue.tasks.is_empty() {
        ctx.push_str("Already-planned tasks (do NOT recreate these):\n");
        for t in &existing_queue.tasks {
            ctx.push_str(&format!("- {} [{:?}] {}\n", t.id, t.state, t.title));
        }
        ctx.push('\n');
    }
    ctx.push_str(&format!(
        "Follow-up request from the user:\n{request}\n\nProduce ONLY new tasks that add \
         to this work; do not redo the tasks above."
    ));

    // Invoke the planner worker (same machinery as run_planning).
    let workers = ws.load_workers()?;
    let billing = ws.load_billing()?;
    let config = ws.load_config()?;
    let language = packet::resolve_language(&config.language, &ctx);
    let images: Vec<String> = Vec::new();
    let (profile, bin, worker_id) = pick_ready_worker(&workers, &billing, None)?;
    let run_id = format!("plan-{}", Local::now().format("%Y%m%d-%H%M%S"));
    let run_dir = ws.runs_dir().join(&run_id);
    std::fs::create_dir_all(run_dir.join("evidence"))?;
    let run_dir_rel = format!(".agents/runs/{run_id}");
    state::save_yaml(
        &run_dir.join("plan-meta.yaml"),
        &PlanMeta {
            mode: "amend".to_string(),
            request: request.to_string(),
        },
    )?;
    let mut lines = Vec::new();
    let summary = inspect::summarize(&ws.root);
    write_str(
        &run_dir.join("evidence").join("repo-summary.md"),
        &inspect::to_markdown(&summary),
    )?;
    let worker_guidance = build_worker_guidance(&workers);
    let harness = packet::discover_harness(&ws.root, config.harness_discovery);
    let packet_text = packet::compile_planning(
        &ctx,
        &summary,
        &run_dir_rel,
        &language,
        &worker_guidance,
        &images,
        &harness,
        &worker_id,
    );
    write_str(&workers::packet_path(&run_dir), &packet_text)?;
    let env = guard::sanitized_worker_env_for(&billing, &profile.invocation.pass_env)
        .map_err(|e| anyhow!(e))?;
    let timeout = Duration::from_secs(profile.limits.max_wall_minutes as u64 * 60);
    let outcome = workers::spawn(
        &profile,
        &bin,
        &packet_text,
        &ws.root,
        &env,
        &run_dir.join("worker-output.log"),
        timeout,
        false,
        &images,
        None,
        false,
    )?;
    lines.push(format!("worker outcome: {}", outcome.note));
    let result_path = run_dir.join("planning-result.json");
    let raw = std::fs::read_to_string(&result_path).with_context(|| {
        format!(
            "planning worker did not write {}. Inspect {}/worker-output.log",
            result_path.display(),
            run_dir_rel
        )
    })?;
    let plan: PlanningResult =
        serde_json::from_str(&raw).with_context(|| format!("parsing {}", result_path.display()))?;
    if plan.tasks.is_empty() {
        bail!("amend produced no new tasks. See {}", result_path.display());
    }

    // Merge: append the new tasks to the existing queue (continue the numbering).
    let mut queue = existing_queue;
    let added = append_plan_tasks(&mut queue, &plan);
    // Ground capabilities against the real workers at creation (see run_planning).
    let parked = reconcile_queue_capabilities(&mut queue, &workers);
    if !parked.is_empty() {
        lines.push(format!(
            "parked (no worker for required capability): {}",
            parked.join(", ")
        ));
    }
    ws.save_queue(&queue)?;

    // Note the follow-up in the intent summary (keep the same intent).
    if let Some(mut intent) = existing_intent {
        if !plan.summary.trim().is_empty() {
            intent.summary = format!("{}\n\n[follow-up] {}", intent.summary, plan.summary.trim());
            state::save_yaml(&ws.intent_path(), &intent)?;
        }
    }
    mark_consumed(&run_dir);

    Ok(PlanningReport {
        run_id,
        worker_id,
        intent_summary: format!("+{added} task(s)"),
        task_count: queue.tasks.len(),
        questions: plan
            .questions_for_user
            .into_iter()
            .map(PlanQuestion::into_text)
            .filter(|q| !q.trim().is_empty())
            .collect(),
        lines,
    })
}

/// Append a plan's tasks to an existing queue (follow-up/amend semantics):
/// continue the YARD-nnn numbering and stack priorities after existing tasks.
/// Returns how many tasks were added.
fn append_plan_tasks(queue: &mut WorkQueue, plan: &PlanningResult) -> usize {
    let next_num = queue
        .tasks
        .iter()
        .filter_map(|t| {
            t.id.strip_prefix("YARD-")
                .and_then(|n| n.parse::<usize>().ok())
        })
        .max()
        .unwrap_or(queue.tasks.len())
        + 1;
    let base_priority = queue.tasks.iter().map(|t| t.priority).max().unwrap_or(0);
    for (i, pt) in plan.tasks.iter().enumerate() {
        let id = if pt.id.trim().is_empty() {
            format!("YARD-{:03}", next_num + i)
        } else {
            pt.id.clone()
        };
        // Follow-up tasks may depend on existing queue tasks or earlier new ones.
        let prior_ids: Vec<String> = queue.tasks.iter().map(|t| t.id.clone()).collect();
        let task = Task {
            id,
            title: pt.title.clone(),
            state: TaskState::Queued,
            priority: base_priority + ((i + 1) * 10) as i64,
            risk: pt.risk.clone(),
            kind: pt.kind.clone(),
            // Blank stays blank so routing's configured default_worker applies
            // (precedence: planner preferred -> learned rule -> default).
            preferred_worker: pt.preferred_worker.clone(),
            model: pt.model.clone(),
            effort: pt.effort.clone(),
            depends_on: sanitize_deps(&pt.depends_on, &prior_ids),
            skills: pt.skills.clone(),
            required_capabilities: pt.required_capabilities.clone(),
            allowed_scope: pt.allowed_scope.clone(),
            acceptance: pt
                .acceptance
                .iter()
                .map(|s| yaml::Value::String(s.clone()))
                .collect(),
            validation: None,
            approval: None,
            interaction: None,
            worker_rationale: pt.worker_rationale.clone(),
            provenance: String::new(),
        };
        queue.tasks.push(task);
    }
    plan.tasks.len()
}

/// Ground every Queued task's `required_capabilities` against the workers that
/// actually exist: normalize the strings and, when a task requires a capability
/// no enabled worker declares, PARK it (Queued -> Blocked) with a note — at
/// queue-creation time, not at run time. Capabilities are free-form text the
/// planner/worker authors; an off-vocab one is either a human-gated need the
/// worker flagged or a typo no worker has, and either way it must not reach
/// routing as a hard failure that stops the drain. We cannot enumerate every
/// capability with an alias table, so the rule is structural: a required
/// capability outside the real worker vocabulary means "no worker can do this"
/// -> park for a human (or a newly added worker). Idempotent; touches only
/// Queued tasks. Returns one `id (caps)` note per task parked.
pub(crate) fn reconcile_queue_capabilities(
    queue: &mut WorkQueue,
    workers: &WorkersFile,
) -> Vec<String> {
    let vocab = crate::routing::declared_capabilities(workers);
    let mut parked = Vec::new();
    for t in queue.tasks.iter_mut() {
        if t.state != TaskState::Queued || t.required_capabilities.is_empty() {
            continue;
        }
        let normalized: Vec<String> = t
            .required_capabilities
            .iter()
            .map(|c| crate::routing::norm_cap(c))
            .filter(|c| !c.is_empty())
            .collect();
        let unsatisfiable = crate::routing::unsatisfiable_capabilities(&normalized, &vocab);
        t.required_capabilities = normalized;
        if !unsatisfiable.is_empty() {
            t.state = TaskState::Blocked;
            let note = format!(
                "blocked at queue creation: no enabled worker declares required \
                 capability/capabilities [{}] — needs a human decision or a new worker",
                unsatisfiable.join(", ")
            );
            t.worker_rationale = Some(match t.worker_rationale.take() {
                Some(r) if !r.trim().is_empty() => format!("{r}\n{note}"),
                _ => note,
            });
            parked.push(format!("{} ({})", t.id, unsatisfiable.join(", ")));
        }
    }
    parked
}

/// Ingest worker-PROPOSED follow-up tasks into a queue (propose -> ingest).
/// The worker proposes follow-ups in its `result.json`; Yardlet assigns ids,
/// sanitizes deps to backward-only, dedups by title, and tags each
/// `provenance: worker-proposed` so an enqueued follow-up is a visible, tracked
/// CANDIDATE rather than a silent expansion of the current task (CLAUDE.md: an
/// adjacent idea becomes a queue candidate, never a silent scope broadening).
/// Yardlet stays the sole writer of the queue — the worker never edits
/// `.agents/work-queue.yaml` itself.
///
/// Placement: `insert: "next"` slots the task's priority below every currently
/// queued task so the selector prefers it (soft ordering); the default appends
/// after the current max. `runs_before: [ids]` is the HARD form — Yardlet
/// injects a dependency so each named existing task waits for this one (true
/// "insert between"), dropping self/unknown/cycle-forming targets.
///
/// Empty-title entries and titles that duplicate an existing queued task are
/// skipped. Returns the ids of the tasks actually ingested.
pub(crate) fn ingest_follow_ups(
    queue: &mut WorkQueue,
    follow_ups: &[crate::schemas::FollowUpTask],
) -> Vec<String> {
    let mut next_num = queue
        .tasks
        .iter()
        .filter_map(|t| {
            t.id.strip_prefix("YARD-")
                .and_then(|n| n.parse::<usize>().ok())
        })
        .max()
        .unwrap_or(queue.tasks.len())
        + 1;
    let mut tail_priority = queue.tasks.iter().map(|t| t.priority).max().unwrap_or(0);
    // "next" tasks share one priority just below the lowest currently-queued
    // task, so the selector runs them first; equal priorities tie-break by
    // queue order, preserving the worker's proposal order among them.
    let head_priority = queue
        .tasks
        .iter()
        .filter(|t| t.state == TaskState::Queued)
        .map(|t| t.priority)
        .min()
        .map(|m| m - 10)
        .unwrap_or(tail_priority + 10);
    let mut ingested = Vec::new();
    for fu in follow_ups {
        let title = fu.title.trim();
        if title.is_empty() {
            continue;
        }
        // Dedup: skip a follow-up whose title already names a queued task.
        if queue
            .tasks
            .iter()
            .any(|t| t.state == TaskState::Queued && t.title.trim().eq_ignore_ascii_case(title))
        {
            continue;
        }
        let prior_ids: Vec<String> = queue.tasks.iter().map(|t| t.id.clone()).collect();
        let id = format!("YARD-{next_num:03}");
        let priority = if fu.insert.eq_ignore_ascii_case("next") {
            head_priority
        } else {
            tail_priority += 10;
            tail_priority
        };
        // Record the worker's `reason` as the task's rationale when it gave no
        // explicit one — it is the audit trail for why the follow-up exists.
        let rationale = fu.worker_rationale.clone().or_else(|| {
            let r = fu.reason.trim();
            (!r.is_empty()).then(|| format!("worker-proposed follow-up: {r}"))
        });
        queue.tasks.push(Task {
            id: id.clone(),
            title: title.to_string(),
            state: TaskState::Queued,
            priority,
            risk: fu.risk.clone(),
            kind: fu.kind.clone(),
            preferred_worker: fu.preferred_worker.clone(),
            model: String::new(),
            effort: String::new(),
            depends_on: sanitize_deps(&fu.depends_on, &prior_ids),
            skills: fu.skills.clone(),
            required_capabilities: fu.required_capabilities.clone(),
            allowed_scope: fu.allowed_scope.clone(),
            acceptance: fu
                .acceptance
                .iter()
                .map(|s| yaml::Value::String(s.clone()))
                .collect(),
            validation: None,
            approval: None,
            interaction: None,
            worker_rationale: rationale,
            provenance: "worker-proposed".to_string(),
        });
        // HARD placement: make each named existing task depend on this new one.
        inject_runs_before(queue, &id, &fu.runs_before);
        ingested.push(id);
        next_num += 1;
    }
    ingested
}

/// Inject a "must run before" dependency: make each existing task named in
/// `targets` depend on `new_id`. Drops self-references, unknown ids, duplicates,
/// and any target that would form a dependency cycle (i.e. `new_id` already
/// depends, transitively, on that target).
fn inject_runs_before(queue: &mut WorkQueue, new_id: &str, targets: &[String]) {
    for target in targets {
        let target = target.trim();
        if target.is_empty() || target == new_id {
            continue;
        }
        if !queue.tasks.iter().any(|t| t.id == target) {
            continue; // unknown id
        }
        if depends_transitively(queue, new_id, target) {
            continue; // would create a cycle
        }
        if let Some(t) = queue.tasks.iter_mut().find(|t| t.id == target) {
            if !t.depends_on.iter().any(|d| d == new_id) {
                t.depends_on.push(new_id.to_string());
            }
        }
    }
}

/// Does task `from` depend, directly or transitively, on `target`? Used as a
/// cycle guard before injecting a `runs_before` dependency.
fn depends_transitively(queue: &WorkQueue, from: &str, target: &str) -> bool {
    let mut stack = vec![from.to_string()];
    let mut seen = std::collections::HashSet::new();
    while let Some(cur) = stack.pop() {
        if !seen.insert(cur.clone()) {
            continue;
        }
        if let Some(t) = queue.tasks.iter().find(|t| t.id == cur) {
            for d in &t.depends_on {
                if d == target {
                    return true;
                }
                stack.push(d.clone());
            }
        }
    }
    false
}

/// Recover a planning result left unconsumed by an interrupted session: the
/// worker finished and wrote `planning-result.json`, but Yardlet exited before
/// deriving the canonical intent/queue from it. Safe to call on every startup.
///
/// Guards against stale or double application: only the newest unconsumed plan
/// run is considered, it must not be superseded by a NEWER plan run (an
/// orphaned planning worker can finish long after the user already planned
/// something else — consuming it then would clobber the live intent/queue),
/// and its result file must be newer than the current queue file. Also
/// surfaces a still-alive planning worker from a previous session, so the
/// user knows a plan is on its way before paying for a duplicate one.
pub fn recover_unconsumed_plan(ws: &Workspace) -> Option<String> {
    let mut best: Option<(String, std::path::PathBuf)> = None;
    // The newest plan run with a result, consumed or not (supersession check).
    let mut newest_finished: Option<String> = None;
    // A previous session's planning worker that is still running.
    let mut live_planner: Option<(String, u32)> = None;
    for entry in std::fs::read_dir(ws.runs_dir()).ok()?.flatten() {
        let dir = entry.path();
        let Some(name) = dir.file_name().and_then(|n| n.to_str()).map(String::from) else {
            continue;
        };
        if !name.starts_with("plan-") {
            continue;
        }
        if !dir.join("planning-result.json").is_file() {
            // No result yet: is its worker still alive (orphaned planning)?
            if let Some(pid) = crate::run::live_worker_pid(&dir) {
                if live_planner
                    .as_ref()
                    .map(|(n, _)| name > *n)
                    .unwrap_or(true)
                {
                    live_planner = Some((name, pid));
                }
            }
            continue;
        }
        if newest_finished.as_ref().map(|n| name > *n).unwrap_or(true) {
            newest_finished = Some(name.clone());
        }
        let has_meta = dir.join("plan-meta.yaml").is_file() || workers::packet_path(&dir).is_file();
        if !has_meta || dir.join(CONSUMED_MARKER).exists() {
            continue;
        }
        if best.as_ref().map(|(n, _)| name > *n).unwrap_or(true) {
            best = Some((name, dir));
        }
    }
    let Some((run_id, run_dir)) = best else {
        // Nothing to consume — but report a planning worker still at work.
        return live_planner.map(|(name, pid)| {
            format!(
                "a planning worker from a previous session is still running \
                 ({name}, pid {pid}); its plan will be picked up when it finishes"
            )
        });
    };

    // Superseded: a newer plan run exists (consumed or not). Consuming this
    // older one would overwrite the user's current intent/queue with a stale
    // plan — retire it instead.
    if newest_finished
        .as_deref()
        .is_some_and(|n| n > run_id.as_str())
    {
        mark_consumed(&run_dir);
        return None;
    }

    // Freshness guard: the result must be newer than the canonical queue.
    let result_path = run_dir.join("planning-result.json");
    let result_mtime = std::fs::metadata(&result_path)
        .and_then(|m| m.modified())
        .ok()?;
    if let Ok(queue_mtime) = std::fs::metadata(ws.queue_path()).and_then(|m| m.modified()) {
        if result_mtime <= queue_mtime {
            // Already applied (or superseded by newer work): retire it quietly.
            mark_consumed(&run_dir);
            return None;
        }
    }

    let raw = std::fs::read_to_string(&result_path).ok()?;
    let plan: PlanningResult = serde_json::from_str(&raw).ok()?;
    if plan.tasks.is_empty() {
        mark_consumed(&run_dir); // unusable; don't retry forever
        return None;
    }
    let meta: PlanMeta = state::load_yaml(&run_dir.join("plan-meta.yaml"))
        .ok()
        .or_else(|| legacy_plan_meta(&run_dir))
        .unwrap_or_default();

    if meta.mode == "amend" {
        let mut queue = ws.load_queue().ok()?;
        let added = append_plan_tasks(&mut queue, &plan);
        ws.save_queue(&queue).ok()?;
        if let Ok(Some(mut intent)) = ws.load_intent() {
            if !plan.summary.trim().is_empty() {
                intent.summary =
                    format!("{}\n\n[follow-up] {}", intent.summary, plan.summary.trim());
                let _ = state::save_yaml(&ws.intent_path(), &intent);
            }
        }
        mark_consumed(&run_dir);
        return Some(format!(
            "recovered interrupted follow-up plan ({run_id}): +{added} task(s)"
        ));
    }

    if plan.summary.trim().is_empty() {
        mark_consumed(&run_dir);
        return None;
    }
    let intent_id = format!("intent-{}", Local::now().format("%Y%m%d-%H%M%S"));
    let intent = build_intent(&intent_id, &meta.request, &plan, &[]);
    let queue = build_queue(&intent_id, &plan);
    let _ = crate::report::archive_intent(ws);
    state::save_yaml(&ws.intent_path(), &intent).ok()?;
    ws.save_queue(&queue).ok()?;
    mark_consumed(&run_dir);
    Some(format!(
        "recovered interrupted plan ({run_id}): {} ({} tasks)",
        intent.summary,
        queue.tasks.len()
    ))
}

fn build_intent(
    intent_id: &str,
    request: &str,
    plan: &PlanningResult,
    images: &[String],
) -> IntentContract {
    // The gate reads one merged question list: the planner's explicit
    // questions_for_user plus whatever its ambiguity block still holds open.
    let mut open_questions: Vec<String> = plan
        .questions_for_user
        .iter()
        .map(|q| match q {
            PlanQuestion::Text(s) => s.clone(),
            PlanQuestion::Obj {
                question,
                statement,
            } => {
                if !question.trim().is_empty() {
                    question.clone()
                } else {
                    statement.clone()
                }
            }
        })
        .filter(|q| !q.trim().is_empty())
        .collect();
    for q in &plan.ambiguity.open_questions {
        if !q.trim().is_empty() && !open_questions.contains(q) {
            open_questions.push(q.clone());
        }
    }
    IntentContract {
        schema_version: 1,
        id: intent_id.to_string(),
        source: "user".to_string(),
        raw_request: request.to_string(),
        summary: plan.summary.clone(),
        allowed_scope: plan.allowed_scope.clone(),
        out_of_scope: plan.out_of_scope.clone(),
        acceptance: plan
            .acceptance
            .iter()
            .filter(|a| !a.statement.trim().is_empty())
            .map(|a| yaml::Value::String(a.statement.clone()))
            .collect(),
        images: images.to_vec(),
        ambiguity: plan.ambiguity.score.to_lowercase(),
        open_questions,
        clarifications: Vec::new(),
        interview_turns: 0,
        status: "accepted".to_string(),
    }
}

fn build_queue(intent_id: &str, plan: &PlanningResult) -> WorkQueue {
    let mut tasks: Vec<Task> = Vec::with_capacity(plan.tasks.len());
    for (i, t) in plan.tasks.iter().enumerate() {
        let prior_ids: Vec<String> = tasks.iter().map(|t| t.id.clone()).collect();
        let task = Task {
            id: if t.id.trim().is_empty() {
                format!("YARD-{:03}", i + 1)
            } else {
                t.id.clone()
            },
            title: t.title.clone(),
            state: TaskState::Queued,
            priority: ((i + 1) * 10) as i64,
            risk: t.risk.clone(),
            kind: t.kind.clone(),
            // Blank stays blank so routing's configured default_worker applies.
            preferred_worker: t.preferred_worker.clone(),
            model: t.model.clone(),
            effort: t.effort.clone(),
            depends_on: sanitize_deps(&t.depends_on, &prior_ids),
            skills: t.skills.clone(),
            required_capabilities: t.required_capabilities.clone(),
            allowed_scope: t.allowed_scope.clone(),
            acceptance: t
                .acceptance
                .iter()
                .map(|s| yaml::Value::String(s.clone()))
                .collect(),
            validation: None,
            approval: None,
            interaction: None,
            worker_rationale: t.worker_rationale.clone(),
            provenance: String::new(),
        };
        tasks.push(task);
    }

    ensure_review_task(&mut tasks);

    WorkQueue {
        schema_version: 1,
        queue_id: format!("queue-{intent_id}"),
        intent_id: intent_id.to_string(),
        selection_policy: SelectionPolicy::default(),
        tasks,
    }
}

/// The Semantic verification rung (absorption.md A3), as a deterministic
/// guarantee: a risky plan (any high-risk task) or a sizable one (3+ tasks)
/// must end in a review-kind task that verifies the intent's acceptance
/// criteria against the actual workspace. The planner is asked to include
/// one; if it forgot, Yardlet appends it — planner forgetfulness cannot skip
/// verification, and the verifier is never the doer (a separate reviewer-
/// role run, not a smarter evaluator).
fn ensure_review_task(tasks: &mut Vec<Task>) {
    let risky = tasks.iter().any(|t| t.risk.eq_ignore_ascii_case("high"));
    let sizable = tasks.len() >= 3;
    let has_review = tasks.iter().any(|t| t.kind.eq_ignore_ascii_case("review"));
    if !(risky || sizable) || has_review || tasks.is_empty() {
        return;
    }
    let next_num = tasks
        .iter()
        .filter_map(|t| {
            t.id.strip_prefix("YARD-")
                .and_then(|n| n.parse::<usize>().ok())
        })
        .max()
        .unwrap_or(tasks.len())
        + 1;
    let depends_on: Vec<String> = tasks.iter().map(|t| t.id.clone()).collect();
    let priority = tasks.iter().map(|t| t.priority).max().unwrap_or(0) + 10;
    tasks.push(Task {
        id: format!("YARD-{next_num:03}"),
        title: "Acceptance review (auto-added)".to_string(),
        state: TaskState::Queued,
        priority,
        risk: "low".to_string(),
        kind: "review".to_string(),
        preferred_worker: String::new(), // routing decides (kind overrides apply)
        model: String::new(),
        effort: String::new(),
        depends_on,
        skills: vec![],
        required_capabilities: vec![],
        allowed_scope: vec![],
        acceptance: vec![yaml::Value::String(
            "Every intent acceptance criterion is verified against the actual workspace, \
             with per-criterion pass/fail and evidence in report.md"
                .to_string(),
        )],
        validation: None,
        approval: None,
        interaction: None,
        worker_rationale: Some(
            "deterministic semantic-verification rung: the verifier is never the doer".to_string(),
        ),
        provenance: String::new(),
    });
}

/// Build the planner's worker-selection rubric from the editable profiles.
/// One neutral, parallel line per worker: a positive signal (best for) and,
/// when set, a negative one (avoid for). Contrastive boundaries and explicit
/// negatives help the planner discriminate better than long positive lists.
fn build_worker_guidance(workers: &WorkersFile) -> String {
    let mut g = format!("Cost bias: {}.\n", workers.routing.cost_bias);
    for w in &workers.workers {
        if w.best_for.is_empty() && w.capabilities.is_empty() {
            continue;
        }
        let cost = if w.cost_weight.is_empty() {
            "?"
        } else {
            &w.cost_weight
        };
        g.push_str(&format!("- {} (cost: {})", w.id, cost));
        if !w.best_for.is_empty() {
            g.push_str(&format!(": best for {}.", w.best_for));
        }
        if !w.not_for.is_empty() {
            g.push_str(&format!(" Avoid for {}.", w.not_for));
        }
        if !w.capabilities.is_empty() {
            g.push_str(&format!(" Capabilities: {}.", w.capabilities.join(", ")));
        }
        g.push('\n');
    }
    // Capabilities are HARD routing constraints, not soft preferences. Tell the
    // planner to set `required_capabilities` on a task that needs one, rather
    // than relying on title wording (no magic keywords).
    let caps: std::collections::BTreeSet<&str> = workers
        .workers
        .iter()
        .flat_map(|w| w.capabilities.iter().map(|c| c.as_str()))
        .collect();
    if !caps.is_empty() {
        let list = caps.into_iter().collect::<Vec<_>>().join(", ");
        g.push_str(&format!(
            "\nCapabilities are HARD constraints. For special work a listed worker CAN do, set the \
             task's `required_capabilities` to the matching capability from [{list}] (exact \
             string): routing then runs only a worker that declares it. Decide from the task's \
             meaning, not keywords; leave it empty when no special capability is needed. For work \
             that genuinely needs something NO listed worker can do (licensing, procurement, an \
             external or human decision), name that needed capability anyway even though it is not \
             in [{list}] — Yardlet parks such a task for a human instead of mis-running it. So: a \
             capability IN [{list}] routes to a worker; one OUTSIDE it flags a human-gated task.\n"
        ));
    }
    g
}

/// Resolve the ordered worker preference and return the first that is ready.
pub(crate) fn pick_ready_worker(
    workers: &WorkersFile,
    billing: &crate::schemas::BillingPolicy,
    worker_override: Option<&str>,
) -> Result<(WorkerProfile, std::path::PathBuf, String)> {
    let mut order: Vec<String> = Vec::new();
    if let Some(o) = worker_override {
        order.push(o.to_string());
    }
    let pg = &workers.routing.planning_gate;
    for v in [&pg.primary, &pg.fallback] {
        if !v.is_empty() && v != "none" {
            order.push(v.clone());
        }
    }
    order.push("codex".to_string());

    let mut tried = Vec::new();
    for id in order {
        if tried.contains(&id) {
            continue;
        }
        tried.push(id.clone());
        let Some(profile) = workers.workers.iter().find(|w| w.id == id) else {
            continue;
        };
        if !profile.enabled {
            continue;
        }
        let status = guard::probe(profile, billing);
        if status.readiness == Readiness::Ready {
            if let Some(bin) = status.binary_path {
                return Ok((profile.clone(), bin, id));
            }
        }
    }

    Err(anyhow!(
        "no invocable planning worker among {tried:?}. Run `yardlet worker status` to diagnose. \
         Yardlet did not call an AI API and did not ask for an API key."
    ))
}

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

    #[test]
    fn worker_guidance_has_contrastive_positive_and_negative_lines() {
        let yaml = r#"
schema_version: 1
workers:
  - id: codex
    best_for: scoped edits
    not_for: ambiguous specs
    cost_weight: low
    invocation: { command: codex }
  - id: claude-code
    best_for: refactors
    cost_weight: high
    invocation: { command: claude }
  - id: blankworker
    cost_weight: low
    invocation: { command: blankworker }
routing:
  cost_bias: balanced
"#;
        let wf: WorkersFile = serde_yaml_ng::from_str(yaml).expect("workers yaml parses");
        let g = build_worker_guidance(&wf);
        assert!(g.contains("Cost bias: balanced."));
        // Positive + negative signal on one neutral line.
        assert!(
            g.contains("- codex (cost: low): best for scoped edits. Avoid for ambiguous specs.\n")
        );
        // No not_for -> no "Avoid for" appended.
        assert!(g.contains("- claude-code (cost: high): best for refactors.\n"));
        assert!(!g.contains("best for refactors. Avoid"));
        // Empty best_for -> worker skipped entirely.
        assert!(!g.contains("blankworker"));
    }

    #[test]
    fn reconcile_parks_unsatisfiable_capability_at_creation() {
        fn cap_task(id: &str, state: TaskState, caps: &[&str]) -> Task {
            Task {
                id: id.into(),
                title: id.into(),
                state,
                priority: 10,
                risk: String::new(),
                kind: String::new(),
                preferred_worker: String::new(),
                model: String::new(),
                effort: String::new(),
                depends_on: vec![],
                skills: vec![],
                required_capabilities: caps.iter().map(|s| s.to_string()).collect(),
                allowed_scope: vec![],
                acceptance: vec![],
                validation: None,
                approval: None,
                interaction: None,
                worker_rationale: None,
                provenance: String::new(),
            }
        }
        let wf: WorkersFile = serde_yaml_ng::from_str(
            r#"
schema_version: 1
workers:
  - id: codex
    enabled: true
    capabilities: [image_generation]
    invocation: { command: codex }
routing:
  cost_bias: balanced
"#,
        )
        .unwrap();
        let mut q = WorkQueue {
            schema_version: 1,
            queue_id: "q".into(),
            intent_id: String::new(),
            selection_policy: SelectionPolicy::default(),
            tasks: vec![
                cap_task("A", TaskState::Queued, &["image_generation"]), // satisfiable
                cap_task("B", TaskState::Queued, &["licensed_3d_asset_intake"]), // no worker
                cap_task("C", TaskState::Queued, &["Image-Generation"]), // normalizes -> satisfiable
                cap_task("D", TaskState::Done, &["sorcery"]),            // non-Queued: untouched
                cap_task("E", TaskState::Queued, &[]),                   // no caps: untouched
            ],
        };
        let parked = reconcile_queue_capabilities(&mut q, &wf);

        assert_eq!(q.tasks[0].state, TaskState::Queued); // A satisfiable
        assert_eq!(q.tasks[1].state, TaskState::Blocked); // B parked
        assert!(q.tasks[1]
            .worker_rationale
            .as_deref()
            .unwrap()
            .contains("licensed_3d_asset_intake"));
        assert_eq!(q.tasks[2].state, TaskState::Queued); // C normalized + satisfiable
        assert_eq!(
            q.tasks[2].required_capabilities,
            vec!["image_generation".to_string()]
        );
        assert_eq!(q.tasks[3].state, TaskState::Done); // D untouched (not Queued)
        assert_eq!(
            q.tasks[3].required_capabilities,
            vec!["sorcery".to_string()]
        );
        assert_eq!(q.tasks[4].state, TaskState::Queued); // E untouched (no caps)
        assert_eq!(parked.len(), 1);
        assert!(parked[0].starts_with("B "));
    }

    // Regression: a worker emitted `questions_for_user` as objects
    // ({id, question, topic}) mirroring the `acceptance` hint, which used to
    // crash serde with `invalid type: map, expected a string`. Accept both
    // object and string shapes and extract the human-readable text.
    #[test]
    fn questions_accept_object_or_string_shape() {
        let json = r#"{
            "summary": "do a thing",
            "tasks": [{ "id": "YARD-001", "title": "t" }],
            "questions_for_user": [
                { "id": "Q1", "question": "scope ok?", "topic": "scope" },
                "plain string question",
                { "id": "Q2", "statement": "fallback to statement" }
            ]
        }"#;
        let plan: PlanningResult =
            serde_json::from_str(json).expect("both question shapes must parse");
        let qs: Vec<String> = plan
            .questions_for_user
            .into_iter()
            .map(PlanQuestion::into_text)
            .collect();
        assert_eq!(
            qs,
            vec![
                "scope ok?".to_string(),
                "plain string question".to_string(),
                "fallback to statement".to_string(),
            ]
        );
    }

    #[test]
    fn recovers_unconsumed_plan_after_restart() {
        let root = std::env::temp_dir().join(format!("yard-planrec-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let ws = Workspace::at(&root);
        let run_dir = ws.runs_dir().join("plan-20990101-000000");
        std::fs::create_dir_all(&run_dir).unwrap();
        state::save_yaml(
            &run_dir.join("plan-meta.yaml"),
            &PlanMeta {
                mode: "new".into(),
                request: "add admin search".into(),
            },
        )
        .unwrap();
        write_str(
            &run_dir.join("planning-result.json"),
            r#"{ "summary": "admin search",
                 "tasks": [{ "id": "YARD-001", "title": "t" }] }"#,
        )
        .unwrap();

        // First startup after the crash: the plan is consumed into canonical state.
        let msg = recover_unconsumed_plan(&ws).expect("plan should be recovered");
        assert!(msg.contains("admin search"));
        let queue = ws.load_queue().unwrap();
        assert_eq!(queue.tasks.len(), 1);
        let intent = ws.load_intent().unwrap().unwrap();
        assert_eq!(intent.raw_request, "add admin search");

        // Second startup: marked consumed, nothing to do.
        assert!(recover_unconsumed_plan(&ws).is_none());
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn review_task_is_guaranteed_for_risky_or_sizable_plans() {
        let plan = |n: usize, risk: &str, with_review: bool| -> WorkQueue {
            let mut json_tasks: Vec<String> = (1..=n)
                .map(|i| {
                    format!(
                        r#"{{ "id": "YARD-{i:03}", "title": "t{i}", "risk": "{risk}", "kind": "implementation" }}"#
                    )
                })
                .collect();
            if with_review {
                json_tasks.push(
                    r#"{ "id": "YARD-099", "title": "review", "kind": "review" }"#.to_string(),
                );
            }
            let json = format!(
                r#"{{ "summary": "s", "tasks": [{}] }}"#,
                json_tasks.join(",")
            );
            let p: PlanningResult = serde_json::from_str(&json).unwrap();
            build_queue("i", &p)
        };

        // High risk, single task: review appended with deps on everything.
        let q = plan(1, "high", false);
        assert_eq!(q.tasks.len(), 2);
        let review = q.tasks.last().unwrap();
        assert_eq!(review.kind, "review");
        assert_eq!(review.id, "YARD-002");
        assert_eq!(review.depends_on, vec!["YARD-001"]);

        // 3+ tasks, all low risk: appended too.
        let q = plan(3, "low", false);
        assert_eq!(q.tasks.len(), 4);
        assert_eq!(
            q.tasks.last().unwrap().depends_on,
            vec!["YARD-001", "YARD-002", "YARD-003"]
        );

        // Planner already included a review: nothing added.
        let q = plan(3, "high", true);
        assert_eq!(q.tasks.iter().filter(|t| t.kind == "review").count(), 1);

        // Small low-risk plan: no forced ceremony.
        let q = plan(2, "low", false);
        assert_eq!(q.tasks.len(), 2);
    }

    #[test]
    fn goal_builds_a_two_task_queue_with_a_separate_verifier() {
        let root = std::env::temp_dir().join(format!("yard-goal-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let ws = Workspace::at(&root);

        // No verify: a single implementation task, no ambiguity gate.
        let n = plan_goal(&ws, "fix the login redirect", None, None, &[]).unwrap();
        assert_eq!(n, 1);
        let q = ws.load_queue().unwrap();
        assert_eq!(q.tasks.len(), 1);
        assert_eq!(q.tasks[0].kind, "implementation");
        let intent = ws.load_intent().unwrap().unwrap();
        assert_eq!(intent.ambiguity, "low");
        assert!(!intent_gated(&intent, true));

        // With verify: a second reviewer task depends on the first.
        let n = plan_goal(
            &ws,
            "polish the title screen",
            Some("no clipped text and the theme is consistent"),
            None,
            &[],
        )
        .unwrap();
        assert_eq!(n, 2);
        let q = ws.load_queue().unwrap();
        assert_eq!(q.tasks[1].kind, "review");
        assert_eq!(q.tasks[1].depends_on, vec!["YARD-001"]);
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn express_goal_does_not_keyword_force_a_worker() {
        let root = std::env::temp_dir().join(format!("yard-image-goal-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let ws = Workspace::at(&root);

        // The express path bypasses the planner; with no --worker/--requires it
        // must NOT infer a worker from wording (the old keyword router is gone).
        let n = plan_goal(
            &ws,
            "generate icon assets for the settings page",
            None,
            None,
            &[],
        )
        .unwrap();
        assert_eq!(n, 1);
        let q = ws.load_queue().unwrap();
        assert_eq!(q.tasks[0].preferred_worker, "");
        assert!(q.tasks[0].required_capabilities.is_empty());
        let _ = std::fs::remove_dir_all(&root);

        // --worker forces a worker for the express goal.
        let _ = std::fs::remove_dir_all(&root);
        let n = plan_goal(&ws, "generate icon assets", None, Some("codex"), &[]).unwrap();
        assert_eq!(n, 1);
        assert_eq!(ws.load_queue().unwrap().tasks[0].preferred_worker, "codex");
        let _ = std::fs::remove_dir_all(&root);

        // --requires sets a hard capability route (the escape hatch for the
        // express path that the capability router can then honor).
        let _ = std::fs::remove_dir_all(&root);
        let n = plan_goal(
            &ws,
            "generate icon assets",
            None,
            None,
            &["image_generation".to_string()],
        )
        .unwrap();
        assert_eq!(n, 1);
        assert_eq!(
            ws.load_queue().unwrap().tasks[0].required_capabilities,
            vec!["image_generation".to_string()]
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn ambiguity_gate_logic() {
        let mut intent = IntentContract {
            schema_version: 1,
            id: "i".into(),
            source: String::new(),
            raw_request: String::new(),
            summary: String::new(),
            allowed_scope: vec![],
            out_of_scope: vec![],
            acceptance: vec![],
            images: vec![],
            ambiguity: "high".into(),
            open_questions: vec!["which auth provider?".into()],
            clarifications: vec![],
            interview_turns: 0,
            status: String::new(),
        };
        assert!(intent_gated(&intent, true));
        assert!(!intent_gated(&intent, false)); // config off
        intent.ambiguity = "medium".into();
        assert!(!intent_gated(&intent, true)); // only high gates
        intent.ambiguity = "high".into();
        intent.interview_turns = INTERVIEW_CAP;
        assert!(!intent_gated(&intent, true)); // cap opens the gate
        intent.interview_turns = 0;
        intent.open_questions.clear();
        assert!(!intent_gated(&intent, true)); // nothing to ask = no gate
    }

    #[test]
    fn intent_records_planner_ambiguity_and_questions() {
        let json = r#"{
            "summary": "s",
            "tasks": [{ "id": "YARD-001", "title": "t" }],
            "ambiguity": { "score": "HIGH", "open_questions": ["q1", "q2"] },
            "questions_for_user": ["q1", "q3"]
        }"#;
        let plan: PlanningResult = serde_json::from_str(json).unwrap();
        let intent = build_intent("i", "req", &plan, &[]);
        assert_eq!(intent.ambiguity, "high");
        // merged + deduped: questions_for_user first, then ambiguity extras
        assert_eq!(intent.open_questions, vec!["q1", "q3", "q2"]);
    }

    #[test]
    fn superseded_plan_is_never_recovered_over_a_newer_one() {
        // An orphaned planning worker can finish AFTER the user has already
        // planned (and consumed) something newer. Recovering the stale plan
        // would clobber the live intent/queue — it must be retired instead.
        let root = std::env::temp_dir().join(format!("yard-stale-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let ws = Workspace::at(&root);

        // Newer plan: already consumed (the user's current work).
        let newer = ws.runs_dir().join("plan-20990202-000000");
        std::fs::create_dir_all(&newer).unwrap();
        write_str(&newer.join("planning-result.json"), "{}").unwrap();
        write_str(&newer.join(CONSUMED_MARKER), "").unwrap();
        ws.save_queue(&WorkQueue {
            schema_version: 1,
            queue_id: "q".into(),
            intent_id: "live".into(),
            selection_policy: Default::default(),
            tasks: vec![],
        })
        .unwrap();

        // Older plan: finished late by an orphaned worker, never consumed.
        // Its result file is NEWER than the queue on disk (written just now).
        let stale = ws.runs_dir().join("plan-20990101-000000");
        std::fs::create_dir_all(&stale).unwrap();
        state::save_yaml(
            &stale.join("plan-meta.yaml"),
            &PlanMeta {
                mode: "new".into(),
                request: "old request".into(),
            },
        )
        .unwrap();
        write_str(
            &stale.join("planning-result.json"),
            r#"{ "summary": "stale plan",
                 "tasks": [{ "id": "YARD-001", "title": "t" }] }"#,
        )
        .unwrap();

        assert!(recover_unconsumed_plan(&ws).is_none());
        // The live queue was not replaced, and the stale plan is retired.
        assert_eq!(ws.load_queue().unwrap().intent_id, "live");
        assert!(stale.join(CONSUMED_MARKER).exists());
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn reports_a_still_running_planning_worker() {
        let root = std::env::temp_dir().join(format!("yard-liveplan-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let ws = Workspace::at(&root);
        let dir = ws.runs_dir().join("plan-20990101-000000");
        std::fs::create_dir_all(&dir).unwrap();
        // No result yet, but the worker (our own pid) is alive.
        write_str(&dir.join("worker.pid"), &std::process::id().to_string()).unwrap();
        let msg = recover_unconsumed_plan(&ws).expect("live planner should be reported");
        assert!(msg.contains("still running"), "{msg}");
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn recovers_legacy_plan_without_meta_file() {
        // Plan dirs created before plan-meta.yaml existed: reconstruct the
        // request (and mode) from the compiled packet.
        let root = std::env::temp_dir().join(format!("yard-planrec-legacy-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let ws = Workspace::at(&root);
        let run_dir = ws.runs_dir().join("plan-20990101-000000");
        std::fs::create_dir_all(&run_dir).unwrap();
        write_str(
            &workers::packet_path(&run_dir),
            "# Yardlet planning gate\n\n## Request (verbatim)\n\n\
             make the game feel like a game\n\n## Rules\n\n- ...\n",
        )
        .unwrap();
        write_str(
            &run_dir.join("planning-result.json"),
            r#"{ "summary": "game feel",
                 "tasks": [{ "id": "YARD-101", "title": "t" }] }"#,
        )
        .unwrap();

        let msg = recover_unconsumed_plan(&ws).expect("legacy plan should be recovered");
        assert!(msg.contains("game feel"));
        let intent = ws.load_intent().unwrap().unwrap();
        assert_eq!(intent.raw_request, "make the game feel like a game");
        assert!(recover_unconsumed_plan(&ws).is_none());
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn ingest_follow_ups_assigns_ids_dedups_and_tags_provenance() {
        use crate::schemas::FollowUpTask;
        // Start from a one-task queue (YARD-001 "existing", priority 10, Queued).
        let plan: PlanningResult = serde_json::from_str(
            r#"{ "summary": "s", "tasks": [{ "id": "YARD-001", "title": "existing", "risk": "low" }] }"#,
        )
        .unwrap();
        let mut queue = build_queue("intent-x", &plan);

        let fus = vec![
            FollowUpTask {
                title: "add tests".into(),
                reason: "coverage gap".into(),
                // backward dep kept; unknown forward dep dropped by sanitize_deps
                depends_on: vec!["YARD-001".into(), "YARD-999".into()],
                ..Default::default()
            },
            FollowUpTask {
                title: "   ".into(), // empty after trim -> dropped
                reason: "blank".into(),
                ..Default::default()
            },
            FollowUpTask {
                title: "existing".into(), // duplicates a queued title -> skipped
                reason: "dup".into(),
                ..Default::default()
            },
        ];
        let ingested = ingest_follow_ups(&mut queue, &fus);

        // Only "add tests" survives, as the next YARD id.
        assert_eq!(ingested, vec!["YARD-002".to_string()]);
        let t = queue.tasks.iter().find(|t| t.id == "YARD-002").unwrap();
        assert_eq!(t.title, "add tests");
        assert_eq!(t.state, TaskState::Queued);
        assert_eq!(t.provenance, "worker-proposed");
        assert!(t.priority > 10, "priority sequenced after the current max");
        assert_eq!(t.depends_on, vec!["YARD-001".to_string()]);
        assert!(t
            .worker_rationale
            .as_deref()
            .unwrap()
            .contains("coverage gap"));
        // Total: original + one ingested (blank + dup were not added).
        assert_eq!(queue.tasks.len(), 2);
    }

    #[test]
    fn ingest_insert_next_sorts_before_existing_queued() {
        use crate::schemas::FollowUpTask;
        let plan: PlanningResult = serde_json::from_str(
            r#"{ "summary": "s", "tasks": [
                { "id": "YARD-001", "title": "a", "risk": "low" },
                { "id": "YARD-002", "title": "b", "risk": "low" } ] }"#,
        )
        .unwrap();
        let mut queue = build_queue("i", &plan);
        let min_before = queue
            .tasks
            .iter()
            .filter(|t| t.state == TaskState::Queued)
            .map(|t| t.priority)
            .min()
            .unwrap();

        let ingested = ingest_follow_ups(
            &mut queue,
            &[FollowUpTask {
                title: "urgent regen".into(),
                reason: "hit a capability ceiling".into(),
                insert: "next".into(),
                ..Default::default()
            }],
        );
        assert_eq!(ingested, vec!["YARD-003".to_string()]);
        let t = queue.tasks.iter().find(|t| t.id == "YARD-003").unwrap();
        assert!(
            t.priority < min_before,
            "insert:next must sort before every currently-queued task (got {} vs min {})",
            t.priority,
            min_before
        );
        // The default (append) still lands after the current max.
        let ingested = ingest_follow_ups(
            &mut queue,
            &[FollowUpTask {
                title: "later cleanup".into(),
                reason: "tidy up".into(),
                ..Default::default()
            }],
        );
        assert_eq!(ingested, vec!["YARD-004".to_string()]);
        let appended = queue.tasks.iter().find(|t| t.id == "YARD-004").unwrap();
        assert!(appended.priority > min_before);
    }

    #[test]
    fn ingest_runs_before_injects_dependency_and_guards_cycles() {
        use crate::schemas::FollowUpTask;
        let plan: PlanningResult = serde_json::from_str(
            r#"{ "summary": "s", "tasks": [
                { "id": "YARD-001", "title": "a", "risk": "low" },
                { "id": "YARD-002", "title": "b", "risk": "low" } ] }"#,
        )
        .unwrap();

        // runs_before YARD-002 -> YARD-002 now WAITS for the inserted task.
        // Self ("YARD-003") and unknown ("NOPE") targets are dropped.
        let mut queue = build_queue("i", &plan);
        let ingested = ingest_follow_ups(
            &mut queue,
            &[FollowUpTask {
                title: "prerequisite".into(),
                reason: "must run first".into(),
                runs_before: vec!["YARD-002".into(), "YARD-003".into(), "NOPE".into()],
                ..Default::default()
            }],
        );
        assert_eq!(ingested, vec!["YARD-003".to_string()]);
        let target = queue.tasks.iter().find(|t| t.id == "YARD-002").unwrap();
        assert!(
            target.depends_on.contains(&"YARD-003".to_string()),
            "YARD-002 must depend on the inserted task"
        );
        let inserted = queue.tasks.iter().find(|t| t.id == "YARD-003").unwrap();
        assert!(
            !inserted.depends_on.contains(&"YARD-003".to_string()),
            "self-reference must be dropped"
        );

        // Cycle guard: a follow-up that itself depends on YARD-002 cannot also
        // make YARD-002 wait for it (that would deadlock the queue).
        let mut q2 = build_queue("i", &plan);
        ingest_follow_ups(
            &mut q2,
            &[FollowUpTask {
                title: "cyclic".into(),
                reason: "r".into(),
                depends_on: vec!["YARD-002".into()],
                runs_before: vec!["YARD-002".into()],
                ..Default::default()
            }],
        );
        let y2 = q2.tasks.iter().find(|t| t.id == "YARD-002").unwrap();
        assert!(
            !y2.depends_on.contains(&"YARD-003".to_string()),
            "cycle-forming runs_before injection must be dropped"
        );
    }

    #[test]
    fn queue_keeps_only_backward_dependencies() {
        let json = r#"{
            "summary": "do a thing",
            "tasks": [
                { "id": "YARD-001", "title": "a" },
                { "id": "YARD-002", "title": "b",
                  "depends_on": ["YARD-001", "YARD-002", "YARD-003", "NOPE"] },
                { "id": "YARD-003", "title": "c", "depends_on": ["YARD-001"] }
            ]
        }"#;
        let plan: PlanningResult = serde_json::from_str(json).unwrap();
        let q = build_queue("intent-x", &plan);
        assert!(q.tasks[0].depends_on.is_empty());
        // self-reference, forward reference, and unknown id are all dropped
        assert_eq!(q.tasks[1].depends_on, vec!["YARD-001".to_string()]);
        assert_eq!(q.tasks[2].depends_on, vec!["YARD-001".to_string()]);
    }
}