oxide-batch-plan 0.7.0

Internal OxideBatch implementation crate; use oxide-batch instead
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
//! Internal implementation crate for `OxideBatch`.
//!
//! **This crate is implementation detail. Use
//! [`oxide-batch`](https://crates.io/crates/oxide-batch) instead.**
//!
//! It exists on crates.io only because the published `oxide-batch` facade
//! depends on it. Its API carries no stability promise: items may be added,
//! changed, or removed in any release, without a deprecation period. It has no
//! supported-configuration matrix, no compatibility ledger row, and no
//! independent release cadence.
//!
//! Everything here that `OxideBatch` supports is re-exported from `oxide-batch`
//! under a stable path.
//!
//! The crate holds immutable flow graphs and the compiled execution plans they
//! lower into. An application declares a [`FlowGraph`] of step and decision
//! nodes joined by exit-pattern transitions, then compiles it into an immutable
//! [`CompiledExecutionPlan`]. Compilation normalizes the graph, rejects every
//! structural error the accepted basic-flow contract names, and produces the
//! canonical manifest whose SHA-256 digest is the definition fingerprint.
//!
//! The graph remains finite and acyclic. M4 adds bounded local split and
//! partition forms. M7 adds bounded nested-flow composition and split-branch
//! subgraphs while retaining one compiled-plan authority; nested jobs and
//! remote execution remain separate lifecycle boundaries.
//! Existing one-step `TaskletJob` and `ChunkJob` definitions lower into a
//! compatibility plan that retains their original format-1 manifest bytes and
//! fingerprint.
//!
//! The crate depends on no async runtime, database driver, command-line
//! framework, telemetry SDK, broker client, or web framework, and on no
//! `OxideBatch` crate other than `oxide-batch-core`. The flow engine that
//! executes a compiled plan, the metadata ports that persist its decisions,
//! and the runtime live above this crate.
//!
//! # Items marked `#[doc(hidden)]`
//!
//! Some items exist as `#[doc(hidden)] pub` only because the facade's own code
//! was split from these types by the extraction boundary: private access that
//! one crate resolved by module privacy now crosses a crate boundary. They are
//! not part of any surface, supported or otherwise, and the facade never
//! re-exports one under its own name. The staged crate-extraction contract
//! records each one.

#![forbid(unsafe_code)]

mod advanced;
mod custom_leaf;
mod late_binding;
mod nested_job;
mod repeat;

pub use custom_leaf::{CustomLeafKind, CustomLeafNode};

pub use late_binding::{
    LateBindingDefinitionError, LateBoundInput, LateBoundSource, MAX_LATE_BOUND_INPUTS,
    MAX_SCOPED_COMPONENTS, ScopeFactoryKind, ScopeFrameworkSource, ScopeKind, ScopeResolverKind,
    ScopedComponentDefinition, ScopedComponentId,
};

pub use nested_job::{
    FrameworkParameterSource, MAX_NESTED_JOB_PARAMETERS, MAX_SELECTOR_PATH_BYTES,
    MAX_SELECTOR_PATH_SEGMENTS, MissingParameterPolicy, NestedJobNode, NestedJobParameterMapping,
    NestedJobParameterSource, ParameterCoercion, SelectorPath,
};
pub use oxide_batch_core::RepeatId;
pub use repeat::{
    RepeatDefinition, RepeatDefinitionError, RepeatInterceptorDefinition, RepeatInterceptorId,
    RepeatInterceptorKind, RepeatPolicyConfiguration, RepeatPolicyDefinition, RepeatPolicyKind,
    RepeatStateSchema,
};

use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;
use std::num::NonZeroU32;

use serde_json::{Value, json};

use oxide_batch_core::{
    ChunkComponentRevisions, ChunkSize, ComponentRevision, DefinitionError, DefinitionIdentity,
    DefinitionRevision, DefinitionTokenKind, ExitCode, FaultPolicy, FlowTarget, InFlightPolicy,
    JobName, MAX_NODES, MAX_PARTITIONS, MAX_TRANSITIONS, NodeId, ParameterIncrementerIdentity,
    ParameterName, RestartPolicy, StartControls, StepName, TerminalKind, definition_token,
    validate_token,
};

/// The maximum number of transitions leaving one node.
pub const MAX_OUTGOING_TRANSITIONS: usize = 64;
/// The maximum length of one exit pattern in UTF-8 bytes.
pub const MAX_PATTERN_BYTES: usize = 64;
/// The maximum number of branches in one M4 split.
pub const MAX_SPLIT_BRANCHES: usize = 8;
/// The maximum number of linear steps in one split branch.
pub const MAX_BRANCH_STEPS: usize = 8;
/// The maximum number of concurrent local partition workers.
pub const MAX_PARTITION_WORKERS: u8 = 64;
/// The maximum structural nesting depth of an M7 composed flow.
pub const MAX_FLOW_COMPOSITION_DEPTH: usize = 8;

/// The sibling behavior selected after one local child fails.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum LocalFailurePolicy {
    /// Request cooperative cancellation of siblings, then join all children.
    #[default]
    CancelSiblings,
    /// Allow siblings to reach their next boundary, then join all children.
    DrainSiblings,
}

impl LocalFailurePolicy {
    const fn as_str(self) -> &'static str {
        match self {
            Self::CancelSiblings => "cancel_siblings",
            Self::DrainSiblings => "drain_siblings",
        }
    }
}

/// The finite concurrency and connection budget for one M4 split.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SplitBudget {
    max_parallel_branches: u8,
    repository_pool_size: u32,
}

impl SplitBudget {
    /// Constructs validated branch-concurrency and connection bounds.
    ///
    /// # Errors
    ///
    /// Rejects zero/over-limit concurrency or a pool that cannot supply every
    /// active branch plus the owning parent connection.
    pub fn new(max_parallel_branches: u8, repository_pool_size: u32) -> Result<Self, PlanError> {
        if max_parallel_branches == 0 || usize::from(max_parallel_branches) > MAX_SPLIT_BRANCHES {
            return Err(PlanError::InvalidParallelBranchBudget {
                max: MAX_SPLIT_BRANCHES,
            });
        }
        let required = u32::from(max_parallel_branches).saturating_add(1);
        if repository_pool_size < required {
            return Err(PlanError::InsufficientPoolCapacity {
                required,
                configured: repository_pool_size,
            });
        }
        Ok(Self {
            max_parallel_branches,
            repository_pool_size,
        })
    }

    /// Returns the maximum concurrent split branches.
    #[must_use]
    pub const fn max_parallel_branches(self) -> u8 {
        self.max_parallel_branches
    }

    /// Returns the validated repository pool size.
    #[must_use]
    pub const fn repository_pool_size(self) -> u32 {
        self.repository_pool_size
    }
}

impl Default for SplitBudget {
    fn default() -> Self {
        Self {
            max_parallel_branches: 1,
            repository_pool_size: 2,
        }
    }
}

/// The finite worker and connection budget for one M4 partition manager.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PartitionBudget {
    max_partition_workers: u8,
    repository_pool_size: u32,
}

impl PartitionBudget {
    /// Constructs validated worker-concurrency and connection bounds.
    ///
    /// # Errors
    ///
    /// Rejects zero/over-limit concurrency or a pool that cannot supply every
    /// active worker plus the owning parent connection.
    pub fn new(max_partition_workers: u8, repository_pool_size: u32) -> Result<Self, PlanError> {
        if !(1..=MAX_PARTITION_WORKERS).contains(&max_partition_workers) {
            return Err(PlanError::InvalidPartitionWorkerBudget {
                max: MAX_PARTITION_WORKERS,
            });
        }
        let required = u32::from(max_partition_workers).saturating_add(1);
        if repository_pool_size < required {
            return Err(PlanError::InsufficientPoolCapacity {
                required,
                configured: repository_pool_size,
            });
        }
        Ok(Self {
            max_partition_workers,
            repository_pool_size,
        })
    }

    /// Returns the maximum concurrent partition workers.
    #[must_use]
    pub const fn max_partition_workers(self) -> u8 {
        self.max_partition_workers
    }

    /// Returns the validated repository pool size.
    #[must_use]
    pub const fn repository_pool_size(self) -> u32 {
        self.repository_pool_size
    }
}

impl Default for PartitionBudget {
    fn default() -> Self {
        Self {
            max_partition_workers: 4,
            repository_pool_size: 5,
        }
    }
}

definition_token!(
    DeciderRevision,
    DefinitionTokenKind::Decider,
    "An application-owned revision token for one deterministic decider."
);

/// The version of the durable input contract one decider reads.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DecisionInputVersion(NonZeroU32);

impl DecisionInputVersion {
    /// Constructs a nonzero durable input-contract version.
    ///
    /// # Errors
    ///
    /// Returns [`PlanError::ZeroDecisionInputVersion`] for zero.
    pub fn new(value: u32) -> Result<Self, PlanError> {
        NonZeroU32::new(value)
            .map(Self)
            .ok_or(PlanError::ZeroDecisionInputVersion)
    }

    /// Returns the version.
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0.get()
    }
}

/// A bounded exit-outcome pattern used to select one transition.
///
/// A pattern contains literal characters plus `*` for zero or more characters
/// and `?` for exactly one character. It matches the bounded
/// [`ExitCode`], never [`BatchStatus`](oxide_batch_core::BatchStatus).
///
/// The worked example lives in the `oxide-batch` crate documentation, so that
/// it keeps demonstrating the supported import path.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ExitPattern(String);

impl ExitPattern {
    /// Validates and constructs an exit pattern.
    ///
    /// # Errors
    ///
    /// Returns [`PlanError::InvalidPattern`] for an empty pattern, a pattern
    /// longer than 64 UTF-8 bytes, surrounding whitespace, or a control
    /// character.
    pub fn new(value: impl Into<String>) -> Result<Self, PlanError> {
        let value = value.into();
        if value.is_empty()
            || value.len() > MAX_PATTERN_BYTES
            || value.trim() != value
            || value.chars().any(char::is_control)
        {
            return Err(PlanError::InvalidPattern {
                max_bytes: MAX_PATTERN_BYTES,
            });
        }
        Ok(Self(value))
    }

    /// Borrows the validated pattern.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns whether this pattern matches one exit code.
    #[must_use]
    pub fn matches(&self, code: &ExitCode) -> bool {
        let pattern: Vec<char> = self.0.chars().collect();
        let value: Vec<char> = code.as_str().chars().collect();
        matches_from(&pattern, &value)
    }

    /// Returns the computed specificity used to order transitions.
    ///
    /// A greater specificity is evaluated first.
    #[must_use]
    pub fn specificity(&self) -> PatternSpecificity {
        let wildcards = self
            .0
            .chars()
            .filter(|character| matches!(character, '*' | '?'))
            .count();
        let literals = self.0.chars().count() - wildcards;
        PatternSpecificity {
            literals,
            wildcards,
            bytes: self.0.len(),
        }
    }

    /// Returns whether some exit code exists that both patterns match.
    #[must_use]
    pub fn intersects(&self, other: &Self) -> bool {
        let left: Vec<char> = self.0.chars().collect();
        let right: Vec<char> = other.0.chars().collect();
        let mut memo = vec![None; (left.len() + 1) * (right.len() + 1)];
        intersects_from(&left, &right, 0, 0, &mut memo)
    }
}

impl fmt::Display for ExitPattern {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

fn matches_from(pattern: &[char], value: &[char]) -> bool {
    let mut pattern_index = 0_usize;
    let mut value_index = 0_usize;
    let mut star: Option<(usize, usize)> = None;
    while value_index < value.len() {
        match pattern.get(pattern_index) {
            Some('*') => {
                star = Some((pattern_index, value_index));
                pattern_index += 1;
            }
            Some('?') => {
                pattern_index += 1;
                value_index += 1;
            }
            Some(literal) if *literal == value[value_index] => {
                pattern_index += 1;
                value_index += 1;
            }
            _ => match star {
                Some((star_index, resume)) => {
                    pattern_index = star_index + 1;
                    value_index = resume + 1;
                    star = Some((star_index, resume + 1));
                }
                None => return false,
            },
        }
    }
    pattern[pattern_index..]
        .iter()
        .all(|character| *character == '*')
}

fn intersects_from(
    left: &[char],
    right: &[char],
    left_index: usize,
    right_index: usize,
    memo: &mut [Option<bool>],
) -> bool {
    let key = left_index * (right.len() + 1) + right_index;
    if let Some(cached) = memo[key] {
        return cached;
    }
    let answer = match (left.get(left_index), right.get(right_index)) {
        (None, None) => true,
        (None, Some(_)) => right[right_index..].iter().all(|value| *value == '*'),
        (Some(_), None) => left[left_index..].iter().all(|value| *value == '*'),
        (Some('*'), _) => {
            intersects_from(left, right, left_index + 1, right_index, memo)
                || intersects_from(left, right, left_index, right_index + 1, memo)
        }
        (_, Some('*')) => {
            intersects_from(left, right, left_index, right_index + 1, memo)
                || intersects_from(left, right, left_index + 1, right_index, memo)
        }
        (Some(left_character), Some(right_character)) => {
            (*left_character == '?' || *right_character == '?' || left_character == right_character)
                && intersects_from(left, right, left_index + 1, right_index + 1, memo)
        }
    };
    memo[key] = Some(answer);
    answer
}

/// The computed specificity of one exit pattern.
///
/// Ordering compares more literal characters first, then fewer wildcards, then
/// a longer UTF-8 byte length. A greater value is evaluated first.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PatternSpecificity {
    literals: usize,
    wildcards: usize,
    bytes: usize,
}

impl PatternSpecificity {
    /// Returns the number of literal characters.
    #[must_use]
    pub const fn literals(self) -> usize {
        self.literals
    }

    /// Returns the number of `*` and `?` characters.
    #[must_use]
    pub const fn wildcards(self) -> usize {
        self.wildcards
    }

    /// Returns the pattern length in UTF-8 bytes.
    #[must_use]
    pub const fn bytes(self) -> usize {
        self.bytes
    }
}

impl Ord for PatternSpecificity {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.literals
            .cmp(&other.literals)
            .then_with(|| other.wildcards.cmp(&self.wildcards))
            .then_with(|| self.bytes.cmp(&other.bytes))
    }
}

impl PartialOrd for PatternSpecificity {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// The executable kind and restart-relevant declaration of one step node.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum StepComponents {
    /// A single-invocation tasklet body.
    Tasklet(ComponentRevision),
    /// A restartable reader, processor, and writer pipeline.
    Chunk {
        /// The committed chunk size.
        size: ChunkSize,
        /// The restart-relevant component revisions and state schemas.
        revisions: Box<ChunkComponentRevisions>,
    },
}

impl StepComponents {
    fn kind_name(&self) -> &'static str {
        match self {
            Self::Tasklet(_) => "tasklet",
            Self::Chunk { .. } => "chunk",
        }
    }

    fn manifest_value(&self) -> Value {
        match self {
            Self::Tasklet(revision) => json!({
                "component": revision.as_str(),
                "delivery_mode": "best_effort",
                "transaction_boundary": "tasklet_completion"
            }),
            Self::Chunk { size, revisions } => {
                let mut chunk = chunk_declaration_manifest(revisions);
                if let Some(members) = chunk.as_object_mut() {
                    members.insert("size".to_owned(), json!(size.get()));
                    members.insert(
                        "transaction_boundary".to_owned(),
                        Value::String("chunk".to_owned()),
                    );
                }
                chunk
            }
        }
    }
}

/// One executable node of a compiled plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StepNode {
    id: NodeId,
    step_name: StepName,
    components: StepComponents,
    start: StartControls,
    fault: Option<FaultPolicy>,
    listeners: Vec<ComponentRevision>,
    repeat: Option<RepeatDefinition>,
}

impl StepNode {
    /// Declares one step node.
    #[must_use]
    pub fn new(id: NodeId, step_name: StepName, components: StepComponents) -> Self {
        Self {
            id,
            step_name,
            components,
            start: StartControls::default(),
            fault: None,
            listeners: Vec::new(),
            repeat: None,
        }
    }

    /// Declares explicit start controls.
    #[must_use]
    pub const fn with_start_controls(mut self, start: StartControls) -> Self {
        self.start = start;
        self
    }

    /// Declares the fault policy this step's fingerprint captures.
    #[must_use]
    pub fn with_fault_policy(mut self, policy: FaultPolicy) -> Self {
        self.fault = Some(policy);
        self
    }

    /// Declares one authoritative listener revision in registration order.
    #[must_use]
    pub fn with_listener_revision(mut self, revision: ComponentRevision) -> Self {
        self.listeners.push(revision);
        self
    }

    /// Declares restart-relevant Gate-C repeat metadata around this step.
    #[must_use]
    pub fn with_repeat_definition(mut self, repeat: RepeatDefinition) -> Self {
        self.repeat = Some(repeat);
        self
    }

    /// Borrows the repeat definition attached to this step, when present.
    #[must_use]
    pub const fn repeat_definition(&self) -> Option<&RepeatDefinition> {
        self.repeat.as_ref()
    }

    /// Borrows the stable node identifier.
    #[must_use]
    pub const fn id(&self) -> &NodeId {
        &self.id
    }

    /// Borrows the durable step name.
    #[must_use]
    pub const fn step_name(&self) -> &StepName {
        &self.step_name
    }

    /// Borrows the executable component declaration.
    #[must_use]
    pub const fn components(&self) -> &StepComponents {
        &self.components
    }

    /// Returns the restart-relevant start controls.
    #[must_use]
    pub const fn start_controls(&self) -> StartControls {
        self.start
    }

    /// Borrows the declared fault policy.
    #[must_use]
    pub const fn fault_policy(&self) -> Option<&FaultPolicy> {
        self.fault.as_ref()
    }

    /// Borrows the authoritative listener revisions in registration order.
    #[must_use]
    pub fn listener_revisions(&self) -> &[ComponentRevision] {
        &self.listeners
    }

    fn manifest_value(&self) -> Value {
        let mut value = json!({
            "id": self.id.as_str(),
            "kind": "step",
            "listeners": self
                .listeners
                .iter()
                .map(|revision| Value::String(revision.as_str().to_owned()))
                .collect::<Vec<_>>(),
            "policy": self.fault.as_ref().map_or(Value::Null, fault_manifest_value),
            "start": start_controls_manifest(self.start),
            "step": {
                "declaration": self.components.manifest_value(),
                "kind": self.components.kind_name(),
                "name": self.step_name.as_str()
            }
        });
        if let Some(repeat) = &self.repeat
            && let Some(object) = value.as_object_mut()
        {
            object.insert("repeat".to_owned(), repeat.manifest_value());
        }
        value
    }
}

/// One deterministic decision node of a compiled plan.
///
/// M3 compiles and fingerprints decision nodes; executing them is owned by the
/// durable-flow workstream.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DecisionNode {
    id: NodeId,
    revision: DeciderRevision,
    input_version: DecisionInputVersion,
}

impl DecisionNode {
    /// Declares one decision node.
    #[must_use]
    pub const fn new(
        id: NodeId,
        revision: DeciderRevision,
        input_version: DecisionInputVersion,
    ) -> Self {
        Self {
            id,
            revision,
            input_version,
        }
    }

    /// Borrows the stable node identifier.
    #[must_use]
    pub const fn id(&self) -> &NodeId {
        &self.id
    }

    /// Borrows the application-owned decider revision.
    #[must_use]
    pub const fn revision(&self) -> &DeciderRevision {
        &self.revision
    }

    /// Returns the durable input-contract version.
    #[must_use]
    pub const fn input_version(&self) -> DecisionInputVersion {
        self.input_version
    }

    fn manifest_value(&self) -> Value {
        json!({
            "decision": {
                "input_version": self.input_version.get(),
                "revision": self.revision.as_str()
            },
            "id": self.id.as_str(),
            "kind": "decision"
        })
    }
}

/// One validated execution scope inside an M7 composed plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompiledFlowScope {
    entry: NodeId,
    members: BTreeSet<NodeId>,
}

impl CompiledFlowScope {
    pub(crate) fn new(entry: NodeId, members: BTreeSet<NodeId>) -> Self {
        Self { entry, members }
    }

    /// Borrows the first executable node in this scope.
    #[must_use]
    pub const fn entry(&self) -> &NodeId {
        &self.entry
    }

    /// Returns whether an executable node belongs to this scope.
    #[must_use]
    pub fn contains(&self, node: &NodeId) -> bool {
        self.members.contains(node)
    }

    /// Iterates executable members in canonical logical-ID order.
    #[must_use]
    pub fn members(&self) -> impl ExactSizeIterator<Item = &NodeId> {
        self.members.iter()
    }
}

/// One reusable M7 flow embedded under a stable structural owner.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NestedFlow {
    id: NodeId,
    graph: Box<FlowGraph>,
}

impl NestedFlow {
    /// Declares one nested-flow boundary.
    #[must_use]
    pub fn new(id: NodeId, graph: FlowGraph) -> Self {
        Self {
            id,
            graph: Box::new(graph),
        }
    }

    /// Borrows the stable structural owner ID.
    #[must_use]
    pub const fn id(&self) -> &NodeId {
        &self.id
    }

    /// Borrows the nested graph declaration.
    #[must_use]
    pub const fn graph(&self) -> &FlowGraph {
        &self.graph
    }
}

/// One split branch. M4 branches are linear; M7 may embed a bounded flow.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SplitBranch {
    steps: Vec<StepNode>,
    flow: Option<Box<FlowGraph>>,
}

impl SplitBranch {
    /// Declares the byte-compatible M4 linear branch form.
    ///
    /// Cardinality and identifier uniqueness are checked by
    /// [`FlowGraph::compile`], so builders can assemble a complete diagnostic
    /// instead of panicking while under construction.
    #[must_use]
    pub fn new(steps: Vec<StepNode>) -> Self {
        Self { steps, flow: None }
    }

    /// Declares an M7 branch as a bounded acyclic subgraph.
    #[must_use]
    pub fn flow(graph: FlowGraph) -> Self {
        Self {
            steps: Vec::new(),
            flow: Some(Box::new(graph)),
        }
    }

    /// Borrows the legacy linear branch steps.
    ///
    /// An M7 flow branch returns an empty slice; use [`flow_graph`](Self::flow_graph)
    /// to inspect its declaration.
    #[must_use]
    pub fn steps(&self) -> &[StepNode] {
        &self.steps
    }

    /// Borrows the M7 branch graph when this is a flow branch.
    #[must_use]
    pub fn flow_graph(&self) -> Option<&FlowGraph> {
        self.flow.as_deref()
    }

    /// Borrows the legacy branch identity, which is its first logical step ID.
    ///
    /// Flow branches have a separate compiled scope and therefore no synthetic
    /// branch `NodeId`.
    #[must_use]
    pub fn id(&self) -> Option<&NodeId> {
        self.steps.first().map(StepNode::id)
    }

    fn manifest_value(&self) -> Value {
        Value::Array(self.steps.iter().map(StepNode::manifest_value).collect())
    }
}

/// A bounded M4 split whose branches converge at exactly one join node.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SplitNode {
    id: NodeId,
    branches: Vec<SplitBranch>,
    join: NodeId,
    budget: SplitBudget,
    failure_policy: LocalFailurePolicy,
}

impl SplitNode {
    /// Declares a split, its ordered branches, and its unique join.
    #[must_use]
    pub fn new(id: NodeId, branches: Vec<SplitBranch>, join: NodeId, budget: SplitBudget) -> Self {
        Self {
            id,
            branches,
            join,
            budget,
            failure_policy: LocalFailurePolicy::default(),
        }
    }

    /// Selects sibling failure behavior.
    #[must_use]
    pub const fn with_failure_policy(mut self, failure_policy: LocalFailurePolicy) -> Self {
        self.failure_policy = failure_policy;
        self
    }

    /// Borrows the stable split identifier.
    #[must_use]
    pub const fn id(&self) -> &NodeId {
        &self.id
    }

    /// Borrows branches in deterministic aggregation order.
    #[must_use]
    pub fn branches(&self) -> &[SplitBranch] {
        &self.branches
    }

    /// Borrows the split's unique join identifier.
    #[must_use]
    pub const fn join(&self) -> &NodeId {
        &self.join
    }

    /// Returns the finite local resource budget.
    #[must_use]
    pub const fn budget(&self) -> SplitBudget {
        self.budget
    }

    /// Returns sibling failure behavior.
    #[must_use]
    pub const fn failure_policy(&self) -> LocalFailurePolicy {
        self.failure_policy
    }

    /// Projects the restart-relevant split declaration.
    ///
    /// The budget is a throughput bound rather than a durable-meaning value, so
    /// [ADR-0009](https://github.com/luceat-lux-vestra/oxide-batch/blob/main/docs/architecture/decisions/0009-definition-fingerprint-input-set.md)
    /// excludes it. Branch membership and order select assignment and remain.
    fn manifest_value(&self) -> Value {
        json!({
            "branches": self.branches.iter().map(SplitBranch::manifest_value).collect::<Vec<_>>(),
            "failure_policy": self.failure_policy.as_str(),
            "id": self.id.as_str(),
            "join": self.join.as_str(),
            "kind": "split"
        })
    }
}

/// The structural join owned by one M4 split.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct JoinNode {
    id: NodeId,
}

impl JoinNode {
    /// Declares a structural join.
    #[must_use]
    pub const fn new(id: NodeId) -> Self {
        Self { id }
    }

    /// Borrows the stable join identifier.
    #[must_use]
    pub const fn id(&self) -> &NodeId {
        &self.id
    }

    fn manifest_value(&self) -> Value {
        json!({
            "id": self.id.as_str(),
            "kind": "join"
        })
    }
}

/// A finite durable partition count for one M4 partitioned step.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PartitionCount(u16);

impl PartitionCount {
    /// Constructs a count in the accepted `1..=1024` range.
    ///
    /// # Errors
    ///
    /// Returns [`PlanError::InvalidPartitionCount`] outside that range.
    pub fn new(value: u16) -> Result<Self, PlanError> {
        if value == 0 || value > MAX_PARTITIONS {
            return Err(PlanError::InvalidPartitionCount {
                max: MAX_PARTITIONS,
            });
        }
        Ok(Self(value))
    }

    /// Returns the declared partition count.
    #[must_use]
    pub const fn get(self) -> u16 {
        self.0
    }
}

/// A bounded local partition manager and its ordinary worker-step definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PartitionedStepNode {
    id: NodeId,
    step_name: StepName,
    worker: StepNode,
    partitioner: ComponentRevision,
    aggregation: ComponentRevision,
    partitions: PartitionCount,
    budget: PartitionBudget,
    failure_policy: LocalFailurePolicy,
    start: StartControls,
}

impl PartitionedStepNode {
    /// Declares the complete restart-relevant local partition shape.
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    pub fn new(
        id: NodeId,
        step_name: StepName,
        worker: StepNode,
        partitioner: ComponentRevision,
        aggregation: ComponentRevision,
        partitions: PartitionCount,
        budget: PartitionBudget,
    ) -> Self {
        Self {
            id,
            step_name,
            worker,
            partitioner,
            aggregation,
            partitions,
            budget,
            failure_policy: LocalFailurePolicy::default(),
            start: StartControls::default(),
        }
    }

    /// Selects sibling failure behavior.
    #[must_use]
    pub const fn with_failure_policy(mut self, failure_policy: LocalFailurePolicy) -> Self {
        self.failure_policy = failure_policy;
        self
    }

    /// Declares the partition manager's start controls.
    #[must_use]
    pub const fn with_start_controls(mut self, start: StartControls) -> Self {
        self.start = start;
        self
    }

    /// Borrows the stable manager node identifier.
    #[must_use]
    pub const fn id(&self) -> &NodeId {
        &self.id
    }

    /// Borrows the manager's durable step name.
    #[must_use]
    pub const fn step_name(&self) -> &StepName {
        &self.step_name
    }

    /// Borrows the ordinary tasklet or chunk worker declaration.
    #[must_use]
    pub const fn worker(&self) -> &StepNode {
        &self.worker
    }

    /// Borrows the deterministic partitioner revision.
    #[must_use]
    pub const fn partitioner(&self) -> &ComponentRevision {
        &self.partitioner
    }

    /// Borrows the deterministic aggregation revision.
    #[must_use]
    pub const fn aggregation(&self) -> &ComponentRevision {
        &self.aggregation
    }

    /// Returns the finite partition count.
    #[must_use]
    pub const fn partition_count(&self) -> PartitionCount {
        self.partitions
    }

    /// Returns the finite local resource budget.
    #[must_use]
    pub const fn budget(&self) -> PartitionBudget {
        self.budget
    }

    /// Returns sibling failure behavior.
    #[must_use]
    pub const fn failure_policy(&self) -> LocalFailurePolicy {
        self.failure_policy
    }

    /// Returns the partition manager's start controls.
    #[must_use]
    pub const fn start_controls(&self) -> StartControls {
        self.start
    }

    /// Projects the restart-relevant partition declaration.
    ///
    /// The partition count selects durable assignment and the partitioner and
    /// aggregation revisions decide how that assignment and its results are
    /// interpreted, so all three remain. The worker and connection budget is a
    /// throughput bound that [ADR-0009](https://github.com/luceat-lux-vestra/oxide-batch/blob/main/docs/architecture/decisions/0009-definition-fingerprint-input-set.md)
    /// excludes.
    fn manifest_value(&self) -> Value {
        json!({
            "aggregation": self.aggregation.as_str(),
            "failure_policy": self.failure_policy.as_str(),
            "id": self.id.as_str(),
            "kind": "partitioned_step",
            "partition_count": self.partitions.get(),
            "partitioner": self.partitioner.as_str(),
            "start": start_controls_manifest(self.start),
            "step_name": self.step_name.as_str(),
            "worker": self.worker.manifest_value()
        })
    }
}

/// One node of a declared flow graph.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum FlowNode {
    /// A tasklet or chunk step.
    Step(Box<StepNode>),
    /// A deterministic decision.
    Decision(DecisionNode),
    /// A separately durable child-job lifecycle boundary.
    NestedJob(Box<NestedJobNode>),
    /// A registered framework-owned custom leaf.
    CustomLeaf(Box<CustomLeafNode>),
    /// A bounded set of linear branches and its structural join.
    Split(Box<SplitNode>),
    /// A structural join owned by exactly one split.
    Join(JoinNode),
    /// A bounded durable local-partition manager.
    PartitionedStep(Box<PartitionedStepNode>),
}

impl FlowNode {
    fn has_nonrestartable_step(&self) -> bool {
        match self {
            Self::Step(step) => {
                step.start_controls().restart_policy() == RestartPolicy::NotRestartable
            }
            Self::CustomLeaf(custom) => {
                custom.start_controls().restart_policy() == RestartPolicy::NotRestartable
            }
            Self::PartitionedStep(partitioned) => {
                partitioned.start_controls().restart_policy() == RestartPolicy::NotRestartable
                    || partitioned.worker().start_controls().restart_policy()
                        == RestartPolicy::NotRestartable
            }
            Self::Split(split) => {
                split
                    .branches()
                    .iter()
                    .flat_map(SplitBranch::steps)
                    .any(|step| {
                        step.start_controls().restart_policy() == RestartPolicy::NotRestartable
                    })
            }
            _ => false,
        }
    }

    fn has_repeat_definition(&self) -> bool {
        match self {
            Self::Step(step) => step.repeat_definition().is_some(),
            Self::PartitionedStep(partitioned) => {
                partitioned.worker().repeat_definition().is_some()
            }
            Self::Split(split) => split
                .branches()
                .iter()
                .flat_map(SplitBranch::steps)
                .any(|step| step.repeat_definition().is_some()),
            _ => false,
        }
    }

    /// Declares a step node.
    #[must_use]
    pub fn step(node: StepNode) -> Self {
        Self::Step(Box::new(node))
    }

    /// Declares a decision node.
    #[must_use]
    pub const fn decision(node: DecisionNode) -> Self {
        Self::Decision(node)
    }

    /// Declares a separately durable nested-job node.
    #[must_use]
    pub fn nested_job(node: NestedJobNode) -> Self {
        Self::NestedJob(Box::new(node))
    }

    /// Declares a registered framework-owned custom leaf.
    #[must_use]
    pub fn custom_leaf(node: CustomLeafNode) -> Self {
        Self::CustomLeaf(Box::new(node))
    }

    /// Declares a bounded split node.
    #[must_use]
    pub fn split(node: SplitNode) -> Self {
        Self::Split(Box::new(node))
    }

    /// Declares a structural join node.
    #[must_use]
    pub const fn join(node: JoinNode) -> Self {
        Self::Join(node)
    }

    /// Declares a bounded local partitioned-step node.
    #[must_use]
    pub fn partitioned_step(node: PartitionedStepNode) -> Self {
        Self::PartitionedStep(Box::new(node))
    }

    /// Borrows the node's stable identifier.
    #[must_use]
    pub const fn id(&self) -> &NodeId {
        match self {
            Self::Step(node) => node.id(),
            Self::Decision(node) => node.id(),
            Self::NestedJob(node) => node.id(),
            Self::CustomLeaf(node) => node.id(),
            Self::Split(node) => node.id(),
            Self::Join(node) => node.id(),
            Self::PartitionedStep(node) => node.id(),
        }
    }

    fn manifest_value(&self) -> Value {
        match self {
            Self::Step(node) => node.manifest_value(),
            Self::Decision(node) => node.manifest_value(),
            Self::NestedJob(node) => node.manifest_value(),
            Self::CustomLeaf(node) => node.manifest_value(),
            Self::Split(node) => node.manifest_value(),
            Self::Join(node) => node.manifest_value(),
            Self::PartitionedStep(node) => node.manifest_value(),
        }
    }
}

/// One declared transition edge.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FlowTransition {
    source: NodeId,
    pattern: ExitPattern,
    target: FlowTarget,
}

impl FlowTransition {
    /// Declares one directed transition selected by an exit pattern.
    #[must_use]
    pub const fn new(source: NodeId, pattern: ExitPattern, target: FlowTarget) -> Self {
        Self {
            source,
            pattern,
            target,
        }
    }

    /// Borrows the source node identifier.
    #[must_use]
    pub const fn source(&self) -> &NodeId {
        &self.source
    }

    /// Borrows the selecting pattern.
    #[must_use]
    pub const fn pattern(&self) -> &ExitPattern {
        &self.pattern
    }

    /// Borrows the selected target.
    #[must_use]
    pub const fn target(&self) -> &FlowTarget {
        &self.target
    }

    fn manifest_value(&self) -> Value {
        json!({
            "pattern": self.pattern.as_str(),
            "source": self.source.as_str(),
            "target": flow_target_manifest(&self.target)
        })
    }
}

/// An immutable declaration of the M3 flow subset.
///
/// The worked example lives in the `oxide-batch` crate documentation, so that
/// it keeps demonstrating the supported import path.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct FlowGraph {
    entry: Option<NodeId>,
    nodes: Vec<FlowNode>,
    transitions: Vec<FlowTransition>,
    nested_flows: Vec<NestedFlow>,
    scoped_components: Vec<ScopedComponentDefinition>,
    parameter_incrementer: Option<ParameterIncrementerIdentity>,
    job_restart_policy: RestartPolicy,
}

impl FlowGraph {
    /// Starts a graph at its entry node.
    #[must_use]
    pub fn new(entry: NodeId) -> Self {
        Self {
            entry: Some(entry),
            nodes: Vec::new(),
            transitions: Vec::new(),
            nested_flows: Vec::new(),
            scoped_components: Vec::new(),
            parameter_incrementer: None,
            job_restart_policy: RestartPolicy::Restartable,
        }
    }

    /// Declares one node.
    #[must_use]
    pub fn with_node(mut self, node: FlowNode) -> Self {
        self.nodes.push(node);
        self
    }

    /// Embeds one reusable flow under a stable structural owner.
    #[must_use]
    pub fn with_nested_flow(mut self, flow: NestedFlow) -> Self {
        self.nested_flows.push(flow);
        self
    }

    /// Declares one restart-relevant job- or step-scoped component.
    ///
    /// Components are canonicalized by scope and logical component ID during
    /// compilation. Duplicate identities fail closed.
    #[must_use]
    pub fn with_scoped_component(mut self, component: ScopedComponentDefinition) -> Self {
        self.scoped_components.push(component);
        self
    }

    /// Declares the restart-relevant identity of the parameter incrementer
    /// authorized for this definition.
    ///
    /// Declaring an incrementer identity opts the graph into manifest format 4.
    #[must_use]
    pub fn with_parameter_incrementer_identity(
        mut self,
        identity: ParameterIncrementerIdentity,
    ) -> Self {
        self.parameter_incrementer = Some(identity);
        self
    }

    /// Applies the execution-definition restart policy for this job.
    ///
    /// A non-restartable declaration opts the definition into manifest format 4.
    /// Nested flow declarations may only narrow the enclosing job to
    /// non-restartable; they can never reset a non-restartable parent.
    #[must_use]
    pub const fn with_job_restart_policy(mut self, policy: RestartPolicy) -> Self {
        self.job_restart_policy = policy;
        self
    }

    /// Returns the declared job restart policy.
    #[must_use]
    pub const fn job_restart_policy(&self) -> RestartPolicy {
        self.job_restart_policy
    }

    /// Borrows the declared entry reference.
    #[must_use]
    pub const fn entry(&self) -> Option<&NodeId> {
        self.entry.as_ref()
    }

    fn requires_advanced_format(&self) -> bool {
        self.job_restart_policy == RestartPolicy::NotRestartable
            || self.parameter_incrementer.is_some()
            || !self.scoped_components.is_empty()
            || !self.nested_flows.is_empty()
            || self.nodes.iter().any(|node| {
                node.has_nonrestartable_step()
                    || node.has_repeat_definition()
                    || match node {
                        FlowNode::NestedJob(_) | FlowNode::CustomLeaf(_) => true,
                        FlowNode::Split(split) => {
                            split.branches().iter().any(|branch| branch.flow.is_some())
                        }
                        _ => false,
                    }
            })
    }

    /// Declares one explicit transition.
    #[must_use]
    pub fn with_transition(mut self, transition: FlowTransition) -> Self {
        self.transitions.push(transition);
        self
    }

    /// Declares the convenience sequential edge.
    ///
    /// A sequential edge compiles to an exact `FAILED` transition leading to
    /// [`TerminalKind::Fail`] and a less specific `*` transition leading to
    /// `next`. Custom successful exit codes therefore continue, while a failed
    /// step ends the job.
    ///
    /// # Errors
    ///
    /// Returns [`PlanError::InvalidPattern`] only if the framework-owned
    /// patterns cannot be constructed.
    pub fn with_sequence(self, source: NodeId, next: FlowTarget) -> Result<Self, PlanError> {
        Ok(self
            .with_transition(FlowTransition::new(
                source.clone(),
                ExitPattern::new("FAILED")?,
                FlowTarget::Terminal(TerminalKind::Fail),
            ))
            .with_transition(FlowTransition::new(source, ExitPattern::new("*")?, next)))
    }

    /// Validates and normalizes the graph into an immutable plan.
    ///
    /// # Errors
    ///
    /// Returns [`PlanError`] for a missing entry node, a duplicate logical
    /// identifier, an undefined source or target, a node without outgoing
    /// transitions, two equally specific patterns that can match one value, an
    /// unreachable node, a cycle, an exceeded bound, or a manifest that cannot
    /// be encoded within the durable limit.
    pub fn compile(
        self,
        job_name: &JobName,
        revision: DefinitionRevision,
    ) -> Result<CompiledExecutionPlan, PlanError> {
        if self.requires_advanced_format() {
            return advanced::compile(self, job_name, revision);
        }
        let entry = self.entry.ok_or(PlanError::MissingEntryNode)?;
        if self.nodes.len() > MAX_NODES {
            return Err(PlanError::TooManyNodes { max: MAX_NODES });
        }
        if self.transitions.len() > MAX_TRANSITIONS {
            return Err(PlanError::TooManyTransitions {
                max: MAX_TRANSITIONS,
            });
        }

        let mut nodes = BTreeMap::new();
        for node in self.nodes {
            if nodes.insert(node.id().clone(), node.clone()).is_some() {
                return Err(PlanError::DuplicateNodeId {
                    node: node.id().clone(),
                });
            }
        }
        if !nodes.contains_key(&entry) {
            return Err(PlanError::UndefinedNode {
                node: entry.clone(),
            });
        }
        let local_scale = check_local_scale_subset(&entry, &nodes)?;

        let mut outgoing: BTreeMap<NodeId, Vec<FlowTransition>> = BTreeMap::new();
        for transition in self.transitions {
            if !nodes.contains_key(transition.source()) {
                return Err(PlanError::UndefinedNode {
                    node: transition.source().clone(),
                });
            }
            if let FlowTarget::Node(target) = transition.target()
                && !nodes.contains_key(target)
            {
                return Err(PlanError::UndefinedNode {
                    node: target.clone(),
                });
            }
            if let FlowTarget::Node(target) = transition.target()
                && matches!(nodes.get(target), Some(FlowNode::Join(_)))
            {
                return Err(PlanError::JoinHasExternalEntry {
                    join: target.clone(),
                });
            }
            if matches!(nodes.get(transition.source()), Some(FlowNode::Split(_))) {
                return Err(PlanError::SplitHasExplicitTransition {
                    split: transition.source().clone(),
                });
            }
            let edges = outgoing.entry(transition.source().clone()).or_default();
            if edges.len() == MAX_OUTGOING_TRANSITIONS {
                return Err(PlanError::TooManyOutgoingTransitions {
                    node: transition.source().clone(),
                    max: MAX_OUTGOING_TRANSITIONS,
                });
            }
            edges.push(transition);
        }

        for (id, node) in &nodes {
            if matches!(node, FlowNode::Split(_)) {
                continue;
            }
            let edges = outgoing
                .get(id)
                .filter(|edges| !edges.is_empty())
                .ok_or_else(|| PlanError::MissingTransition { node: id.clone() })?;
            check_unambiguous(id, edges)?;
        }

        let mut compiled: BTreeMap<NodeId, Vec<FlowTransition>> = outgoing;
        for edges in compiled.values_mut() {
            edges.sort_by(|left, right| {
                right
                    .pattern()
                    .specificity()
                    .cmp(&left.pattern().specificity())
                    .then_with(|| left.pattern().cmp(right.pattern()))
                    .then_with(|| left.target().sort_key().cmp(&right.target().sort_key()))
            });
        }

        check_reachable_and_acyclic(&entry, &nodes, &compiled)?;

        let manifest = flow_manifest(job_name, &entry, &nodes, &compiled, local_scale);
        let canonical = serde_json::to_vec(&manifest)
            .map_err(|_| PlanError::Manifest(DefinitionError::ManifestEncoding))?;
        let definition = DefinitionIdentity::from_flow_manifest(job_name, revision, &canonical)
            .map_err(PlanError::Manifest)?;
        Ok(CompiledExecutionPlan {
            definition,
            job_restart_policy: RestartPolicy::Restartable,
            parameter_incrementer: None,
            scoped_components: BTreeMap::new(),
            root_scope: CompiledFlowScope::new(entry.clone(), nodes.keys().cloned().collect()),
            entry,
            nodes,
            transitions: compiled,
            split_branch_scopes: BTreeMap::new(),
            nested_scopes: BTreeMap::new(),
            decision_sequences: BTreeMap::new(),
        })
    }
}

fn check_local_scale_subset(
    entry: &NodeId,
    nodes: &BTreeMap<NodeId, FlowNode>,
) -> Result<bool, PlanError> {
    let mut embedded_ids = BTreeSet::new();
    let mut join_owners: BTreeMap<NodeId, NodeId> = BTreeMap::new();
    let mut local_scale = false;
    for (id, node) in nodes {
        match node {
            FlowNode::Split(split) => {
                local_scale = true;
                if id == entry {
                    return Err(PlanError::SplitIsEntry { split: id.clone() });
                }
                if !(2..=MAX_SPLIT_BRANCHES).contains(&split.branches().len()) {
                    return Err(PlanError::InvalidSplitBranchCount {
                        split: id.clone(),
                        min: 2,
                        max: MAX_SPLIT_BRANCHES,
                    });
                }
                if usize::from(split.budget().max_parallel_branches()) > split.branches().len() {
                    return Err(PlanError::ParallelBudgetExceedsBranches {
                        split: id.clone(),
                        branches: split.branches().len(),
                    });
                }
                if !matches!(nodes.get(split.join()), Some(FlowNode::Join(_))) {
                    return Err(PlanError::InvalidSplitJoin {
                        split: id.clone(),
                        join: split.join().clone(),
                    });
                }
                if let Some(first) = join_owners.insert(split.join().clone(), id.clone()) {
                    return Err(PlanError::JoinHasMultipleOwners {
                        join: split.join().clone(),
                        first,
                        second: id.clone(),
                    });
                }
                for branch in split.branches() {
                    if !(1..=MAX_BRANCH_STEPS).contains(&branch.steps().len()) {
                        return Err(PlanError::InvalidBranchLength {
                            split: id.clone(),
                            max: MAX_BRANCH_STEPS,
                        });
                    }
                    for step in branch.steps() {
                        if nodes.contains_key(step.id()) || !embedded_ids.insert(step.id().clone())
                        {
                            return Err(PlanError::DuplicateNodeId {
                                node: step.id().clone(),
                            });
                        }
                    }
                }
            }
            FlowNode::Join(_) => {
                local_scale = true;
            }
            FlowNode::PartitionedStep(partitioned) => {
                local_scale = true;
                let worker = partitioned.worker().id();
                if nodes.contains_key(worker) || !embedded_ids.insert(worker.clone()) {
                    return Err(PlanError::DuplicateNodeId {
                        node: worker.clone(),
                    });
                }
            }
            FlowNode::Step(_)
            | FlowNode::Decision(_)
            | FlowNode::NestedJob(_)
            | FlowNode::CustomLeaf(_) => {}
        }
    }
    if nodes.len().saturating_add(embedded_ids.len()) > MAX_NODES {
        return Err(PlanError::TooManyNodes { max: MAX_NODES });
    }
    for (id, node) in nodes {
        if matches!(node, FlowNode::Join(_)) && !join_owners.contains_key(id) {
            return Err(PlanError::OrphanJoin { join: id.clone() });
        }
    }
    Ok(local_scale)
}

fn check_unambiguous(node: &NodeId, edges: &[FlowTransition]) -> Result<(), PlanError> {
    for (index, left) in edges.iter().enumerate() {
        for right in &edges[index + 1..] {
            if left.pattern().specificity() == right.pattern().specificity()
                && left.pattern().intersects(right.pattern())
            {
                return Err(PlanError::AmbiguousTransition {
                    node: node.clone(),
                    first: left.pattern().clone(),
                    second: right.pattern().clone(),
                });
            }
        }
    }
    Ok(())
}

fn check_reachable_and_acyclic(
    entry: &NodeId,
    nodes: &BTreeMap<NodeId, FlowNode>,
    transitions: &BTreeMap<NodeId, Vec<FlowTransition>>,
) -> Result<(), PlanError> {
    let mut visited = BTreeSet::new();
    let mut on_path = BTreeSet::new();
    visit(entry, nodes, transitions, &mut visited, &mut on_path)?;
    for id in nodes.keys() {
        if !visited.contains(id) {
            return Err(PlanError::UnreachableNode { node: id.clone() });
        }
    }
    Ok(())
}

fn visit(
    node: &NodeId,
    nodes: &BTreeMap<NodeId, FlowNode>,
    transitions: &BTreeMap<NodeId, Vec<FlowTransition>>,
    visited: &mut BTreeSet<NodeId>,
    on_path: &mut BTreeSet<NodeId>,
) -> Result<(), PlanError> {
    if on_path.contains(node) {
        return Err(PlanError::CyclicGraph { node: node.clone() });
    }
    if !visited.insert(node.clone()) {
        return Ok(());
    }
    on_path.insert(node.clone());
    if let Some(FlowNode::Split(split)) = nodes.get(node) {
        visit(split.join(), nodes, transitions, visited, on_path)?;
    }
    if let Some(edges) = transitions.get(node) {
        for edge in edges {
            if let FlowTarget::Node(target) = edge.target() {
                visit(target, nodes, transitions, visited, on_path)?;
            }
        }
    }
    on_path.remove(node);
    Ok(())
}

/// Projects restart-relevant start controls into their manifest member.
///
/// The projection lives here rather than on the value because the canonical
/// manifest is this crate's contract. Keeping it here is also what keeps the
/// serializer out of the core's public signatures, and out of the facade that
/// re-exports them.
fn start_controls_manifest(controls: StartControls) -> Value {
    let mut value = json!({
        "allow_start_if_complete": controls.allow_start_if_complete(),
        "start_limit": controls.start_limit().get()
    });
    if controls.restart_policy() == RestartPolicy::NotRestartable
        && let Some(object) = value.as_object_mut()
    {
        object.insert(
            "restart_policy".to_owned(),
            Value::String("not_restartable".to_owned()),
        );
    }
    value
}

/// Projects one transition target into its manifest member.
fn flow_target_manifest(target: &FlowTarget) -> Value {
    match target {
        FlowTarget::Node(id) => json!({ "node": id.as_str() }),
        FlowTarget::Terminal(kind) => json!({ "terminal": kind.as_str() }),
    }
}

/// Projects the restart-relevant chunk declaration into manifest members.
///
/// `in_flight_policy` is present only when it is the non-default rollback
/// policy, because format 1 recorded nothing for the default and the two
/// formats must agree on what a chunk declaration means.
fn chunk_declaration_manifest(revisions: &ChunkComponentRevisions) -> Value {
    let mut value = json!({
        "checkpoint": {
            "schema": revisions.checkpoint_schema().as_str(),
            "version": revisions.checkpoint_schema_version().get()
        },
        "components": {
            "checkpoint": revisions.checkpoint().as_str(),
            "processor": revisions.processor().as_str(),
            "reader": revisions.reader().as_str(),
            "writer": revisions.writer().as_str()
        },
        "context": {
            "schema": revisions.context_schema().as_str(),
            "version": revisions.context_schema_version().get()
        },
        "delivery_mode": revisions.delivery_mode().manifest_name()
    });
    if revisions.in_flight_policy() == InFlightPolicy::RollbackChunk
        && let Some(object) = value.as_object_mut()
    {
        object.insert(
            "in_flight_policy".to_owned(),
            Value::String("rollback_chunk".to_owned()),
        );
    }
    value
}

fn fault_manifest_value(policy: &FaultPolicy) -> Value {
    let backoff = policy.backoff();
    let rules: Vec<Value> = policy
        .classifier()
        .rules()
        .iter()
        .map(|rule| {
            json!({
                "category": rule.category().as_str(),
                "phase": rule.phase().as_str(),
                "retryable": rule.action().is_retryable(),
                "skip": rule
                    .action()
                    .skip_disposition()
                    .map_or(Value::Null, |skip| Value::String(skip.as_str().to_owned()))
            })
        })
        .collect();
    json!({
        "backoff": {
            "initial_ms": u64::try_from(backoff.initial().as_millis()).unwrap_or(u64::MAX),
            "kind": backoff.kind().as_str(),
            "maximum_ms": u64::try_from(backoff.maximum().as_millis()).unwrap_or(u64::MAX),
            "multiplier": backoff.multiplier()
        },
        "classifier": {
            "revision": policy.classifier().revision().as_str(),
            "rules": rules
        },
        "retry_limit": policy.retry_limit().get(),
        "retry_state_limit": policy.retry_state_limit().get(),
        "skip_limit": policy.skip_limit().get()
    })
}

/// Projects the compiled graph into its canonical restart-relevant manifest.
///
/// The projection carries exactly the values that select or reinterpret durable
/// state. Framework capacity bounds are deliberately absent: they belong to the
/// runtime that reads a manifest, not to the definition it identifies, so
/// raising one in a later release must not change a fingerprint. `MAX_NODES`
/// and `MAX_TRANSITIONS` are enforced against the graph a manifest declares by
/// [`DefinitionManifest::read`](oxide_batch_core::DefinitionManifest::read).
fn flow_manifest(
    job_name: &JobName,
    entry: &NodeId,
    nodes: &BTreeMap<NodeId, FlowNode>,
    transitions: &BTreeMap<NodeId, Vec<FlowTransition>>,
    local_scale: bool,
) -> Value {
    let node_values: Vec<Value> = nodes.values().map(FlowNode::manifest_value).collect();
    let transition_values: Vec<Value> = transitions
        .values()
        .flat_map(|edges| edges.iter().map(FlowTransition::manifest_value))
        .collect();
    json!({
        "entry": entry.as_str(),
        "format": if local_scale {
            oxide_batch_core::MANIFEST_FORMAT_LOCAL_SCALE
        } else {
            oxide_batch_core::MANIFEST_FORMAT_FLOW
        },
        "job": job_name.as_str(),
        "nodes": node_values,
        "transitions": transition_values
    })
}

/// A validated, immutable execution plan.
///
/// A plan owns the exact canonical manifest and fingerprint that identify the
/// definition across restart. A plan lowered from a one-step wrapper retains
/// that wrapper's original format-1 manifest bytes instead of emitting new
/// ones, so lowering never changes a persisted identity.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompiledExecutionPlan {
    definition: DefinitionIdentity,
    job_restart_policy: RestartPolicy,
    parameter_incrementer: Option<ParameterIncrementerIdentity>,
    scoped_components: BTreeMap<(ScopeKind, ScopedComponentId), ScopedComponentDefinition>,
    entry: NodeId,
    root_scope: CompiledFlowScope,
    nodes: BTreeMap<NodeId, FlowNode>,
    transitions: BTreeMap<NodeId, Vec<FlowTransition>>,
    split_branch_scopes: BTreeMap<(NodeId, usize), CompiledFlowScope>,
    nested_scopes: BTreeMap<NodeId, CompiledFlowScope>,
    decision_sequences: BTreeMap<NodeId, u64>,
}

impl CompiledExecutionPlan {
    /// Lowers one validated wrapper step into an in-memory compatibility plan.
    ///
    /// The plan reuses `definition` unchanged, so its manifest bytes, format,
    /// and fingerprint stay exactly what the wrapper persisted. The synthetic
    /// graph maps the framework's own exit codes onto terminals and adds no
    /// node an application could observe as a new durable decision.
    #[doc(hidden)]
    pub fn compatibility_one_step(
        definition: DefinitionIdentity,
        step: StepNode,
    ) -> Result<Self, PlanError> {
        let entry = step.id().clone();
        let mut nodes = BTreeMap::new();
        nodes.insert(entry.clone(), FlowNode::step(step));
        let mut edges = Vec::with_capacity(3);
        for (code, terminal) in [
            ("COMPLETED", TerminalKind::Complete),
            ("FAILED", TerminalKind::Fail),
            ("STOPPED", TerminalKind::Stop),
        ] {
            edges.push(FlowTransition::new(
                entry.clone(),
                ExitPattern::new(code)?,
                FlowTarget::Terminal(terminal),
            ));
        }
        check_unambiguous(&entry, &edges)?;
        let mut transitions = BTreeMap::new();
        transitions.insert(entry.clone(), edges);
        Ok(Self {
            definition,
            job_restart_policy: RestartPolicy::Restartable,
            parameter_incrementer: None,
            scoped_components: BTreeMap::new(),
            root_scope: CompiledFlowScope::new(entry.clone(), nodes.keys().cloned().collect()),
            entry,
            nodes,
            transitions,
            split_branch_scopes: BTreeMap::new(),
            nested_scopes: BTreeMap::new(),
            decision_sequences: BTreeMap::new(),
        })
    }

    /// Borrows the restart-relevant definition identity.
    #[must_use]
    pub const fn definition_identity(&self) -> &DefinitionIdentity {
        &self.definition
    }

    /// Returns the execution-definition restart policy for this job.
    #[must_use]
    pub const fn job_restart_policy(&self) -> RestartPolicy {
        self.job_restart_policy
    }

    /// Borrows the restart-relevant parameter-incrementer identity, when declared.
    #[must_use]
    pub const fn parameter_incrementer_identity(&self) -> Option<&ParameterIncrementerIdentity> {
        self.parameter_incrementer.as_ref()
    }

    /// Iterates scoped component definitions in canonical scope/ID order.
    #[must_use]
    pub fn scoped_components(&self) -> impl ExactSizeIterator<Item = &ScopedComponentDefinition> {
        self.scoped_components.values()
    }

    /// Borrows one scoped component definition by scope and logical ID.
    #[must_use]
    pub fn scoped_component(
        &self,
        scope: ScopeKind,
        id: &ScopedComponentId,
    ) -> Option<&ScopedComponentDefinition> {
        self.scoped_components.get(&(scope, id.clone()))
    }

    /// Returns the canonical manifest format this plan is identified by.
    #[must_use]
    pub const fn manifest_format(&self) -> u16 {
        self.definition.manifest_format()
    }

    /// Returns the SHA-256 definition fingerprint.
    #[must_use]
    pub const fn fingerprint(&self) -> &[u8; 32] {
        self.definition.manifest_digest()
    }

    /// Borrows the entry node identifier.
    #[must_use]
    pub const fn entry(&self) -> &NodeId {
        &self.entry
    }

    /// Borrows the root execution scope.
    #[must_use]
    pub const fn root_scope(&self) -> &CompiledFlowScope {
        &self.root_scope
    }

    /// Borrows one M7 split-branch execution scope by zero-based branch ordinal.
    #[must_use]
    pub fn split_branch_scope(&self, split: &NodeId, ordinal: usize) -> Option<&CompiledFlowScope> {
        self.split_branch_scopes.get(&(split.clone(), ordinal))
    }

    /// Borrows one flattened nested-flow scope by structural owner ID.
    #[must_use]
    pub fn nested_scope(&self, owner: &NodeId) -> Option<&CompiledFlowScope> {
        self.nested_scopes.get(owner)
    }

    /// Returns the canonical format-4 decision sequence for one transition source.
    ///
    /// Formats 1-3 return `None` and retain their historical append sequence.
    #[must_use]
    pub fn decision_sequence(&self, source: &NodeId) -> Option<u64> {
        self.decision_sequences.get(source).copied()
    }

    /// Returns the compiled node count.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Returns the compiled transition count.
    #[must_use]
    pub fn transition_count(&self) -> usize {
        self.transitions.values().map(Vec::len).sum()
    }

    /// Borrows one compiled node.
    #[must_use]
    pub fn node(&self, id: &NodeId) -> Option<&FlowNode> {
        self.nodes.get(id)
    }

    /// Iterates over compiled nodes in stable logical-identifier order.
    ///
    /// The returned order is canonical and independent of builder declaration
    /// order. It is useful when binding executable components to an immutable
    /// plan before launch.
    #[must_use]
    pub fn nodes(&self) -> impl ExactSizeIterator<Item = (&NodeId, &FlowNode)> {
        self.nodes.iter()
    }

    /// Borrows one node's transitions in evaluation order.
    ///
    /// The first matching transition wins, so the slice is ordered from the
    /// most specific pattern to the least specific one.
    #[must_use]
    pub fn transitions(&self, id: &NodeId) -> &[FlowTransition] {
        self.transitions.get(id).map_or(&[], Vec::as_slice)
    }

    /// Selects the target one node's exit outcome reaches.
    ///
    /// # Errors
    ///
    /// Returns [`FlowSelectionError::UnknownNode`] when `id` is not compiled
    /// into this plan and [`FlowSelectionError::UnmappedExitOutcome`] when no
    /// declared pattern matches `code`. The plan never selects an arbitrary
    /// default.
    pub fn select_target(
        &self,
        id: &NodeId,
        code: &ExitCode,
    ) -> Result<&FlowTarget, FlowSelectionError> {
        let edges = self
            .transitions
            .get(id)
            .ok_or_else(|| FlowSelectionError::UnknownNode { node: id.clone() })?;
        edges
            .iter()
            .find(|edge| edge.pattern().matches(code))
            .map(FlowTransition::target)
            .ok_or_else(|| FlowSelectionError::UnmappedExitOutcome {
                node: id.clone(),
                code: code.clone(),
            })
    }
}

/// A flow graph that cannot be compiled into an executable plan.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PlanError {
    /// No entry node was declared.
    MissingEntryNode,
    /// Two nodes declared the same logical identifier.
    DuplicateNodeId {
        /// Repeated identifier.
        node: NodeId,
    },
    /// A transition referenced a node the graph does not declare.
    UndefinedNode {
        /// Missing identifier.
        node: NodeId,
    },
    /// A node declared no outgoing transition.
    MissingTransition {
        /// Identifier of the node without a transition.
        node: NodeId,
    },
    /// Two equally specific patterns can match one exit outcome.
    AmbiguousTransition {
        /// Identifier of the node with the ambiguity.
        node: NodeId,
        /// First conflicting pattern.
        first: ExitPattern,
        /// Second conflicting pattern.
        second: ExitPattern,
    },
    /// A node cannot be reached from the entry node.
    UnreachableNode {
        /// Unreachable identifier.
        node: NodeId,
    },
    /// The graph contains a cycle.
    CyclicGraph {
        /// Identifier revisited on one path.
        node: NodeId,
    },
    /// The graph declared more nodes than M3 accepts.
    TooManyNodes {
        /// Maximum accepted node count.
        max: usize,
    },
    /// The graph declared more transitions than M3 accepts.
    TooManyTransitions {
        /// Maximum accepted transition count.
        max: usize,
    },
    /// One node declared more outgoing transitions than M3 accepts.
    TooManyOutgoingTransitions {
        /// Identifier of the node with too many transitions.
        node: NodeId,
        /// Maximum accepted outgoing transition count.
        max: usize,
    },
    /// An exit pattern violated its bounded format.
    InvalidPattern {
        /// Maximum accepted pattern length in UTF-8 bytes.
        max_bytes: usize,
    },
    /// A decision input-contract version of zero is not a version.
    ZeroDecisionInputVersion,
    /// A split declared fewer than two or more than eight branches.
    InvalidSplitBranchCount {
        /// Split whose branch count was invalid.
        split: NodeId,
        /// Minimum accepted branch count.
        min: usize,
        /// Maximum accepted branch count.
        max: usize,
    },
    /// A split branch was empty or longer than the accepted bound.
    InvalidBranchLength {
        /// Owning split.
        split: NodeId,
        /// Maximum accepted branch length.
        max: usize,
    },
    /// A split was declared as the graph entry.
    SplitIsEntry {
        /// Rejected split.
        split: NodeId,
    },
    /// A split did not reference a declared structural join.
    InvalidSplitJoin {
        /// Owning split.
        split: NodeId,
        /// Missing or wrongly typed join.
        join: NodeId,
    },
    /// More than one split tried to own the same join.
    JoinHasMultipleOwners {
        /// Multiply owned join.
        join: NodeId,
        /// First owning split.
        first: NodeId,
        /// Second owning split.
        second: NodeId,
    },
    /// A join was not owned by any split.
    OrphanJoin {
        /// Unowned join.
        join: NodeId,
    },
    /// A normal transition attempted to enter a structural join.
    JoinHasExternalEntry {
        /// Join with an external incoming edge.
        join: NodeId,
    },
    /// A split tried to bypass its implicit join edge.
    SplitHasExplicitTransition {
        /// Split with the explicit edge.
        split: NodeId,
    },
    /// The branch concurrency budget exceeded the declared branch count.
    ParallelBudgetExceedsBranches {
        /// Split with the contradictory budget.
        split: NodeId,
        /// Declared branch count.
        branches: usize,
    },
    /// A branch concurrency budget was zero or above the M4 ceiling.
    InvalidParallelBranchBudget {
        /// Maximum accepted branch concurrency.
        max: usize,
    },
    /// A partition-worker budget was zero or above the M4 ceiling.
    InvalidPartitionWorkerBudget {
        /// Maximum accepted worker concurrency.
        max: u8,
    },
    /// The declared pool cannot supply active children plus their parent.
    InsufficientPoolCapacity {
        /// Minimum required connection count.
        required: u32,
        /// Declared connection count.
        configured: u32,
    },
    /// A durable partition count was zero or above the M4 ceiling.
    InvalidPartitionCount {
        /// Maximum accepted partition count.
        max: u16,
    },
    /// M7 composition exceeded the bounded structural nesting depth.
    CompositionDepthExceeded {
        /// Maximum accepted composition depth.
        max: usize,
    },
    /// A nested-flow terminal class had no owner transition.
    UnmappedNestedFlowExit {
        /// Structural nested-flow owner.
        flow: NodeId,
        /// Normalized terminal outcome that could not be routed.
        code: ExitCode,
    },
    /// A structured selector path exceeded its closed bounded shape.
    InvalidSelectorPath {
        /// Maximum accepted encoded path bytes.
        max_bytes: usize,
        /// Maximum accepted segment count.
        max_segments: usize,
    },
    /// A nested-job child definition had no bound job identity.
    NestedJobMissingChildIdentity {
        /// Nested-job node with the unbound child.
        node: NodeId,
    },
    /// A graph declared more scoped components than the M7 ceiling.
    TooManyScopedComponents {
        /// Maximum accepted scoped component count.
        max: usize,
    },
    /// Two declarations reused one scope/component logical identity.
    DuplicateScopedComponent {
        /// Repeated scope.
        scope: ScopeKind,
        /// Repeated logical component identifier.
        component: ScopedComponentId,
    },
    /// Two repeat declarations reused one logical repeat identity.
    DuplicateRepeatId {
        /// Repeated repeat identity.
        repeat: RepeatId,
    },
    /// A nested job declared more child parameters than the M7 ceiling.
    TooManyNestedJobParameters {
        /// Nested-job node over the limit.
        node: NodeId,
        /// Maximum accepted mapping count.
        max: usize,
    },
    /// Two mappings targeted the same child parameter.
    DuplicateNestedJobParameter {
        /// Nested-job node with the duplicate target.
        node: NodeId,
        /// Repeated child parameter name.
        parameter: ParameterName,
    },
    /// A logical identifier or revision token was invalid.
    Token(DefinitionError),
    /// The canonical manifest could not be encoded within its bound.
    Manifest(DefinitionError),
}

impl fmt::Display for PlanError {
    #[allow(
        clippy::too_many_lines,
        reason = "each typed plan rejection retains one stable redacted diagnostic"
    )]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingEntryNode => formatter.write_str("flow graph has no entry node"),
            Self::DuplicateNodeId { node } => {
                write!(
                    formatter,
                    "node {} is declared more than once",
                    node.as_str()
                )
            }
            Self::UndefinedNode { node } => {
                write!(formatter, "node {} is not declared", node.as_str())
            }
            Self::MissingTransition { node } => {
                write!(
                    formatter,
                    "node {} has no outgoing transition",
                    node.as_str()
                )
            }
            Self::AmbiguousTransition {
                node,
                first,
                second,
            } => write!(
                formatter,
                "node {} patterns {first} and {second} are equally specific and overlap",
                node.as_str()
            ),
            Self::UnreachableNode { node } => {
                write!(
                    formatter,
                    "node {} is unreachable from the entry node",
                    node.as_str()
                )
            }
            Self::CyclicGraph { node } => {
                write!(formatter, "node {} closes a cycle", node.as_str())
            }
            Self::TooManyNodes { max } => write!(formatter, "flow graph exceeds {max} nodes"),
            Self::TooManyTransitions { max } => {
                write!(formatter, "flow graph exceeds {max} transitions")
            }
            Self::TooManyOutgoingTransitions { node, max } => write!(
                formatter,
                "node {} exceeds {max} outgoing transitions",
                node.as_str()
            ),
            Self::InvalidPattern { max_bytes } => write!(
                formatter,
                "exit pattern must be 1 to {max_bytes} bytes without control characters"
            ),
            Self::ZeroDecisionInputVersion => {
                formatter.write_str("decision input version must be nonzero")
            }
            Self::InvalidSplitBranchCount { split, min, max } => write!(
                formatter,
                "split {} must declare {min} to {max} branches",
                split.as_str()
            ),
            Self::InvalidBranchLength { split, max } => write!(
                formatter,
                "split {} branches must declare 1 to {max} steps",
                split.as_str()
            ),
            Self::SplitIsEntry { split } => {
                write!(
                    formatter,
                    "split {} cannot be the entry node",
                    split.as_str()
                )
            }
            Self::InvalidSplitJoin { split, join } => write!(
                formatter,
                "split {} does not own declared join {}",
                split.as_str(),
                join.as_str()
            ),
            Self::JoinHasMultipleOwners {
                join,
                first,
                second,
            } => write!(
                formatter,
                "join {} is owned by both splits {} and {}",
                join.as_str(),
                first.as_str(),
                second.as_str()
            ),
            Self::OrphanJoin { join } => {
                write!(formatter, "join {} has no owning split", join.as_str())
            }
            Self::JoinHasExternalEntry { join } => write!(
                formatter,
                "join {} can be entered only by its owning split",
                join.as_str()
            ),
            Self::SplitHasExplicitTransition { split } => write!(
                formatter,
                "split {} reaches only its declared join",
                split.as_str()
            ),
            Self::ParallelBudgetExceedsBranches { split, branches } => write!(
                formatter,
                "split {} parallel budget exceeds its {branches} branches",
                split.as_str()
            ),
            Self::InvalidParallelBranchBudget { max } => {
                write!(formatter, "parallel branch budget must be 1 to {max}")
            }
            Self::InvalidPartitionWorkerBudget { max } => {
                write!(formatter, "partition worker budget must be 1 to {max}")
            }
            Self::InsufficientPoolCapacity {
                required,
                configured,
            } => write!(
                formatter,
                "repository pool size {configured} cannot supply required capacity {required}"
            ),
            Self::InvalidPartitionCount { max } => {
                write!(formatter, "partition count must be 1 to {max}")
            }
            Self::CompositionDepthExceeded { max } => {
                write!(formatter, "flow composition exceeds depth {max}")
            }
            Self::InvalidSelectorPath {
                max_bytes,
                max_segments,
            } => write!(
                formatter,
                "selector path must contain 1 to {max_segments} bounded segments within {max_bytes} bytes"
            ),
            Self::NestedJobMissingChildIdentity { node } => write!(
                formatter,
                "nested job {} requires a bound child definition identity",
                node.as_str()
            ),
            Self::TooManyScopedComponents { max } => {
                write!(formatter, "flow graph exceeds {max} scoped components")
            }
            Self::DuplicateScopedComponent { scope, component } => write!(
                formatter,
                "{} scope component {} is declared more than once",
                scope.as_str(),
                component.as_str()
            ),
            Self::DuplicateRepeatId { repeat } => write!(
                formatter,
                "repeat {} is declared more than once in the compiled plan",
                repeat.as_str()
            ),
            Self::TooManyNestedJobParameters { node, max } => write!(
                formatter,
                "nested job {} exceeds {max} child parameters",
                node.as_str()
            ),
            Self::DuplicateNestedJobParameter { node, parameter } => write!(
                formatter,
                "nested job {} maps child parameter {} more than once",
                node.as_str(),
                parameter.as_str()
            ),
            Self::UnmappedNestedFlowExit { flow, code } => write!(
                formatter,
                "nested flow {} declares no transition for terminal outcome {code}",
                flow.as_str()
            ),
            Self::Token(error) => write!(formatter, "flow graph token is invalid: {error}"),
            Self::Manifest(error) => {
                write!(formatter, "flow manifest could not be encoded: {error}")
            }
        }
    }
}

impl Error for PlanError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Token(error) | Self::Manifest(error) => Some(error),
            _ => None,
        }
    }
}

impl From<DefinitionError> for PlanError {
    fn from(error: DefinitionError) -> Self {
        Self::Token(error)
    }
}

/// A compiled plan that cannot route one observed exit outcome.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum FlowSelectionError {
    /// The requested node is not part of this plan.
    UnknownNode {
        /// Requested identifier.
        node: NodeId,
    },
    /// No declared pattern matches the produced exit outcome.
    UnmappedExitOutcome {
        /// Node whose outcome could not be routed.
        node: NodeId,
        /// Produced exit code.
        code: ExitCode,
    },
}

impl fmt::Display for FlowSelectionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownNode { node } => {
                write!(
                    formatter,
                    "node {} is not part of the compiled plan",
                    node.as_str()
                )
            }
            Self::UnmappedExitOutcome { node, code } => write!(
                formatter,
                "node {} declares no transition for exit outcome {code}",
                node.as_str()
            ),
        }
    }
}

impl Error for FlowSelectionError {}