octl-core 0.1.6

Core library for orchestratectl (schema, file I/O, locking, supervisor protocol).
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
//! `plan.json` v3 — serde types + structural validator (design.md §4, §7, §13).
//!
//! `plan.json` is the **interface contract** the spec-node writes and the
//! supervisor + orchestrator read. It is immutable per revision, versioned, and
//! provenance-bearing. This module provides:
//!
//! - The serde [`Plan`] type (and its parts) mirroring `plan-schema.md` v3.
//! - A structural [`validate_plan`] / [`parse_and_validate_plan`] pass that
//!   rejects a bad plan with a domain-typed [`PlanValidationError`] (the CLI
//!   maps these to its `schema_violation` envelope at the boundary, exactly as
//!   it does for [`crate::report::ReportValidationError`]).
//! - [`PLAN_V3_JSON_SCHEMA`], the checked-in JSON Schema artifact, so external
//!   readers/writers validate against a single source of truth. A drift-guard
//!   test keeps the Rust types and the JSON Schema in agreement.
//!
//! # v3: baseline provenance is structurally required
//!
//! v3 promotes the three baseline provenance fields — `commit_oid`,
//! `toolchain`, and `enumerated_targets_hash` — from additive-optional
//! (`#[serde(default)]` in v2) to **required**, so a plan that carries no
//! provenance can never be certified. The requirement is enforced in two
//! layers: a document that *omits* a field fails to deserialize
//! ([`PlanValidationError::Malformed`], because the fields carry no serde
//! default), and one that carries a *blank* field is rejected by
//! [`validate_plan`] ([`PROVENANCE_REQUIRED_SCHEMA`],
//! [`PlanValidationError::EmptyString`]) — the same two-layer treatment the
//! other required baseline strings get. This is only the *structural* half: it
//! proves the evidence is present and non-blank, not that it is well-formed or
//! authentic. The runtime fail-closed gate (`verify_plan_baseline` /
//! `gate_plan_baseline` in the CLI) is the other half — it checks the values
//! *match* the live snapshot (and validates the OID shape + toolchain there).
//!
//! # Compatibility semantics (design.md §13, `plan-schema.md` "Principles")
//!
//! `schema_version` gates the file with *real* compatibility semantics — this
//! is not "ignore everything unknown":
//!
//! - Readers **reject unsupported major versions** ([`SUPPORTED_PLAN_SCHEMAS`]).
//! - Readers **reject undeclared fields** — any key not in the v3 shape is a
//!   rejection. On the map-like objects (plan, `feature`, `baseline`,
//!   `chunks[]`, `chunks[].checks[]`) this is [`PlanValidationError::UnknownField`],
//!   gated by a **per-object-shape** allowlist (`tolerated_fields`): a field
//!   ratified as additive on one shape is tolerated there and nowhere else. On
//!   `acceptance[]` items (a tagged enum) it is a `deny_unknown_fields`
//!   deserialization error ([`PlanValidationError::Malformed`]) — the same
//!   stance the JSON Schema takes, with no additive seam in v3. The allowlists
//!   are empty in v3, so every unknown key is currently rejected; a future minor
//!   registers an additive optional field against its shape (and in the JSON
//!   Schema) so older readers tolerate it, and only then. Schema growth
//!   otherwise goes gap-event → reviewed proposal → versioned schema.
//!
//! This module is **read-only + validation types**. It does not touch the
//! reducer, the lock layer, or any event-append path (state-integrity
//! invariants), and it is not yet wired into a live path — T3 (deterministic
//! floor) and T5 (supervisor) consume it.

use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

/// The current `plan.json` schema major version this crate writes.
pub const PLAN_SCHEMA_VERSION: u32 = 3;

/// All `plan.json` schema major versions this crate can read. A file whose
/// `schema_version` is not listed here is rejected outright
/// ([`PlanValidationError::UnsupportedSchemaVersion`]) — tolerant reading is
/// limited to additive optional fields *within* a supported major, never to a
/// whole unknown major.
///
/// v2 is intentionally dropped: a v2 plan carries optional-by-default provenance
/// and so cannot satisfy the v3 structural requirement. Rather than admit it and
/// then fail it on the provenance gate, a v2 document is rejected up front as an
/// unsupported major (the runtime already fails closed on missing provenance).
pub const SUPPORTED_PLAN_SCHEMAS: &[u32] = &[3];

/// The first schema major at which baseline provenance (`commit_oid`,
/// `toolchain`, `enumerated_targets_hash`) is **structurally required** at
/// [`validate_plan`]: a plan whose `schema_version` is `>=` this value must
/// carry all three as non-empty strings.
///
/// Today [`SUPPORTED_PLAN_SCHEMAS`] is `[3]` and this equals `3`, so every plan
/// that reaches the gate already satisfies the threshold — the check is
/// effectively unconditional (a `debug_assert!` in [`validate_plan`] pins that
/// invariant). The constant is named rather than inlined only to document *when*
/// the requirement began and to give a future major that keeps these exact three
/// provenance fields a single place to reason about. It is **not** a
/// back-compat seam: the [`Baseline`] fields carry no `#[serde(default)]`, so a
/// document missing them cannot deserialize regardless of this threshold — a
/// future major that dropped the requirement would need its own wire type, not
/// merely a lower `schema_version`.
pub const PROVENANCE_REQUIRED_SCHEMA: u32 = 3;

/// Field names tolerated when they appear as unknown keys in an otherwise-valid
/// plan — the governed-evolution seam (design.md §13). Empty in v3: no additive
/// optional field has been ratified yet, so every unknown key is currently a
/// rejection.
///
/// This is the flattened union across every object shape, exposed for
/// documentation and the `expected` hint. The *operative* allowlist is
/// **per-object-shape** (`tolerated_fields`): a field ratified as additive on
/// `chunks[]` is tolerated there and nowhere else — a field's optionality
/// depends on its location, not just its name, so a global name-only allowlist
/// would leak a `chunks[].retries` tolerance onto `feature`, `baseline`, and
/// the top level. A future minor registers a new field against its specific
/// `ObjectShape` (and in the JSON Schema) so older readers tolerate it there;
/// anything not listed for that shape is a possibly-required unknown and is
/// rejected.
pub const TOLERATED_OPTIONAL_FIELDS: &[&str] = &[];

/// The object shapes an unknown-field check runs against — each carries its own
/// additive-optional allowlist ([`tolerated_fields`]), so the governed-evolution
/// seam is scoped to a location rather than a bare field name. (`Acceptance`
/// items are absent: they reject unknowns at deserialize time via
/// `deny_unknown_fields`, matching the schema, and have no seam in v3.)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ObjectShape {
    /// The top-level plan object.
    Plan,
    /// `feature`.
    Feature,
    /// `baseline`.
    Baseline,
    /// A `chunks[]` element.
    Chunk,
    /// A `chunks[].checks[]` element.
    Check,
}

impl ObjectShape {
    /// Dotted path fragment naming this shape in an error (the chunk/check
    /// arms fill in the index at the call site).
    fn label(self) -> &'static str {
        match self {
            ObjectShape::Plan => "<plan>",
            ObjectShape::Feature => "feature",
            ObjectShape::Baseline => "baseline",
            ObjectShape::Chunk => "chunks[]",
            ObjectShape::Check => "checks[]",
        }
    }
}

/// The additive-optional fields tolerated on a given object shape. Empty for
/// every shape in v3 — the seam exists so a ratified field can be admitted at
/// exactly one location without widening any other (design.md §13).
const fn tolerated_fields(shape: ObjectShape) -> &'static [&'static str] {
    match shape {
        ObjectShape::Plan
        | ObjectShape::Feature
        | ObjectShape::Baseline
        | ObjectShape::Chunk
        | ObjectShape::Check => &[],
    }
}

/// The checked-in JSON Schema (Draft 2020-12) describing `plan.json` v3.
///
/// This is the machine-readable artifact external readers/writers validate
/// against. The operative source of truth for the supervisor/spec-node is the
/// [`Plan`] type + [`validate_plan`] in this module; a drift-guard test
/// (`json_schema_matches_rust_types`) asserts the two never diverge on the
/// version constant, the required top-level fields, the [`Tier`] enum, and the
/// acceptance `kind` discriminants.
pub const PLAN_V3_JSON_SCHEMA: &str = include_str!("../schemas/plan.v3.schema.json");

/// Return the checked-in JSON Schema source for `plan.json` v3.
#[must_use]
pub fn plan_v3_json_schema() -> &'static str {
    PLAN_V3_JSON_SCHEMA
}

/// The checked-in canonical `plan.json` v3 example (`plan-schema.md` sample),
/// exposed so a spec-node prompt can show the model the exact target shape.
pub const PLAN_V3_EXAMPLE: &str = include_str!("../schemas/plan.v3.example.json");

/// Return the canonical `plan.json` v3 example document.
#[must_use]
pub fn plan_v3_json_schema_example() -> &'static str {
    PLAN_V3_EXAMPLE
}

/// A `plan.json` v3 document (design.md §4, §7; `plan-schema.md`).
///
/// Deserialization is deliberately *tolerant* of unknown keys (they are
/// captured into `extra` rather than failing the parse) so the structural
/// validator can decide their fate per the compatibility semantics above —
/// rejecting undeclared fields while leaving room for an allowlisted additive
/// optional field. Always construct through [`parse_and_validate_plan`] (or run
/// [`validate_plan`] after deserializing) before trusting a `Plan`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Plan {
    /// Major schema version. Readers reject unsupported majors.
    pub schema_version: u32,
    /// Immutable revision of this plan; chunk attempts reference it.
    pub plan_rev: u32,
    /// The `intent.md` revision this plan targets (intent is referenced, not
    /// embedded).
    pub intent_rev: u32,
    /// Feature identity: slug + source/integration branches.
    pub feature: Feature,
    /// Snapshot at `feat/<slug>` fork; the floor + verify diff against it.
    pub baseline: Baseline,
    /// Whole-feature intent gate; each item is a `check` or an `assertion`,
    /// and at least one must be a `check`.
    pub acceptance: Vec<Acceptance>,
    /// The DAG of implementation chunks (`deps` form an acyclic graph).
    pub chunks: Vec<Chunk>,
    /// Unrecognized top-level keys, captured for the compatibility check rather
    /// than silently dropped. Serialized back out verbatim so a tolerated
    /// additive field round-trips.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// Feature identity block (owner: orchestrator/spec).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Feature {
    /// Feature slug (e.g. `user-csv-export`).
    pub slug: String,
    /// Branch the feature forks from (e.g. `main`).
    pub source_branch: String,
    /// Integration branch the chunks merge into (e.g. `feat/user-csv-export`).
    pub integration_branch: String,
    /// Unrecognized keys, captured for the compatibility check.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// Baseline snapshot captured at the `feat/<slug>` fork (owner: supervisor).
///
/// # Provenance fields (`floor-capture-hardening-round-2` item 5 / F10)
///
/// `r#ref` is a **mutable** ref string (`feat/<slug>@fork`) — a force-push can
/// re-point it. The floor therefore also records the pinned `commit_oid` the ref
/// resolved to at capture time, the `toolchain` fingerprint the snapshot was
/// captured with, and `enumerated_targets_hash` (F7). The evaluator compares all
/// of these — not just the two content hashes — so a spec-node cannot smuggle a
/// baseline captured at a different commit, under a different toolchain, or over
/// a narrowed target set than the one the supervisor gates against.
///
/// As of schema v3 ([`PROVENANCE_REQUIRED_SCHEMA`]) all three are **required**:
/// they carry no `#[serde(default)]`, so a document missing one fails to
/// deserialize ([`PlanValidationError::Malformed`]), and [`validate_plan`]
/// additionally rejects an empty / whitespace-only value
/// ([`PlanValidationError::EmptyString`]) — the same two-layer treatment the
/// other required baseline strings (`ref`, the two content hashes) get. This is
/// the structural half of the fail-closed provenance guard; the evaluator
/// (`verify_plan_baseline`) is the runtime half that additionally checks the
/// values *match* the live snapshot. A security oracle treats "no evidence" as
/// a rejection, not a match — so the plan may not even omit the evidence.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Baseline {
    /// Git ref the snapshot was taken at (e.g. `feat/<slug>@fork`) — mutable,
    /// display/audit only; `commit_oid` is the authoritative binding.
    pub r#ref: String,
    /// The ref resolved to an immutable commit OID at capture time (provenance).
    /// Required as of v3.
    pub commit_oid: String,
    /// `rustc -V` fingerprint the snapshot was captured with (provenance).
    /// Required as of v3.
    pub toolchain: String,
    /// Hash of the passing-test list at baseline (floor: no baseline pass may
    /// regress).
    pub test_passlist_hash: String,
    /// Hash of the clippy-warning list at baseline (floor: no new warnings).
    pub clippy_warnings_hash: String,
    /// Hash of the enumerated `(package, target_kind, target)` test-target set at
    /// baseline (floor F7: the tip's set must be a superset — a shrink fails
    /// closed). Required as of v3.
    pub enumerated_targets_hash: String,
    /// Unrecognized keys, captured for the compatibility check.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// A whole-feature acceptance criterion — an executable `check` or an
/// LLM-judged `assertion`. Internally tagged on `kind`, so an unknown `kind`
/// fails deserialization (surfaced as [`PlanValidationError::Malformed`]).
///
/// `deny_unknown_fields` makes an undeclared key inside a variant (e.g. a
/// `run` on an `assertion`, or a stray `budget` on a `check`) a hard
/// deserialization error, matching the JSON Schema's `additionalProperties:
/// false` on each acceptance variant. Acceptance items therefore have **no
/// additive-optional seam** in v3 — the same stance the schema takes; a future
/// minor that needs one would move to a captured-`extra` shape (as the
/// [`Chunk`]/[`Check`] structs use) under governed evolution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Acceptance {
    /// An executable end-to-end check (`desc` + shell/test `run`, with optional
    /// `cwd` / `expect_exit` precision — same flexible shape as [`Check`]).
    Check {
        /// The general goal of the check — what it verifies.
        desc: String,
        /// A flexible shell command the supervisor executes.
        run: String,
        /// Optional working directory (repo-relative) to run `run` in.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cwd: Option<String>,
        /// Optional expected exit code (absent = exit 0).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expect_exit: Option<i32>,
    },
    /// An LLM-judged criterion (no executable command).
    Assertion {
        /// Human-readable description of the asserted property.
        desc: String,
    },
}

impl Acceptance {
    /// True for the executable [`Acceptance::Check`] arm.
    #[must_use]
    pub fn is_check(&self) -> bool {
        matches!(self, Acceptance::Check { .. })
    }
}

/// One implementation chunk (owner: spec).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Chunk {
    /// Unique id within the plan; referenced by other chunks' `deps`.
    pub id: String,
    /// Short human-readable title.
    pub title: String,
    /// Ids of chunks this one depends on (the DAG edges).
    #[serde(default)]
    pub deps: Vec<String>,
    /// Starting model-tier hint; the orchestrator owns promotion.
    pub tier: Tier,
    /// Turnkey, self-contained implementation brief.
    pub brief: String,
    /// Repo-relative files this chunk may touch — a merge-time constraint, not
    /// just a hint.
    pub files_touched: Vec<String>,
    /// Executable per-chunk checks (`desc` + `run`); at least one required.
    pub checks: Vec<Check>,
    /// LLM-judged criteria, additive above the deterministic floor.
    #[serde(default)]
    pub assertions: Vec<String>,
    /// If true, the supervisor blocks a merge that added/modified no tests.
    #[serde(default)]
    pub requires_tests: bool,
    /// Unrecognized keys, captured for the compatibility check.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// An executable check: the general goal plus a flexible runnable form that
/// proves it. The goal (`desc`) is always communicated and the command (`run`)
/// is a free-form shell string; precision (`cwd`, `expect_exit`) is available
/// but not forced (owner decision 2026-07-23, `plan-check-run-contract`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Check {
    /// The general goal of the check — what it verifies. Always present,
    /// human- and LLM-readable.
    pub desc: String,
    /// A flexible shell command the supervisor executes (via `sh -c`).
    pub run: String,
    /// Optional working directory (repo-relative) to run `run` in; when absent
    /// the check runs at the worktree root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// Optional expected exit code — the check passes iff the command exits with
    /// this code. Absent means the default: exit 0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expect_exit: Option<i32>,
    /// Unrecognized keys, captured for the compatibility check.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// Model-tier hint for a chunk. Serialized as its lowercase wire name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Tier {
    /// Cheapest tier — turnkey briefs, no architectural reasoning.
    Code,
    /// Mid tier.
    Mid,
    /// Highest tier — reserved for the hardest chunks / promotions.
    High,
}

impl Tier {
    /// The lowercase wire name serde (de)serializes this tier as.
    #[must_use]
    pub const fn wire_name(self) -> &'static str {
        match self {
            Tier::Code => "code",
            Tier::Mid => "mid",
            Tier::High => "high",
        }
    }

    /// Every tier's wire name, in declaration order — the single source of
    /// truth for "the set of accepted tiers" (mirrors [`crate::schema::Kind`]).
    pub const WIRE_NAMES: &'static [&'static str] = &[
        Tier::Code.wire_name(),
        Tier::Mid.wire_name(),
        Tier::High.wire_name(),
    ];
}

/// A `plan.json` document failed schema validation.
///
/// Every variant names one violation. The CLI renders these as a
/// `schema_violation` error; [`PlanValidationError::expected`] supplies the
/// machine-readable `expected` hint for the variants that carry one, mirroring
/// [`crate::report::ReportValidationError`].
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum PlanValidationError {
    /// The document root was not a JSON object.
    #[error("plan must be a JSON object")]
    NotObject,

    /// The required `schema_version` field was absent.
    #[error("plan missing required field `schema_version`")]
    SchemaVersionMissing,

    /// `schema_version` was present but not a non-negative integer.
    #[error("field `schema_version` must be a non-negative integer")]
    SchemaVersionNotInt,

    /// `schema_version` declared a major this build does not support.
    #[error("unsupported plan schema_version {found} (supported: {supported:?})")]
    UnsupportedSchemaVersion {
        /// The `schema_version` value read from the document.
        found: u64,
        /// The majors this build accepts (see [`SUPPORTED_PLAN_SCHEMAS`]).
        supported: Vec<u32>,
    },

    /// The document is a supported version but does not match the v3 shape
    /// (missing required field, wrong type, unknown acceptance `kind`, unknown
    /// `tier`, …). Carries the underlying serde message.
    #[error("plan is malformed: {message}")]
    Malformed {
        /// The serde deserialization message.
        message: String,
    },

    /// An undeclared field appeared and is not in [`TOLERATED_OPTIONAL_FIELDS`].
    #[error("unknown field `{field}` at {path} (not a tolerated additive optional field)")]
    UnknownField {
        /// Dotted path to the object carrying the unknown key.
        path: String,
        /// The offending field name.
        field: String,
    },

    /// A required string field was empty (or whitespace-only).
    #[error("field `{path}` must be a non-empty string")]
    EmptyString {
        /// Dotted path to the offending field.
        path: String,
    },

    /// `acceptance[]` was empty.
    #[error("`acceptance` must contain at least one item")]
    AcceptanceEmpty,

    /// `acceptance[]` contained no executable `check` (only assertions).
    #[error("`acceptance` must contain at least one executable check (not all assertions)")]
    AcceptanceNoCheck,

    /// `chunks[]` was empty.
    #[error("`chunks` must contain at least one chunk")]
    ChunksEmpty,

    /// A chunk id was empty or used characters outside `[A-Za-z0-9_.-]` (with a
    /// leading alphanumeric). Chunk ids must be safe to reference and log.
    #[error("chunk id {id:?} is invalid: expected {expected}")]
    InvalidChunkId {
        /// The offending id.
        id: String,
        /// Accepted-shape hint.
        expected: &'static str,
    },

    /// Two chunks shared an id.
    #[error("duplicate chunk id {id:?}")]
    DuplicateChunkId {
        /// The repeated id.
        id: String,
    },

    /// A chunk's `deps` referenced an id that no chunk defines.
    #[error("chunk {chunk:?} depends on unknown chunk {dep:?}")]
    UnknownDep {
        /// The depending chunk.
        chunk: String,
        /// The dangling dependency id.
        dep: String,
    },

    /// A chunk listed the same dependency more than once.
    #[error("chunk {chunk:?} lists duplicate dependency {dep:?}")]
    DuplicateDep {
        /// The depending chunk.
        chunk: String,
        /// The repeated dependency id.
        dep: String,
    },

    /// The dependency graph contained a cycle.
    #[error("chunk dependency graph has a cycle: {}", cycle.join(" -> "))]
    DependencyCycle {
        /// The chunk ids forming the cycle, in order, with the entry id
        /// repeated at the end (e.g. `["c1", "c2", "c1"]`).
        cycle: Vec<String>,
    },

    /// A chunk declared no executable `check`.
    #[error("chunk {chunk:?} must have at least one check")]
    ChunkNoCheck {
        /// The offending chunk id.
        chunk: String,
    },

    /// A chunk declared no `files_touched` entries.
    #[error("chunk {chunk:?} must declare at least one file in `files_touched`")]
    ChunkNoFiles {
        /// The offending chunk id.
        chunk: String,
    },

    /// A `files_touched` entry was not a safe repo-relative path.
    #[error("path {path:?} in chunk {chunk:?} is not a safe repo-relative path (no absolute paths, `~`, `\\`, `:`, control chars, or `.`/`..`/empty components)")]
    UnsafePath {
        /// The offending chunk id.
        chunk: String,
        /// The offending path.
        path: String,
    },

    /// A check's optional `cwd` was not a safe repo-relative directory. Held to
    /// the same lexical guard as `files_touched` (`is_safe_repo_relative`) —
    /// `cwd` controls *where a shell command executes*, so an absolute path
    /// (`/etc`) or a `..`/`~` traversal would let a check escape the worktree the
    /// floor gates. Absence already means "the worktree root", so a bare `.` is
    /// rejected too — there is one spelling for root, not two.
    #[error("cwd {path:?} at {location} is not a safe repo-relative directory (no absolute paths, `~`, `\\`, `:`, control chars, or `.`/`..`/empty components; omit `cwd` for the worktree root)")]
    UnsafeCwd {
        /// Dotted path to the offending `cwd` (e.g. `chunks[c1].checks[0].cwd`).
        location: String,
        /// The offending path.
        path: String,
    },

    /// A check's optional `expect_exit` was outside the range a `sh -c` process
    /// can actually report. A shell exit status is `0..=255`; a value outside it
    /// (negative, or `> 255`) could never match `code()` and would make the check
    /// permanently un-passable, so it is rejected at validation rather than
    /// silently failing every run.
    #[error("expect_exit {value} at {location} is out of range (a shell exit status is 0..=255)")]
    ExpectExitOutOfRange {
        /// Dotted path to the offending `expect_exit`.
        location: String,
        /// The offending value.
        value: i64,
    },
}

impl PlanValidationError {
    /// The machine-readable `expected` hint for this error, if any — mirrors
    /// [`crate::report::ReportValidationError::expected`] so the CLI can attach
    /// the same structured payload.
    #[must_use]
    pub fn expected(&self) -> Option<Value> {
        match self {
            Self::SchemaVersionMissing | Self::SchemaVersionNotInt => {
                Some(serde_json::json!({"field": "schema_version", "type": "integer"}))
            }
            Self::UnsupportedSchemaVersion { supported, .. } => {
                Some(serde_json::json!({"field": "schema_version", "supported": supported}))
            }
            Self::UnknownField { .. } => {
                Some(serde_json::json!({"tolerated_optional": TOLERATED_OPTIONAL_FIELDS}))
            }
            _ => None,
        }
    }
}

/// Parse a raw JSON value as a `plan.json` v3 document and validate it.
///
/// The two-phase entry point the supervisor/spec-node use. It gates the version
/// *before* deserializing into the typed shape, so a future/unknown major yields
/// a clean [`PlanValidationError::UnsupportedSchemaVersion`] instead of a
/// confusing shape mismatch. On success the returned [`Plan`] has passed every
/// structural rule in [`validate_plan`].
///
/// # Errors
///
/// Returns the first [`PlanValidationError`] found.
pub fn parse_and_validate_plan(raw: &Value) -> Result<Plan, PlanValidationError> {
    let obj = raw.as_object().ok_or(PlanValidationError::NotObject)?;

    // Gate the version first, from the raw value, so an unsupported major is a
    // version error rather than a shape error.
    let version = obj
        .get("schema_version")
        .ok_or(PlanValidationError::SchemaVersionMissing)?;
    let version = version
        .as_u64()
        .ok_or(PlanValidationError::SchemaVersionNotInt)?;
    check_supported_version(version)?;

    // Deserialize into the typed shape. Missing required fields, wrong types,
    // an unknown acceptance `kind`, and an unknown `tier` all fail here.
    let plan: Plan =
        serde_json::from_value(raw.clone()).map_err(|e| PlanValidationError::Malformed {
            message: e.to_string(),
        })?;

    validate_plan(&plan)?;
    Ok(plan)
}

/// Reject a `schema_version` value whose major is not in
/// [`SUPPORTED_PLAN_SCHEMAS`]. Shared by the raw-`Value` gate in
/// [`parse_and_validate_plan`] and the typed re-check in [`validate_plan`], so
/// neither entry point can admit an unsupported major.
fn check_supported_version(version: u64) -> Result<(), PlanValidationError> {
    if u32::try_from(version).is_ok_and(|v| SUPPORTED_PLAN_SCHEMAS.contains(&v)) {
        Ok(())
    } else {
        Err(PlanValidationError::UnsupportedSchemaVersion {
            found: version,
            supported: SUPPORTED_PLAN_SCHEMAS.to_vec(),
        })
    }
}

/// Structural validation of an already-deserialized [`Plan`].
///
/// Enforces every rule the deserializer cannot (design.md §4, §13): no
/// undeclared fields, non-empty required strings, unique chunk ids, resolvable
/// and acyclic `deps`, at least one executable check per chunk and in
/// `acceptance[]`, and safe repo-relative `files_touched` paths. Split out from
/// [`parse_and_validate_plan`] so a caller holding a typed `Plan` (e.g. one it
/// just built) can re-check it without re-serializing.
///
/// # Errors
///
/// Returns the first [`PlanValidationError`] found.
pub fn validate_plan(plan: &Plan) -> Result<(), PlanValidationError> {
    // Re-gate the version: `validate_plan` is a public entry point, and a `Plan`
    // built directly or deserialized without the raw gate could carry an
    // unsupported major. Without this, a caller re-checking a typed plan (as the
    // doc invites) could admit an unsupported `schema_version` (e.g. `4`).
    check_supported_version(u64::from(plan.schema_version))?;

    // --- undeclared-field rejection (compatibility semantics) ---
    reject_unknown_fields(&plan.extra, ObjectShape::Plan)?;
    reject_unknown_fields(&plan.feature.extra, ObjectShape::Feature)?;
    reject_unknown_fields(&plan.baseline.extra, ObjectShape::Baseline)?;

    // --- required non-empty strings ---
    non_empty(&plan.feature.slug, "feature.slug")?;
    non_empty(&plan.feature.source_branch, "feature.source_branch")?;
    non_empty(
        &plan.feature.integration_branch,
        "feature.integration_branch",
    )?;
    non_empty(&plan.baseline.r#ref, "baseline.ref")?;
    non_empty(
        &plan.baseline.test_passlist_hash,
        "baseline.test_passlist_hash",
    )?;
    non_empty(
        &plan.baseline.clippy_warnings_hash,
        "baseline.clippy_warnings_hash",
    )?;

    // --- baseline provenance required (v3 / PROVENANCE_REQUIRED_SCHEMA) ---
    // At v3 and above the three provenance fields are structurally required.
    // A missing field already failed deserialization (they carry no serde
    // default); this rejects an empty / whitespace-only value with a per-field
    // error, closing the "present but blank" hole a security oracle must not
    // treat as evidence. Presence + non-blankness only — the OID/toolchain
    // *shape* and value *match* are the runtime gate's job (`verify_plan_baseline`).
    //
    // The version gate below is effectively unconditional today: the
    // `check_supported_version` guard above admits only majors in
    // `SUPPORTED_PLAN_SCHEMAS` (`[3]`), all `>= PROVENANCE_REQUIRED_SCHEMA`. The
    // `debug_assert` pins that so a future maintainer who widens the supported
    // set to re-admit an older major is forced to revisit this gate (that major
    // would also need its own wire type — these fields have no serde default).
    debug_assert!(
        plan.schema_version >= PROVENANCE_REQUIRED_SCHEMA,
        "supported majors must all require provenance; \
         a lower major needs its own wire type, not a skipped gate"
    );
    if plan.schema_version >= PROVENANCE_REQUIRED_SCHEMA {
        non_empty(&plan.baseline.commit_oid, "baseline.commit_oid")?;
        non_empty(&plan.baseline.toolchain, "baseline.toolchain")?;
        non_empty(
            &plan.baseline.enumerated_targets_hash,
            "baseline.enumerated_targets_hash",
        )?;
    }

    // --- acceptance: non-empty, ≥1 executable check ---
    if plan.acceptance.is_empty() {
        return Err(PlanValidationError::AcceptanceEmpty);
    }
    for (i, item) in plan.acceptance.iter().enumerate() {
        match item {
            Acceptance::Check {
                desc,
                run,
                cwd,
                expect_exit,
            } => {
                non_empty(desc, &format!("acceptance[{i}].desc"))?;
                non_empty(run, &format!("acceptance[{i}].run"))?;
                validate_check_precision(
                    cwd.as_deref(),
                    *expect_exit,
                    &format!("acceptance[{i}]"),
                )?;
            }
            Acceptance::Assertion { desc } => {
                non_empty(desc, &format!("acceptance[{i}].desc"))?;
            }
        }
    }
    if !plan.acceptance.iter().any(Acceptance::is_check) {
        return Err(PlanValidationError::AcceptanceNoCheck);
    }

    // --- chunks: non-empty, unique ids, per-chunk rules ---
    if plan.chunks.is_empty() {
        return Err(PlanValidationError::ChunksEmpty);
    }
    let mut ids: HashSet<&str> = HashSet::with_capacity(plan.chunks.len());
    for chunk in &plan.chunks {
        validate_chunk_id(&chunk.id)?;
        if !ids.insert(chunk.id.as_str()) {
            return Err(PlanValidationError::DuplicateChunkId {
                id: chunk.id.clone(),
            });
        }
    }
    for chunk in &plan.chunks {
        validate_chunk(chunk, &ids)?;
    }

    // --- deps resolvable + DAG acyclic (over the whole graph) ---
    detect_cycle(&plan.chunks)?;

    Ok(())
}

/// Reject any key in `extra` not on `shape`'s [`tolerated_fields`] allowlist —
/// the per-object-shape compatibility check. `path` overrides `shape.label()`
/// when the caller can name the concrete location (e.g. `chunks[c1]`).
fn reject_unknown_fields_at(
    extra: &Map<String, Value>,
    shape: ObjectShape,
    path: &str,
) -> Result<(), PlanValidationError> {
    let allow = tolerated_fields(shape);
    if let Some((field, _)) = extra.iter().find(|(k, _)| !allow.contains(&k.as_str())) {
        return Err(PlanValidationError::UnknownField {
            path: path.to_string(),
            field: field.clone(),
        });
    }
    Ok(())
}

/// [`reject_unknown_fields_at`] using the shape's own label as the error path —
/// for the fixed-location shapes (`Plan`, `feature`, `baseline`).
fn reject_unknown_fields(
    extra: &Map<String, Value>,
    shape: ObjectShape,
) -> Result<(), PlanValidationError> {
    reject_unknown_fields_at(extra, shape, shape.label())
}

/// Reject an empty / whitespace-only required string.
fn non_empty(s: &str, path: &str) -> Result<(), PlanValidationError> {
    if s.trim().is_empty() {
        return Err(PlanValidationError::EmptyString {
            path: path.to_string(),
        });
    }
    Ok(())
}

/// The highest exit status a `sh -c` process can report; a shell truncates the
/// wait status to `0..=255` (a signalled child surfaces as `128 + signal`), so
/// an `expect_exit` outside this range can never match and is rejected.
const MAX_SHELL_EXIT: i32 = 255;

/// Validate a check's optional precision fields (`cwd`, `expect_exit`) — shared
/// by the per-chunk `checks[]` and `acceptance[]` check paths so the two never
/// diverge. `location` is the dotted path to the check (e.g.
/// `chunks[c1].checks[0]` or `acceptance[0]`); the field name is appended here.
///
/// - `cwd`, when present, must be a non-empty *safe repo-relative* directory —
///   the same lexical guard `files_touched` gets ([`is_safe_repo_relative`]),
///   because `cwd` chooses where a shell command runs and an unchecked `/etc` or
///   `../..` would escape the worktree the floor gates. Absence already means the
///   worktree root, so a bare `.` is rejected (one spelling for root).
/// - `expect_exit`, when present, must be a real shell exit status (`0..=255`).
fn validate_check_precision(
    cwd: Option<&str>,
    expect_exit: Option<i32>,
    location: &str,
) -> Result<(), PlanValidationError> {
    if let Some(cwd) = cwd {
        non_empty(cwd, &format!("{location}.cwd"))?;
        if !is_safe_repo_relative(cwd) {
            return Err(PlanValidationError::UnsafeCwd {
                location: format!("{location}.cwd"),
                path: cwd.to_string(),
            });
        }
    }
    if let Some(code) = expect_exit {
        if !(0..=MAX_SHELL_EXIT).contains(&code) {
            return Err(PlanValidationError::ExpectExitOutOfRange {
                location: format!("{location}.expect_exit"),
                value: i64::from(code),
            });
        }
    }
    Ok(())
}

/// Chunk-id shape hint shared by every rejection.
const CHUNK_ID_EXPECTED: &str = "a non-empty id of `[A-Za-z0-9_.-]` starting with an alphanumeric";

/// Validate a chunk id: non-empty, leading alphanumeric, body limited to
/// `[A-Za-z0-9_.-]`. Keeps ids safe to reference in errors, logs, and any
/// future path derived from them (no `/`, `..`, or leading dot).
fn validate_chunk_id(id: &str) -> Result<(), PlanValidationError> {
    let ok = {
        let mut chars = id.chars();
        chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
            && id
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
    };
    if ok {
        Ok(())
    } else {
        Err(PlanValidationError::InvalidChunkId {
            id: id.to_string(),
            expected: CHUNK_ID_EXPECTED,
        })
    }
}

/// Per-chunk structural rules (unknown fields, non-empty strings, ≥1 check,
/// declared + safe `files_touched`, resolvable + unique `deps`, non-empty
/// assertions).
fn validate_chunk(chunk: &Chunk, ids: &HashSet<&str>) -> Result<(), PlanValidationError> {
    reject_unknown_fields_at(
        &chunk.extra,
        ObjectShape::Chunk,
        &format!("chunks[{}]", chunk.id),
    )?;
    non_empty(&chunk.title, &format!("chunks[{}].title", chunk.id))?;
    non_empty(&chunk.brief, &format!("chunks[{}].brief", chunk.id))?;

    // deps must resolve to a real chunk (cycles are caught separately) and must
    // not repeat — a duplicate edge is malformed and skews any indegree-based
    // scheduler (a dependent counted twice can never unblock).
    let mut seen_deps: HashSet<&str> = HashSet::with_capacity(chunk.deps.len());
    for dep in &chunk.deps {
        if !ids.contains(dep.as_str()) {
            return Err(PlanValidationError::UnknownDep {
                chunk: chunk.id.clone(),
                dep: dep.clone(),
            });
        }
        if !seen_deps.insert(dep.as_str()) {
            return Err(PlanValidationError::DuplicateDep {
                chunk: chunk.id.clone(),
                dep: dep.clone(),
            });
        }
    }

    // ≥1 executable check.
    if chunk.checks.is_empty() {
        return Err(PlanValidationError::ChunkNoCheck {
            chunk: chunk.id.clone(),
        });
    }
    for (i, check) in chunk.checks.iter().enumerate() {
        reject_unknown_fields_at(
            &check.extra,
            ObjectShape::Check,
            &format!("chunks[{}].checks[{i}]", chunk.id),
        )?;
        non_empty(
            &check.desc,
            &format!("chunks[{}].checks[{i}].desc", chunk.id),
        )?;
        non_empty(&check.run, &format!("chunks[{}].checks[{i}].run", chunk.id))?;
        validate_check_precision(
            check.cwd.as_deref(),
            check.expect_exit,
            &format!("chunks[{}].checks[{i}]", chunk.id),
        )?;
    }

    // assertions are LLM-judged criteria — an empty one is nonsensical (mirrors
    // the non-empty check applied to `acceptance[]` items).
    for (i, assertion) in chunk.assertions.iter().enumerate() {
        non_empty(assertion, &format!("chunks[{}].assertions[{i}]", chunk.id))?;
    }

    // files_touched: declared + safe repo-relative.
    if chunk.files_touched.is_empty() {
        return Err(PlanValidationError::ChunkNoFiles {
            chunk: chunk.id.clone(),
        });
    }
    for path in &chunk.files_touched {
        if !is_safe_repo_relative(path) {
            return Err(PlanValidationError::UnsafePath {
                chunk: chunk.id.clone(),
                path: path.clone(),
            });
        }
    }

    Ok(())
}

/// True iff `p` is a safe repo-relative path. This is a **lexical** guard
/// (mirroring the crate's id-level path-traversal stance in `schema.rs`) applied
/// to multi-component paths — it is deliberately platform-independent, because a
/// plan may be written on one OS and consumed on another. It is NOT a
/// filesystem-resolution guarantee: a lexically-safe path can still resolve
/// outside the repo through a symlinked directory, so the supervisor's actual
/// merge-scope enforcement must not rely on this alone.
///
/// Rejects: empty; absolute (`/…`); `~` home-expansion; backslash (`\`, a
/// Windows separator — kills `\\server\share` too); a `:` anywhere (kills
/// Windows drive/`C:foo` and drive-absolute `C:/…`); any control character
/// (NUL, `\n`, `\r`, `\t` — legal in some filenames but log-poisoning and
/// adversarial); and any component that is empty (`a//b`), whitespace-only,
/// `.` (`a/./b` — a non-canonical form that would defeat file-scope matching),
/// or `..` (traversal).
fn is_safe_repo_relative(p: &str) -> bool {
    if p.is_empty()
        || p.starts_with('/')
        || p.starts_with('~')
        || p.contains('\\')
        || p.contains(':')
        || p.chars().any(char::is_control)
    {
        return false;
    }
    p.split('/')
        .all(|comp| !comp.trim().is_empty() && comp != "." && comp != "..")
}

/// Detect a cycle (or a self-loop) in the chunk dependency graph via a
/// three-colour DFS. On a back-edge to a node still on the DFS stack, returns
/// [`PlanValidationError::DependencyCycle`] with the cycle path (entry id
/// repeated at the end). Assumes every `deps` entry already resolves to a real
/// chunk (checked by [`validate_chunk`]).
fn detect_cycle(chunks: &[Chunk]) -> Result<(), PlanValidationError> {
    #[derive(Clone, Copy, PartialEq)]
    enum Colour {
        White,
        Grey,
        Black,
    }

    let adj: HashMap<&str, &[String]> = chunks
        .iter()
        .map(|c| (c.id.as_str(), c.deps.as_slice()))
        .collect();
    let mut colour: HashMap<&str, Colour> = chunks
        .iter()
        .map(|c| (c.id.as_str(), Colour::White))
        .collect();

    // Iterative DFS with an explicit stack of (node, next-dep-index) so a deep
    // or wide graph cannot blow the call stack. `path` mirrors the grey stack
    // for cycle reconstruction.
    for start in chunks.iter().map(|c| c.id.as_str()) {
        if colour[start] != Colour::White {
            continue;
        }
        let mut stack: Vec<(&str, usize)> = vec![(start, 0)];
        let mut path: Vec<&str> = vec![start];
        colour.insert(start, Colour::Grey);

        while let Some(&mut (node, ref mut idx)) = stack.last_mut() {
            let deps = adj[node];
            if *idx < deps.len() {
                let dep = deps[*idx].as_str();
                *idx += 1;
                match colour[dep] {
                    Colour::White => {
                        colour.insert(dep, Colour::Grey);
                        stack.push((dep, 0));
                        path.push(dep);
                    }
                    Colour::Grey => {
                        // Back-edge: `dep` is an ancestor on the current path.
                        let from = path.iter().position(|&n| n == dep).unwrap_or(0);
                        let mut cycle: Vec<String> =
                            path[from..].iter().map(|s| (*s).to_string()).collect();
                        cycle.push(dep.to_string());
                        return Err(PlanValidationError::DependencyCycle { cycle });
                    }
                    Colour::Black => {}
                }
            } else {
                colour.insert(node, Colour::Black);
                stack.pop();
                path.pop();
            }
        }
    }
    Ok(())
}

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

    /// The canonical valid plan — the `plan-schema.md` example, kept in sync
    /// with the checked-in `schemas/plan.v3.example.json` by
    /// `checked_in_example_is_valid`.
    fn valid_plan() -> Value {
        serde_json::from_str(include_str!("../schemas/plan.v3.example.json")).unwrap()
    }

    // --- valid ---

    #[test]
    fn example_plan_validates() {
        let plan = parse_and_validate_plan(&valid_plan()).expect("example must validate");
        assert_eq!(plan.schema_version, PLAN_SCHEMA_VERSION);
        assert_eq!(plan.chunks.len(), 2);
        assert_eq!(plan.chunks[1].deps, vec!["c1".to_string()]);
        assert!(plan.chunks[0].requires_tests);
    }

    #[test]
    fn checked_in_example_is_valid() {
        // The example artifact and the doc example are one and the same; if the
        // artifact drifts out of the v3 shape this fails.
        let raw: Value = serde_json::from_str(PLAN_V3_EXAMPLE).unwrap();
        assert!(parse_and_validate_plan(&raw).is_ok());
    }

    /// A minimal but complete v3 baseline block — all required strings present
    /// and non-empty, including the three provenance fields. Shared by the
    /// inline-fixture tests that don't start from [`valid_plan`].
    fn minimal_baseline() -> Value {
        json!({
            "ref": "feat/f@fork",
            "commit_oid": "0123456789abcdef0123456789abcdef01234567",
            "toolchain": "rustc 1.97.1 (abcdef012 2026-06-01)",
            "test_passlist_hash": "sha256:a",
            "clippy_warnings_hash": "sha256:b",
            "enumerated_targets_hash": "sha256:c"
        })
    }

    #[test]
    fn minimal_valid_plan() {
        let v = json!({
            "schema_version": 3,
            "plan_rev": 1,
            "intent_rev": 1,
            "feature": {"slug": "f", "source_branch": "main", "integration_branch": "feat/f"},
            "baseline": minimal_baseline(),
            "acceptance": [{"kind": "check", "desc": "e2e", "run": "cargo test"}],
            "chunks": [{
                "id": "c1", "title": "t", "tier": "code", "brief": "b",
                "files_touched": ["src/a.rs"],
                "checks": [{"desc": "d", "run": "cargo test a"}]
            }],
        });
        assert!(parse_and_validate_plan(&v).is_ok());
    }

    #[test]
    fn round_trips_through_serde() {
        let plan = parse_and_validate_plan(&valid_plan()).unwrap();
        let reser = serde_json::to_value(&plan).unwrap();
        let again = parse_and_validate_plan(&reser).unwrap();
        assert_eq!(plan, again);
    }

    // --- version gating ---

    #[test]
    fn unsupported_major_rejected() {
        let mut v = valid_plan();
        v["schema_version"] = json!(4);
        let err = parse_and_validate_plan(&v).unwrap_err();
        assert!(matches!(
            err,
            PlanValidationError::UnsupportedSchemaVersion { found: 4, .. }
        ));
        assert_eq!(
            err.expected(),
            Some(json!({"field": "schema_version", "supported": [3]}))
        );
    }

    #[test]
    fn v2_major_now_unsupported() {
        // v2 is deliberately dropped from SUPPORTED_PLAN_SCHEMAS: a v2 plan
        // carries optional-by-default provenance and cannot satisfy the v3
        // requirement, so it is rejected up front as an unsupported major.
        let mut v = valid_plan();
        v["schema_version"] = json!(2);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::UnsupportedSchemaVersion { found: 2, .. }
        ));
    }

    #[test]
    fn genuine_v2_document_rejected_at_version_gate_not_shape() {
        // A *real* v2 document — v2 shape, no provenance fields at all — is
        // rejected at the raw version gate (UnsupportedSchemaVersion), never
        // reaching deserialization. This pins the design choice: v2 is refused by
        // major, so its missing provenance never surfaces as a shape/Malformed
        // error. (Regression guard for the "reject at version, not at shape"
        // decision — a v2 plan would otherwise be a confusing missing-field error.)
        let v = json!({
            "schema_version": 2, "plan_rev": 1, "intent_rev": 1,
            "feature": {"slug": "f", "source_branch": "main", "integration_branch": "feat/f"},
            "baseline": {"ref": "feat/f@fork", "test_passlist_hash": "h", "clippy_warnings_hash": "h"},
            "acceptance": [{"kind": "check", "desc": "e2e", "run": "cargo test"}],
            "chunks": [{
                "id": "c1", "title": "t", "tier": "code", "brief": "b",
                "files_touched": ["src/a.rs"],
                "checks": [{"desc": "d", "run": "cargo test a"}]
            }],
        });
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::UnsupportedSchemaVersion { found: 2, .. }
        ));
    }

    #[test]
    fn missing_version_rejected() {
        let mut v = valid_plan();
        v.as_object_mut().unwrap().remove("schema_version");
        assert_eq!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::SchemaVersionMissing
        );
    }

    #[test]
    fn non_integer_version_rejected() {
        let mut v = valid_plan();
        v["schema_version"] = json!("2");
        assert_eq!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::SchemaVersionNotInt
        );
    }

    #[test]
    fn validate_plan_regates_version_on_typed_plan() {
        // A typed `Plan` that bypassed the raw gate (built directly, or mutated
        // after deserialization) must still be rejected by `validate_plan` —
        // otherwise the "re-check a typed plan" path admits an unsupported major.
        let mut plan = parse_and_validate_plan(&valid_plan()).unwrap();
        plan.schema_version = 4;
        assert!(matches!(
            validate_plan(&plan).unwrap_err(),
            PlanValidationError::UnsupportedSchemaVersion { found: 4, .. }
        ));
    }

    // --- unknown fields ---

    #[test]
    fn unknown_top_level_field_rejected() {
        let mut v = valid_plan();
        v["budget"] = json!(1000);
        let err = parse_and_validate_plan(&v).unwrap_err();
        assert!(matches!(
            err,
            PlanValidationError::UnknownField { ref field, .. } if field == "budget"
        ));
    }

    #[test]
    fn unknown_chunk_field_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["retries"] = json!(3);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::UnknownField { field, .. } if field == "retries"
        ));
    }

    // --- malformed (deserialize-time) ---

    #[test]
    fn unknown_acceptance_kind_rejected() {
        let mut v = valid_plan();
        v["acceptance"][0]["kind"] = json!("gut-feeling");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::Malformed { .. }
        ));
    }

    #[test]
    fn unknown_tier_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["tier"] = json!("ultra");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::Malformed { .. }
        ));
    }

    #[test]
    fn missing_required_chunk_field_rejected() {
        let mut v = valid_plan();
        v["chunks"][0].as_object_mut().unwrap().remove("brief");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::Malformed { .. }
        ));
    }

    #[test]
    fn non_object_root_rejected() {
        assert_eq!(
            parse_and_validate_plan(&json!([1, 2, 3])).unwrap_err(),
            PlanValidationError::NotObject
        );
    }

    // --- acceptance rules ---

    #[test]
    fn acceptance_all_assertions_rejected() {
        let mut v = valid_plan();
        v["acceptance"] = json!([{"kind": "assertion", "desc": "vibes"}]);
        assert_eq!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::AcceptanceNoCheck
        );
    }

    #[test]
    fn acceptance_empty_rejected() {
        let mut v = valid_plan();
        v["acceptance"] = json!([]);
        assert_eq!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::AcceptanceEmpty
        );
    }

    #[test]
    fn acceptance_check_unknown_field_rejected() {
        // The tagged `Acceptance` enum uses `deny_unknown_fields`, so a stray
        // key inside a variant fails at deserialize time (Malformed), matching
        // the JSON Schema's `additionalProperties: false`. This is the fix for
        // the silent-drop divergence all reviewers flagged.
        let mut v = valid_plan();
        v["acceptance"][0]["budget"] = json!(100);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::Malformed { .. }
        ));
    }

    #[test]
    fn acceptance_assertion_with_run_rejected() {
        // `run` is not a field of the `assertion` variant — reject it rather
        // than silently drop an executable command onto a non-executable item.
        let mut v = valid_plan();
        v["acceptance"] = json!([
            {"kind": "check", "desc": "e2e", "run": "cargo test"},
            {"kind": "assertion", "desc": "x", "run": "rm -rf /"},
        ]);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::Malformed { .. }
        ));
    }

    // --- chunk rules ---

    #[test]
    fn chunk_missing_check_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["checks"] = json!([]);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::ChunkNoCheck { chunk } if chunk == "c1"
        ));
    }

    #[test]
    fn chunk_empty_files_touched_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["files_touched"] = json!([]);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::ChunkNoFiles { chunk } if chunk == "c1"
        ));
    }

    #[test]
    fn duplicate_chunk_id_rejected() {
        let mut v = valid_plan();
        v["chunks"][1]["id"] = json!("c1");
        // dep "c1" still resolves; the duplicate id is what fails.
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::DuplicateChunkId { id } if id == "c1"
        ));
    }

    #[test]
    fn dangling_dep_rejected() {
        let mut v = valid_plan();
        v["chunks"][1]["deps"] = json!(["nope"]);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::UnknownDep { dep, .. } if dep == "nope"
        ));
    }

    #[test]
    fn invalid_chunk_id_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["id"] = json!("../evil");
        // deps still point at "c1"; make c2 independent so the id check fires.
        v["chunks"][1]["deps"] = json!([]);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::InvalidChunkId { .. }
        ));
    }

    #[test]
    fn duplicate_dep_rejected() {
        let mut v = valid_plan();
        v["chunks"][1]["deps"] = json!(["c1", "c1"]);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::DuplicateDep { dep, .. } if dep == "c1"
        ));
    }

    #[test]
    fn empty_chunk_assertion_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["assertions"] = json!(["ok", "   "]);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::EmptyString { path } if path == "chunks[c1].assertions[1]"
        ));
    }

    // --- flexible check shape (desc + run + optional cwd/expect_exit) ---

    #[test]
    fn check_with_cwd_and_expect_exit_validates_and_round_trips() {
        let mut v = valid_plan();
        v["chunks"][0]["checks"] = json!([
            {"desc": "runs in a subdir with a non-zero expected code",
             "run": "make check", "cwd": "crates/x", "expect_exit": 2},
        ]);
        v["acceptance"] = json!([
            {"kind": "check", "desc": "e2e", "run": "cargo test", "cwd": "tests", "expect_exit": 0},
        ]);
        let plan = parse_and_validate_plan(&v).expect("optional check fields must validate");

        // The optional fields land on the typed shape, not in `extra`.
        let check = &plan.chunks[0].checks[0];
        assert_eq!(check.cwd.as_deref(), Some("crates/x"));
        assert_eq!(check.expect_exit, Some(2));
        assert!(check.extra.is_empty());
        assert!(matches!(
            &plan.acceptance[0],
            Acceptance::Check { cwd, expect_exit, .. }
                if cwd.as_deref() == Some("tests") && *expect_exit == Some(0)
        ));

        // Round-trips through serde back to an equal, still-valid plan.
        let reser = serde_json::to_value(&plan).unwrap();
        assert_eq!(parse_and_validate_plan(&reser).unwrap(), plan);
    }

    #[test]
    fn check_without_optional_fields_defaults() {
        // Back-compat: a check with only desc+run parses, leaving the optional
        // precision absent (expect_exit defaults to 0 at execution time). The
        // absent fields skip serialization entirely.
        let plan = parse_and_validate_plan(&valid_plan()).unwrap();
        let check = &plan.chunks[0].checks[0];
        assert_eq!(check.cwd, None);
        assert_eq!(check.expect_exit, None);

        let reser = serde_json::to_value(&plan.chunks[0].checks[0]).unwrap();
        let obj = reser.as_object().unwrap();
        assert!(!obj.contains_key("cwd"));
        assert!(!obj.contains_key("expect_exit"));
    }

    #[test]
    fn empty_check_cwd_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["checks"][0]["cwd"] = json!("  ");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::EmptyString { path } if path == "chunks[c1].checks[0].cwd"
        ));
    }

    #[test]
    fn empty_acceptance_check_cwd_rejected() {
        let mut v = valid_plan();
        v["acceptance"][0]["cwd"] = json!("");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::EmptyString { path } if path == "acceptance[0].cwd"
        ));
    }

    #[test]
    fn non_integer_expect_exit_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["checks"][0]["expect_exit"] = json!("nope");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::Malformed { .. }
        ));
    }

    #[test]
    fn unsafe_check_cwd_rejected() {
        // `cwd` controls where a shell command runs, so it gets the same
        // repo-relative safety guard as `files_touched` — an absolute path or a
        // `..`/`~` traversal would let a check escape the worktree the floor
        // gates. A bare `.` is rejected too: absence already means the root.
        for bad in [
            "/etc",
            "../../outside",
            "a/../../etc",
            "~/secret",
            ".",
            "a\\b",
        ] {
            let mut v = valid_plan();
            v["chunks"][0]["checks"][0]["cwd"] = json!(bad);
            assert!(
                matches!(
                    parse_and_validate_plan(&v).unwrap_err(),
                    PlanValidationError::UnsafeCwd { location, .. }
                        if location == "chunks[c1].checks[0].cwd"
                ),
                "expected UnsafeCwd for chunk cwd {bad:?}"
            );
        }
    }

    #[test]
    fn unsafe_acceptance_check_cwd_rejected() {
        for bad in ["/etc", "../escape", "~/x", "."] {
            let mut v = valid_plan();
            v["acceptance"][0]["cwd"] = json!(bad);
            assert!(
                matches!(
                    parse_and_validate_plan(&v).unwrap_err(),
                    PlanValidationError::UnsafeCwd { location, .. }
                        if location == "acceptance[0].cwd"
                ),
                "expected UnsafeCwd for acceptance cwd {bad:?}"
            );
        }
    }

    #[test]
    fn out_of_range_expect_exit_rejected() {
        // A shell exit status is 0..=255; anything outside can never match
        // `code()` and would make the check permanently un-passable.
        for (loc, patch) in [
            (
                "chunks[c1].checks[0].expect_exit",
                (&["chunks", "0", "checks", "0"][..], -1),
            ),
            (
                "chunks[c1].checks[0].expect_exit",
                (&["chunks", "0", "checks", "0"][..], 256),
            ),
            ("acceptance[0].expect_exit", (&["acceptance", "0"][..], 300)),
        ] {
            let mut v = valid_plan();
            let (path, code) = patch;
            let mut node = &mut v;
            for key in path {
                node = match key.parse::<usize>() {
                    Ok(idx) => &mut node[idx],
                    Err(_) => &mut node[key],
                };
            }
            node["expect_exit"] = json!(code);
            assert!(
                matches!(
                    parse_and_validate_plan(&v).unwrap_err(),
                    PlanValidationError::ExpectExitOutOfRange { location, value }
                        if location == loc && value == i64::from(code)
                ),
                "expected ExpectExitOutOfRange for {loc} = {code}"
            );
        }
    }

    #[test]
    fn boundary_expect_exit_accepted() {
        // 0 and 255 are the inclusive bounds — both valid.
        for code in [0, 255] {
            let mut v = valid_plan();
            v["chunks"][0]["checks"][0]["expect_exit"] = json!(code);
            assert!(
                parse_and_validate_plan(&v).is_ok(),
                "expect_exit {code} should be accepted"
            );
        }
    }

    // --- DAG acyclicity ---

    #[test]
    fn self_loop_rejected() {
        let mut v = valid_plan();
        v["chunks"][0]["deps"] = json!(["c1"]);
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::DependencyCycle { .. }
        ));
    }

    #[test]
    fn two_cycle_rejected() {
        let mut v = valid_plan();
        // c1 -> c2 and c2 -> c1.
        v["chunks"][0]["deps"] = json!(["c2"]);
        v["chunks"][1]["deps"] = json!(["c1"]);
        let err = parse_and_validate_plan(&v).unwrap_err();
        match err {
            PlanValidationError::DependencyCycle { cycle } => {
                assert_eq!(cycle.first(), cycle.last());
                assert!(cycle.contains(&"c1".to_string()));
                assert!(cycle.contains(&"c2".to_string()));
            }
            other => panic!("expected cycle, got {other:?}"),
        }
    }

    #[test]
    fn longer_cycle_rejected() {
        // Three chunks a -> b -> c -> a.
        let v = json!({
            "schema_version": 3, "plan_rev": 1, "intent_rev": 1,
            "feature": {"slug": "f", "source_branch": "main", "integration_branch": "feat/f"},
            "baseline": minimal_baseline(),
            "acceptance": [{"kind": "check", "desc": "e2e", "run": "t"}],
            "chunks": [
                {"id": "a", "title": "t", "tier": "code", "brief": "b", "deps": ["c"], "files_touched": ["x"], "checks": [{"desc": "d", "run": "r"}]},
                {"id": "b", "title": "t", "tier": "code", "brief": "b", "deps": ["a"], "files_touched": ["y"], "checks": [{"desc": "d", "run": "r"}]},
                {"id": "c", "title": "t", "tier": "code", "brief": "b", "deps": ["b"], "files_touched": ["z"], "checks": [{"desc": "d", "run": "r"}]},
            ],
        });
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::DependencyCycle { .. }
        ));
    }

    #[test]
    fn diamond_dag_is_acyclic() {
        // a -> {b, c} -> d is a valid DAG (a shared dep + a join).
        let v = json!({
            "schema_version": 3, "plan_rev": 1, "intent_rev": 1,
            "feature": {"slug": "f", "source_branch": "main", "integration_branch": "feat/f"},
            "baseline": minimal_baseline(),
            "acceptance": [{"kind": "check", "desc": "e2e", "run": "t"}],
            "chunks": [
                {"id": "a", "title": "t", "tier": "code", "brief": "b", "files_touched": ["w"], "checks": [{"desc": "d", "run": "r"}]},
                {"id": "b", "title": "t", "tier": "code", "brief": "b", "deps": ["a"], "files_touched": ["x"], "checks": [{"desc": "d", "run": "r"}]},
                {"id": "c", "title": "t", "tier": "code", "brief": "b", "deps": ["a"], "files_touched": ["y"], "checks": [{"desc": "d", "run": "r"}]},
                {"id": "d", "title": "t", "tier": "code", "brief": "b", "deps": ["b", "c"], "files_touched": ["z"], "checks": [{"desc": "d", "run": "r"}]},
            ],
        });
        assert!(parse_and_validate_plan(&v).is_ok());
    }

    // --- path traversal ---

    #[test]
    fn path_traversal_in_files_touched_rejected() {
        for bad in [
            "../etc/passwd",
            "/abs/path",
            "~/secret",
            "a/../b",
            "a//b",
            "a\\b",
        ] {
            let mut v = valid_plan();
            v["chunks"][0]["files_touched"] = json!([bad]);
            assert!(
                matches!(
                    parse_and_validate_plan(&v).unwrap_err(),
                    PlanValidationError::UnsafePath { .. }
                ),
                "expected UnsafePath for {bad:?}"
            );
        }
    }

    #[test]
    fn safe_paths_accepted() {
        for ok in [
            "src/a.rs",
            "crates/x/src/mod.rs",
            "a.rs",
            "deep/nested/dir/file.txt",
            ".github/workflows/ci.yml", // leading-dot dir is fine; only `.`/`..` components are rejected
        ] {
            assert!(is_safe_repo_relative(ok), "should accept {ok:?}");
        }
        for bad in [
            "",             // empty
            "/x",           // absolute
            "~/x",          // home expansion
            "..",           // traversal
            "a/../b",       // traversal component
            "a//b",         // empty component
            "a\\b",         // backslash separator
            "a/./b",        // non-canonical `.` component
            ".",            // bare `.`
            "C:/Windows",   // windows drive-absolute (colon)
            "C:foo",        // windows drive-relative (colon)
            "src/foo\nbar", // control char (log poisoning)
            "src/foo\tbar", // control char
            "   ",          // whitespace-only
            "a/   /b",      // whitespace-only component
        ] {
            assert!(!is_safe_repo_relative(bad), "should reject {bad:?}");
        }
    }

    // --- empty required strings ---

    #[test]
    fn empty_feature_slug_rejected() {
        let mut v = valid_plan();
        v["feature"]["slug"] = json!("   ");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::EmptyString { path } if path == "feature.slug"
        ));
    }

    #[test]
    fn empty_baseline_hash_rejected() {
        let mut v = valid_plan();
        v["baseline"]["test_passlist_hash"] = json!("");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::EmptyString { path } if path == "baseline.test_passlist_hash"
        ));
    }

    // --- v3 baseline provenance is structurally required ---

    #[test]
    fn missing_provenance_field_is_malformed() {
        // Each provenance field carries no serde default in v3, so a document
        // that OMITS one fails to deserialize (Malformed) — provenance can't be
        // silently defaulted to empty as it was in v2.
        for field in ["commit_oid", "toolchain", "enumerated_targets_hash"] {
            let mut v = valid_plan();
            v["baseline"].as_object_mut().unwrap().remove(field);
            let err = parse_and_validate_plan(&v).unwrap_err();
            assert!(
                matches!(err, PlanValidationError::Malformed { .. }),
                "expected Malformed for missing baseline.{field}, got {err:?}"
            );
        }
    }

    #[test]
    fn all_provenance_fields_missing_is_malformed() {
        // Removing all three at once (serde stops at the first missing field, so
        // the per-field loop only proves each in isolation).
        let mut v = valid_plan();
        for field in ["commit_oid", "toolchain", "enumerated_targets_hash"] {
            v["baseline"].as_object_mut().unwrap().remove(field);
        }
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::Malformed { .. }
        ));
    }

    #[test]
    fn empty_provenance_field_rejected() {
        // A present-but-blank provenance value is rejected by validate_plan with
        // a per-field EmptyString error (the PROVENANCE_REQUIRED_SCHEMA gate) —
        // "no evidence" is never treated as evidence.
        for field in ["commit_oid", "toolchain", "enumerated_targets_hash"] {
            let mut v = valid_plan();
            v["baseline"][field] = json!("   ");
            let err = parse_and_validate_plan(&v).unwrap_err();
            assert!(
                matches!(&err, PlanValidationError::EmptyString { path } if path == &format!("baseline.{field}")),
                "expected EmptyString for blank baseline.{field}, got {err:?}"
            );
        }
    }

    #[test]
    fn provenance_gate_fires_via_validate_plan_on_typed_blank() {
        // A typed Plan that blanks a provenance field after deserialization is
        // still rejected by validate_plan (the gate is in validate_plan, not
        // only at the serde boundary).
        let mut plan = parse_and_validate_plan(&valid_plan()).unwrap();
        plan.baseline.commit_oid = String::new();
        assert!(matches!(
            validate_plan(&plan).unwrap_err(),
            PlanValidationError::EmptyString { path } if path == "baseline.commit_oid"
        ));
    }

    #[test]
    fn provenance_fields_always_serialize() {
        // Required fields carry no skip_serializing_if, so a round-trip always
        // re-emits them (a spec that dropped one on serialize would fail the
        // reader that re-validates it).
        let plan = parse_and_validate_plan(&valid_plan()).unwrap();
        let reser = serde_json::to_value(&plan).unwrap();
        let baseline = reser["baseline"].as_object().unwrap();
        for field in ["commit_oid", "toolchain", "enumerated_targets_hash"] {
            assert!(
                baseline.contains_key(field),
                "baseline must serialize {field}"
            );
        }
    }

    // --- tier wire names ---

    #[test]
    fn tier_wire_names_round_trip() {
        for &name in Tier::WIRE_NAMES {
            let tier: Tier = serde_json::from_value(json!(name)).unwrap();
            assert_eq!(serde_json::to_value(tier).unwrap(), json!(name));
        }
    }

    // --- JSON Schema drift guard ---

    #[test]
    fn json_schema_matches_rust_types() {
        let schema: Value = serde_json::from_str(PLAN_V3_JSON_SCHEMA)
            .expect("checked-in JSON Schema must be valid JSON");

        // Version constant agrees.
        assert_eq!(
            schema["properties"]["schema_version"]["const"],
            json!(PLAN_SCHEMA_VERSION)
        );

        // Required top-level fields agree with the Rust struct's fields.
        let required: HashSet<String> = schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap().to_string())
            .collect();
        let expected: HashSet<String> = [
            "schema_version",
            "plan_rev",
            "intent_rev",
            "feature",
            "baseline",
            "acceptance",
            "chunks",
        ]
        .iter()
        .map(ToString::to_string)
        .collect();
        assert_eq!(required, expected);

        // Tier enum agrees.
        let tiers: Vec<String> = schema["$defs"]["chunk"]["properties"]["tier"]["enum"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap().to_string())
            .collect();
        assert_eq!(tiers, Tier::WIRE_NAMES);

        // Nested required-field sets agree with the Rust structs.
        let required_at = |ptr: &str| -> HashSet<String> {
            schema
                .pointer(ptr)
                .and_then(Value::as_array)
                .unwrap_or_else(|| panic!("missing required[] at {ptr}"))
                .iter()
                .map(|v| v.as_str().unwrap().to_string())
                .collect()
        };
        let set = |fields: &[&str]| -> HashSet<String> {
            fields.iter().map(ToString::to_string).collect()
        };
        assert_eq!(
            required_at("/properties/feature/required"),
            set(&["slug", "source_branch", "integration_branch"])
        );
        assert_eq!(
            required_at("/properties/baseline/required"),
            set(&[
                "ref",
                "commit_oid",
                "toolchain",
                "test_passlist_hash",
                "clippy_warnings_hash",
                "enumerated_targets_hash",
            ])
        );

        // Every required baseline string carries `minLength: 1` — the schema-side
        // mirror of the Rust `non_empty` check (including the three v3 provenance
        // fields). If a future edit dropped `minLength` from one, the JSON Schema
        // would tolerate `""` while the Rust validator still rejects it; this
        // pins the two together. (Note the residual, deliberate gap: `minLength`
        // rejects only length-0, whereas Rust's `non_empty` trims, so a
        // whitespace-only value is rejected by the operative Rust validator but
        // tolerated by the JSON Schema. The Rust validator is the source of truth
        // per the module docs; the schema is the coarser machine-readable mirror.)
        for field in [
            "ref",
            "commit_oid",
            "toolchain",
            "test_passlist_hash",
            "clippy_warnings_hash",
            "enumerated_targets_hash",
        ] {
            assert_eq!(
                schema.pointer(&format!(
                    "/properties/baseline/properties/{field}/minLength"
                )),
                Some(&json!(1)),
                "expected baseline.{field} minLength:1 in the JSON Schema"
            );
        }

        assert_eq!(
            required_at("/$defs/chunk/required"),
            set(&["id", "title", "tier", "brief", "files_touched", "checks"])
        );
        assert_eq!(required_at("/$defs/check/required"), set(&["desc", "run"]));

        // Acceptance variants keep their exact required-sets — the `check` arm
        // requires `kind`+`desc`+`run` (never the optional precision), the
        // `assertion` arm `kind`+`desc`. A future edit that promoted `cwd`/
        // `expect_exit` to required would diverge from the Rust `Option<_>`.
        assert_eq!(
            required_at("/$defs/acceptance_item/oneOf/0/required"),
            set(&["kind", "desc", "run"])
        );
        assert_eq!(
            required_at("/$defs/acceptance_item/oneOf/1/required"),
            set(&["kind", "desc"])
        );

        // The flexible-check optional fields (`plan-check-run-contract`) are
        // present as optional (not required) properties on both the per-chunk
        // check def and the acceptance `check` variant — mirroring the Rust
        // `Option<_>` fields on `Check` / `Acceptance::Check`. The schema-side
        // constraints must also match the Rust validator: `cwd` non-empty
        // (`minLength: 1`) and `expect_exit` bounded to the shell range
        // `0..=255`. If a future edit drops or loosens either, schema and types
        // stop agreeing and this fails.
        for ptr in [
            "/$defs/check/properties",
            "/$defs/acceptance_item/oneOf/0/properties",
        ] {
            let props = schema
                .pointer(ptr)
                .unwrap_or_else(|| panic!("missing {ptr}"));
            assert_eq!(
                props["cwd"]["type"],
                json!("string"),
                "expected optional string `cwd` at {ptr}"
            );
            assert_eq!(
                props["cwd"]["minLength"],
                json!(1),
                "expected `cwd` minLength:1 at {ptr}"
            );
            assert_eq!(
                props["expect_exit"]["type"],
                json!("integer"),
                "expected optional integer `expect_exit` at {ptr}"
            );
            assert_eq!(
                props["expect_exit"]["minimum"],
                json!(0),
                "expected `expect_exit` minimum:0 at {ptr}"
            );
            assert_eq!(
                props["expect_exit"]["maximum"],
                json!(i64::from(MAX_SHELL_EXIT)),
                "expected `expect_exit` maximum:255 at {ptr}"
            );
        }

        // Every object shape closes itself with `additionalProperties: false` —
        // the schema-side mirror of the Rust reject-unknown-fields policy. If a
        // future edit drops one, the two stop agreeing and this fails.
        for ptr in [
            "",
            "/properties/feature",
            "/properties/baseline",
            "/$defs/chunk",
            "/$defs/check",
            "/$defs/acceptance_item/oneOf/0",
            "/$defs/acceptance_item/oneOf/1",
        ] {
            let node = if ptr.is_empty() {
                &schema
            } else {
                schema
                    .pointer(ptr)
                    .unwrap_or_else(|| panic!("missing {ptr}"))
            };
            assert_eq!(
                node["additionalProperties"],
                json!(false),
                "expected additionalProperties:false at {ptr:?}"
            );
        }

        // Acceptance `kind` discriminants agree with the Rust enum wire names.
        let kinds: HashSet<String> = schema["$defs"]["acceptance_item"]["oneOf"]
            .as_array()
            .unwrap()
            .iter()
            .map(|variant| {
                variant["properties"]["kind"]["const"]
                    .as_str()
                    .unwrap()
                    .to_string()
            })
            .collect();
        assert_eq!(kinds, set(&["check", "assertion"]));

        // The example the doc/tests use validates against the Rust validator,
        // tying schema + types + example together.
        let example: Value = serde_json::from_str(PLAN_V3_EXAMPLE).unwrap();
        assert!(parse_and_validate_plan(&example).is_ok());
    }

    #[test]
    fn tolerated_optional_seam_is_empty_in_v3() {
        // The governed-evolution seam exists but admits nothing in v3: every
        // object shape's allowlist is empty, so any unknown key is rejected.
        for shape in [
            ObjectShape::Plan,
            ObjectShape::Feature,
            ObjectShape::Baseline,
            ObjectShape::Chunk,
            ObjectShape::Check,
        ] {
            assert!(tolerated_fields(shape).is_empty());
        }
        assert!(TOLERATED_OPTIONAL_FIELDS.is_empty());
    }

    #[test]
    fn unknown_field_scoped_to_its_object() {
        // A per-shape allowlist means an unknown key is reported against the
        // object that carries it, not conflated across shapes.
        let mut v = valid_plan();
        v["feature"]["team"] = json!("payments");
        assert!(matches!(
            parse_and_validate_plan(&v).unwrap_err(),
            PlanValidationError::UnknownField { path, field }
                if path == "feature" && field == "team"
        ));
    }
}