khive-request 0.2.6

Request DSL — parses verb-dispatch strings (function-call, JSON, and future LNDL / pipe / bash-style syntaxes) into a transport-agnostic ParsedRequest AST
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
//! `khive-request` — request-DSL parser, transport-agnostic.
//!
//! ## Scope
//!
//! Conceptually every transport into khive walks the same pipeline:
//!
//! ```text
//! request string  →  parse  →  ParsedRequest  →  dispatch (VerbRegistry)  →  result
//! ```
//!
//! This crate owns only the *parse* step. The AST it produces (`ParsedRequest`,
//! `ParsedOp`) is consumed by transports (MCP today; HTTP gateway, FFI, CLI
//! in future) which then dispatch through `khive-runtime`'s [`VerbRegistry`].
//!
//! Keeping the parser in its own crate frees us to grow the syntax — pipe
//! chains, `$prev` substitution, LNDL-style natural-language declarations,
//! bash-flavoured redirections — without touching the runtime layering.
//!
//! ## Today's syntax (ADR-016)
//!
//! - **Single op**: `tool_name(arg=value, arg=value)` — `ExecutionMode::Single`
//! - **Parallel batch**: `[tool_name(...), tool_name(...)]` — `ExecutionMode::Parallel`
//! - **Sequential chain**: `op1(...) | op2(id=$prev.id)` — `ExecutionMode::Chain`
//! - **JSON form**: `[{"tool":"...", "args": {...}}, ...]` (or a single object)
//!
//! Argument values are JSON literals — strings, numbers, booleans, `null`,
//! arrays, objects. Chain-only: `$prev` and `$prev.field.path` references resolve
//! at dispatch time against the preceding op's result.

use std::collections::BTreeMap;
use std::fmt;

use serde_json::{Map, Value};

/// Hard cap on operations per request. ADR-016 §Why-100.
pub const MAX_OPS: usize = 100;

/// Execution mode for a [`ParsedRequest`] (ADR-016).
///
/// - `Single`: one operation, no batching.
/// - `Parallel`: operations separated by `,` inside `[...]`; run concurrently,
///   results in input order.
/// - `Chain`: operations separated by `|`; run sequentially, each op may
///   reference the prior op's result via `$prev` / `$prev.field.path`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecutionMode {
    /// One operation, no batching or chaining.
    Single,
    /// `[op1(...), op2(...)]` — parallel, best-effort, independent results.
    Parallel,
    /// `op1(...) | op2(id=$prev.id)` — sequential, abort-on-failure.
    Chain,
}

/// An argument value in a [`ParsedOp`].
///
/// Most arguments are concrete JSON values. In chain ops (ADR-016 §Chain
/// semantics), arguments may reference the preceding op's result via `$prev`
/// or `$prev.dotted.path`. Substitution happens at dispatch time, not at parse
/// time, because the prior result isn't known until runtime.
///
/// `$prev` references may also appear inside array or object literals, which is
/// why `Array` and `Object` variants exist alongside the flat `PrevRef` variant.
/// The dispatcher resolves these recursively before calling the verb handler.
#[derive(Debug, Clone, PartialEq)]
pub enum ArgValue {
    /// A concrete JSON value (no `$prev` references anywhere inside).
    Value(Value),
    /// A `$prev` or `$prev.field.path` reference — chain mode only.
    ///
    /// `path` is the dot-separated field path after `$prev`. Empty string means
    /// the whole prior result (`$prev` with no field selector).
    PrevRef { path: String },
    /// An array literal whose elements may themselves be `ArgValue`s (including
    /// nested `PrevRef` or further `Array`/`Object`).  Used when at least one
    /// element contains a `$prev` reference; pure-JSON arrays are still
    /// represented as `Value(Value::Array(_))` for efficiency.
    Array(Vec<ArgValue>),
    /// An object literal whose values may themselves be `ArgValue`s.  Used when
    /// at least one value contains a `$prev` reference; pure-JSON objects are
    /// still represented as `Value(Value::Object(_))`.
    Object(Vec<(String, ArgValue)>),
}

impl ArgValue {
    /// Returns the contained [`Value`] if this is `ArgValue::Value`.
    pub fn as_value(&self) -> Option<&Value> {
        match self {
            ArgValue::Value(v) => Some(v),
            ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
        }
    }

    /// Returns `true` if this is a `$prev` reference.
    pub fn is_prev_ref(&self) -> bool {
        matches!(self, ArgValue::PrevRef { .. })
    }

    /// Resolve a `$prev` reference against a preceding op's result.
    ///
    /// Returns the extracted field value, or `None` if the path doesn't
    /// exist in `prev_result`. Non-`PrevRef` variants return `None`.
    ///
    /// Path segments may include array indices: `$prev.items[0].id` or
    /// `$prev[0].name`. Bracket indices are parsed as `usize` (ue-dsl-chain H1).
    pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
        let ArgValue::PrevRef { path } = self else {
            return None;
        };
        if path.is_empty() {
            return Some(prev_result);
        }
        let mut cur = prev_result;
        for segment in split_path(path) {
            cur = apply_path_segment(cur, segment)?;
        }
        Some(cur)
    }

    /// Recursively resolve all `$prev` references within this value.
    ///
    /// - `PrevRef`: resolved via `resolve_prev`.
    /// - `Array`/`Object`: each element/value is resolved recursively.
    /// - `Value`: returned as-is (no `$prev` anywhere inside).
    ///
    /// Returns `None` if any `$prev` path is missing from `prev_result`.
    pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
        match self {
            ArgValue::Value(v) => Some(v.clone()),
            ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
            ArgValue::Array(elements) => {
                let mut out = Vec::with_capacity(elements.len());
                for el in elements {
                    out.push(el.resolve_all(prev_result)?);
                }
                Some(Value::Array(out))
            }
            ArgValue::Object(pairs) => {
                let mut map = serde_json::Map::with_capacity(pairs.len());
                for (key, val) in pairs {
                    map.insert(key.clone(), val.resolve_all(prev_result)?);
                }
                Some(Value::Object(map))
            }
        }
    }
}

/// A single parsed operation: tool name + named argument bag.
///
/// Arguments may be concrete [`ArgValue::Value`]s or `$prev` references
/// ([`ArgValue::PrevRef`]) that the dispatcher resolves against the prior op's
/// result (chain mode only).
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedOp {
    pub tool: String,
    pub args: BTreeMap<String, ArgValue>,
}

/// Result of parsing a `request` input string (ADR-016).
///
/// The `mode` field tells the dispatcher how to execute the operations:
/// - `Single`: dispatch the one op, wrap in a single-element envelope.
/// - `Parallel`: dispatch all ops concurrently via `join_all`, collect in order.
/// - `Chain`: dispatch ops sequentially; substitute `$prev` references between
///   ops; abort remaining ops when any op or substitution fails.
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedRequest {
    pub ops: Vec<ParsedOp>,
    pub mode: ExecutionMode,
}

/// Parser error — surfaced as `invalid_params` at the MCP boundary.
#[derive(Debug, Clone, PartialEq)]
pub enum DslError {
    Empty,
    TooManyOps {
        count: usize,
        max: usize,
    },
    UnexpectedChar {
        pos: usize,
        found: char,
        expected: &'static str,
    },
    UnexpectedEof {
        expected: &'static str,
    },
    InvalidIdentifier {
        pos: usize,
    },
    DuplicateArg {
        name: String,
    },
    InvalidValue {
        pos: usize,
        error: String,
    },
    InvalidJson {
        error: String,
    },
    UnclosedString,
    UnclosedBracket {
        kind: char,
    },
    /// `$prev` reference used outside a chain context (emitted by the parser for
    /// Single-op and Parallel-batch forms, and for JSON form).
    ///
    /// # Policy
    ///
    /// `$prev` references are only meaningful in chain (`|`) mode. If they appear
    /// in a non-chain context the parser rejects the request here so downstream
    /// consumers that pattern-match on `DslError` get a typed error rather than
    /// a runtime string.
    PrevRefOutsideChain {
        pos: usize,
    },
    /// `$prev` found in JSON-form input — JSON form does not support chains.
    ///
    /// JSON form (`[{"tool":"...","args":{...}},...]`) always runs in parallel.
    /// To use `$prev` substitution, use the function-call DSL with the `|` chain
    /// operator: `verb1(...) | verb2(id=$prev.id)`.
    PrevRefInJsonForm {
        arg_name: String,
    },
    /// Mixing `,` and `|` at the top level.
    MixedSeparators,
    /// Empty batch `[]` — no ops provided.
    EmptyBatch,
    /// Dotted verb name with more than one level (e.g. `a.b.c`). Only
    /// single-level dotted names are supported (`a.b`).
    UnsupportedVerbNesting {
        pos: usize,
    },
    /// Two or more ops in a parallel batch write to the same UUID (ADR-038).
    ///
    /// Write-key conflict detection is a preflight check applied after parsing.
    /// Write ops are: `update`, `delete`, `merge`, `link`. When two ops share the
    /// same `id` (or `into_id` / `from_id` for `merge`, `source_id`/`target_id`
    /// for `link`) the batch is rejected before any op is dispatched.
    WriteKeyConflict {
        /// The duplicated UUID.
        id: String,
        /// Name of the first op that claimed the key.
        first_op: String,
        /// Name of the second op that conflicts.
        second_op: String,
    },
}

impl fmt::Display for DslError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DslError::Empty => write!(f, "request is empty"),
            DslError::TooManyOps { count, max } => {
                write!(f, "batch has {count} ops; max is {max}")
            }
            DslError::UnexpectedChar {
                pos,
                found,
                expected,
            } => {
                write!(f, "at position {pos}: expected {expected}, found {found:?}")
            }
            DslError::UnexpectedEof { expected } => {
                write!(f, "unexpected end of input; expected {expected}")
            }
            DslError::InvalidIdentifier { pos } => {
                write!(
                    f,
                    "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
                )
            }
            DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
            DslError::InvalidValue { pos, error } => {
                write!(f, "at position {pos}: invalid value: {error}")
            }
            DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
            DslError::UnclosedString => write!(f, "unterminated string literal"),
            DslError::UnclosedBracket { kind } => {
                write!(f, "unclosed bracket: {kind:?} has no matching close")
            }
            DslError::PrevRefOutsideChain { pos } => {
                write!(
                    f,
                    "at position {pos}: $prev reference is only valid in chain (|) mode; \
                     use function-call form with '|' to chain ops"
                )
            }
            DslError::PrevRefInJsonForm { arg_name } => {
                write!(
                    f,
                    "argument {arg_name:?}: $prev substitution requires the function-call DSL \
                     with the chain (|) operator; JSON form does not support chains. \
                     Use: verb1(...) | verb2({arg_name}=$prev.id)"
                )
            }
            DslError::MixedSeparators => {
                write!(
                    f,
                    "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
                )
            }
            DslError::EmptyBatch => {
                write!(f, "empty batch not allowed; provide at least one op")
            }
            DslError::UnsupportedVerbNesting { pos } => {
                write!(
                    f,
                    "at position {pos}: only single-level dotted verb names are supported \
                     (e.g. brain.state); use a shorter name or register a pack alias"
                )
            }
            DslError::WriteKeyConflict {
                id,
                first_op,
                second_op,
            } => {
                write!(
                    f,
                    "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
                     {second_op:?} in the same batch; split into separate requests"
                )
            }
        }
    }
}

impl std::error::Error for DslError {}

/// Check a parsed batch for write-key conflicts (ADR-038 preflight).
///
/// Write operations (`update`, `delete`, `merge`, `link`) target specific UUIDs.
/// If two ops in the same parallel (or single-op) batch write to the same UUID,
/// the batch is rejected before any op is dispatched.
///
/// Chain mode is excluded: sequential ops intentionally build on prior results
/// and the runtime resolves `$prev` references between them.
///
/// The checked keys per verb:
/// - `update` / `delete`: `id`
/// - `merge`:             `into_id`, `from_id`
/// - `link`:              `source_id`, `target_id`
///
/// Only concrete `ArgValue::Value(String)` arguments are checked; `$prev`
/// references are skipped because their target is not known until dispatch time.
pub fn check_write_key_conflicts(req: &ParsedRequest) -> Result<(), DslError> {
    // Chain mode is sequentially ordered; skip conflict detection.
    if req.mode == ExecutionMode::Chain {
        return Ok(());
    }
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for op in &req.ops {
        let keys = write_keys_for_op(op);
        for key in keys {
            if let Some(first) = seen.get(&key) {
                return Err(DslError::WriteKeyConflict {
                    id: key,
                    first_op: first.clone(),
                    second_op: op.tool.clone(),
                });
            }
            seen.insert(key, op.tool.clone());
        }
    }
    Ok(())
}

/// Extract write-conflict keys from a single op for preflight conflict detection (ADR-038).
///
/// Keys are substrate-prefixed to avoid false positives between different substrates:
/// - Entity write ops (`update`, `delete`, `merge`): `entity:<uuid>`
/// - Edge write ops (`link`): `edge-natural:<source_id>:<target_id>:<relation>`
///   — `link` creates an edge record, NOT an entity write, so source/target entity
///   IDs must NOT be used as entity-level keys.
///
/// Only concrete `ArgValue::Value(String)` args are checked; `$prev` refs are skipped.
///
/// # Why `create` is excluded
///
/// `create` generates its UUID server-side and the ID is not statically known at parse
/// time, so there is no key to conflict on.  The existing DB-level serialization handles
/// concurrent creates safely (unique constraint on the generated UUID).
///
/// This function is `pub` so the MCP server can call it directly without the full
/// `check_write_key_conflicts` batch-level function.
pub fn write_keys_for_op_pub(op: &ParsedOp) -> Vec<String> {
    let mut keys = Vec::new();
    match op.tool.as_str() {
        "update" | "delete" => {
            if let Some(ArgValue::Value(Value::String(s))) = op.args.get("id") {
                keys.push(format!("entity:{s}"));
            }
        }
        "merge" => {
            for name in &["into_id", "from_id"] {
                if let Some(ArgValue::Value(Value::String(s))) = op.args.get(*name) {
                    keys.push(format!("entity:{s}"));
                }
            }
        }
        "link" => {
            // `link` writes an edge, not an entity.  Use a natural-key format so
            // update(id="X") + link(source_id="X", ...) do NOT conflict (they target
            // different substrates).
            let src = op.args.get("source_id");
            let tgt = op.args.get("target_id");
            let rel = op.args.get("relation");
            if let (
                Some(ArgValue::Value(Value::String(s))),
                Some(ArgValue::Value(Value::String(t))),
                Some(ArgValue::Value(Value::String(r))),
            ) = (src, tgt, rel)
            {
                keys.push(format!("edge-natural:{s}:{t}:{r}"));
            }
        }
        _ => {}
    }
    keys
}

/// Extract the write-key UUIDs from a single op (internal helper, kept for tests).
fn write_keys_for_op(op: &ParsedOp) -> Vec<String> {
    write_keys_for_op_pub(op)
}

/// Parse a request input string, returning either a single op or a batch.
pub fn parse_request(input: &str) -> Result<ParsedRequest, DslError> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Err(DslError::Empty);
    }

    // JSON form: `[{...}, ...]` or `{...}`. After `[`, JSON whitespace is legal
    // before the first element — common when pretty-printers emit `[ {...} ]`.
    let first = trimmed.as_bytes()[0];
    let looks_like_json = first == b'{'
        || (first == b'['
            && trimmed
                .as_bytes()
                .iter()
                .skip(1)
                .find(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
                .is_some_and(|b| *b == b'{'));
    if looks_like_json {
        return parse_json_form(trimmed);
    }

    // Function-call batch `[...]` — parallel.
    if first == b'[' {
        return parse_fn_batch(trimmed);
    }

    // Chain or single: starts with an identifier.
    // Parse the first op, then check for `|` to detect chain mode.
    let mut p = Parser::new(trimmed);
    let first_op = p.parse_op()?;
    p.skip_ws();

    if p.eof() {
        // Single op — no separator follows.
        // PrevRef in a single op is always invalid (adr-dsl-packs H1).
        if let Some(pos) = find_prev_ref_pos(&first_op) {
            return Err(DslError::PrevRefOutsideChain { pos });
        }
        return Ok(ParsedRequest {
            ops: vec![first_op],
            mode: ExecutionMode::Single,
        });
    }

    if p.peek() == Some('|') {
        // Chain mode: `op1 | op2 | ...`
        return parse_chain_tail(p, first_op);
    }

    // Unexpected trailing content after a single op.
    Err(DslError::UnexpectedChar {
        pos: p.pos,
        found: p.peek().unwrap(),
        expected: "'|' or end of input",
    })
}

/// Parse the rest of a chain after the first op has been consumed.
///
/// Called when we've seen `first_op` followed by `|`. Parses one or more
/// `| op` segments and returns a `Chain` request.
fn parse_chain_tail(mut p: Parser<'_>, first_op: ParsedOp) -> Result<ParsedRequest, DslError> {
    let mut ops = vec![first_op];
    while p.peek() == Some('|') {
        if ops.len() >= MAX_OPS {
            return Err(DslError::TooManyOps {
                count: ops.len() + 1,
                max: MAX_OPS,
            });
        }
        p.advance(1); // consume '|'
        p.skip_ws();
        let op = p.parse_op()?;
        ops.push(op);
        p.skip_ws();
    }
    if !p.eof() {
        if p.peek() == Some(',') {
            return Err(DslError::MixedSeparators);
        }
        return Err(DslError::UnexpectedChar {
            pos: p.pos,
            found: p.peek().unwrap(),
            expected: "'|' or end of input",
        });
    }
    Ok(ParsedRequest {
        ops,
        mode: ExecutionMode::Chain,
    })
}

fn parse_json_form(input: &str) -> Result<ParsedRequest, DslError> {
    let v: Value = serde_json::from_str(input).map_err(|e| DslError::InvalidJson {
        error: e.to_string(),
    })?;
    let (arr, is_single) = match v {
        Value::Array(arr) => (arr, false),
        Value::Object(_) => (vec![v], true),
        other => {
            return Err(DslError::InvalidJson {
                error: format!("expected object or array of objects, got {other}"),
            })
        }
    };
    if arr.is_empty() && !is_single {
        return Err(DslError::EmptyBatch);
    }
    if arr.len() > MAX_OPS {
        return Err(DslError::TooManyOps {
            count: arr.len(),
            max: MAX_OPS,
        });
    }
    let mut ops = Vec::with_capacity(arr.len());
    for entry in arr {
        let obj = entry.as_object().ok_or_else(|| DslError::InvalidJson {
            error: "each batch entry must be an object".into(),
        })?;
        let tool = obj
            .get("tool")
            .and_then(Value::as_str)
            .ok_or_else(|| DslError::InvalidJson {
                error: "each entry needs a \"tool\" string".into(),
            })?
            .to_owned();
        let args = obj
            .get("args")
            .cloned()
            .unwrap_or_else(|| Value::Object(Map::new()));
        let args_map = match args {
            Value::Object(m) => m,
            other => {
                return Err(DslError::InvalidJson {
                    error: format!("\"args\" must be an object, got {other}"),
                })
            }
        };
        // JSON form does not support $prev references — all args are Values.
        // Recursively scan every arg value (including nested arrays/objects) for
        // any string matching $prev, $prev.*, or $prev[* and reject with a typed
        // PrevRefInJsonForm error (ue-dsl-chain C1, fix: recursive scan).
        let mut args: BTreeMap<String, ArgValue> = BTreeMap::new();
        for (k, v) in args_map {
            if json_value_contains_prev_ref(&v) {
                return Err(DslError::PrevRefInJsonForm { arg_name: k });
            }
            args.insert(k, ArgValue::Value(v));
        }
        ops.push(ParsedOp { tool, args });
    }
    let mode = if is_single {
        ExecutionMode::Single
    } else {
        ExecutionMode::Parallel
    };
    Ok(ParsedRequest { ops, mode })
}

fn parse_fn_batch(input: &str) -> Result<ParsedRequest, DslError> {
    let mut p = Parser::new(input);
    p.expect_char('[')?;
    p.skip_ws();
    let mut ops = Vec::new();
    if p.peek() == Some(']') {
        p.advance(1);
        return Err(DslError::EmptyBatch);
    }
    loop {
        if ops.len() >= MAX_OPS {
            return Err(DslError::TooManyOps {
                count: ops.len() + 1,
                max: MAX_OPS,
            });
        }
        let op = p.parse_op()?;
        ops.push(op);
        p.skip_ws();
        match p.peek() {
            Some(',') => {
                p.advance(1);
                p.skip_ws();
            }
            Some(']') => {
                p.advance(1);
                break;
            }
            Some('|') => return Err(DslError::MixedSeparators),
            Some(c) => {
                return Err(DslError::UnexpectedChar {
                    pos: p.pos,
                    found: c,
                    expected: "',' or ']'",
                });
            }
            None => return Err(DslError::UnexpectedEof { expected: "']'" }),
        }
    }
    p.skip_ws();
    if !p.eof() {
        return Err(DslError::UnexpectedChar {
            pos: p.pos,
            found: p.peek().unwrap(),
            expected: "end of input",
        });
    }
    // PrevRef inside a function-call parallel batch is invalid (adr-dsl-packs H1).
    for op in &ops {
        if let Some(pos) = find_prev_ref_pos(op) {
            return Err(DslError::PrevRefOutsideChain { pos });
        }
    }
    Ok(ParsedRequest {
        ops,
        mode: ExecutionMode::Parallel,
    })
}

// ── recursive-descent parser ────────────────────────────────────────────────

struct Parser<'a> {
    src: &'a [u8],
    pos: usize,
}

impl<'a> Parser<'a> {
    fn new(src: &'a str) -> Self {
        Self {
            src: src.as_bytes(),
            pos: 0,
        }
    }

    fn eof(&self) -> bool {
        self.pos >= self.src.len()
    }

    fn peek(&self) -> Option<char> {
        self.src.get(self.pos).map(|b| *b as char)
    }

    fn advance(&mut self, n: usize) {
        self.pos = (self.pos + n).min(self.src.len());
    }

    fn skip_ws(&mut self) {
        while let Some(c) = self.peek() {
            if c.is_ascii_whitespace() {
                self.advance(1);
            } else {
                break;
            }
        }
    }

    fn expect_char(&mut self, want: char) -> Result<(), DslError> {
        self.skip_ws();
        match self.peek() {
            Some(c) if c == want => {
                self.advance(1);
                Ok(())
            }
            Some(c) => Err(DslError::UnexpectedChar {
                pos: self.pos,
                found: c,
                expected: char_label(want),
            }),
            None => Err(DslError::UnexpectedEof {
                expected: char_label(want),
            }),
        }
    }

    fn parse_identifier(&mut self) -> Result<String, DslError> {
        self.skip_ws();
        let start = self.pos;
        match self.peek() {
            Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
            _ => return Err(DslError::InvalidIdentifier { pos: self.pos }),
        }
        while let Some(c) = self.peek() {
            if c.is_ascii_alphanumeric() || c == '_' {
                self.advance(1);
            } else {
                break;
            }
        }
        Ok(std::str::from_utf8(&self.src[start..self.pos])
            .expect("ascii-only chunk")
            .to_owned())
    }

    fn parse_op(&mut self) -> Result<ParsedOp, DslError> {
        let mut tool = self.parse_identifier()?;
        // One-level dotted verbs: brain.state, recall.candidates
        if self.peek() == Some('.') {
            self.advance(1);
            let sub = self.parse_identifier()?;
            tool = format!("{tool}.{sub}");
            // Only one level of dotting is supported. A second '.' is a clear
            // error (adr-dsl-packs H2) — emit UnsupportedVerbNesting instead of
            // the misleading "expected '|' or end of input, found '.'" message.
            if self.peek() == Some('.') {
                return Err(DslError::UnsupportedVerbNesting { pos: self.pos });
            }
        }
        self.expect_char('(')?;
        self.skip_ws();
        let mut args: BTreeMap<String, ArgValue> = BTreeMap::new();
        if self.peek() == Some(')') {
            self.advance(1);
            return Ok(ParsedOp { tool, args });
        }
        loop {
            let name = self.parse_identifier()?;
            self.expect_char('=')?;
            self.skip_ws();
            let arg_val = self.parse_arg_value()?;
            if args.contains_key(&name) {
                return Err(DslError::DuplicateArg { name });
            }
            args.insert(name, arg_val);
            self.skip_ws();
            match self.peek() {
                Some(',') => {
                    self.advance(1);
                    self.skip_ws();
                }
                Some(')') => {
                    self.advance(1);
                    return Ok(ParsedOp { tool, args });
                }
                Some(c) => {
                    return Err(DslError::UnexpectedChar {
                        pos: self.pos,
                        found: c,
                        expected: "',' or ')'",
                    });
                }
                None => return Err(DslError::UnexpectedEof { expected: "')'" }),
            }
        }
    }

    /// Parse an argument value — either a `$prev` reference, an array/object
    /// literal (which may contain `$prev` refs), or a plain JSON literal.
    ///
    /// CC-3: a quoted string like `"$prev.id"` is treated identically to the
    /// unquoted token `$prev.id`. Both resolve to `ArgValue::PrevRef { path: "id" }`.
    /// To pass the literal string `$prev.id` as a value, escape the leading `$`
    /// in the JSON string: `"\\$prev.id"` deserializes to `\$prev.id`, which is
    /// stripped to `$prev.id` and returned as a concrete `ArgValue::Value`.
    fn parse_arg_value(&mut self) -> Result<ArgValue, DslError> {
        self.skip_ws();
        if self.peek() == Some('$') {
            return self.parse_prev_ref();
        }
        if self.peek() == Some('[') {
            return self.parse_array_arg();
        }
        if self.peek() == Some('{') {
            return self.parse_object_arg();
        }
        let v = self.parse_value()?;
        // CC-3: promote quoted "$prev[.path]" strings to PrevRef.
        if let Value::String(s) = &v {
            if let Some(prev_ref) = Self::string_as_prev_ref(s) {
                return Ok(prev_ref);
            }
        }
        Ok(ArgValue::Value(v))
    }

    /// Parse an array argument: `[elem, elem, ...]` where each element may be
    /// a `$prev` reference, a nested array/object, or a plain JSON literal.
    ///
    /// When no element contains a `$prev` reference, the result is folded back
    /// into an `ArgValue::Value(Array(_))` so pure-JSON callers see no change.
    fn parse_array_arg(&mut self) -> Result<ArgValue, DslError> {
        self.advance(1); // consume '['
        self.skip_ws();
        let mut elements: Vec<ArgValue> = Vec::new();
        if self.peek() == Some(']') {
            self.advance(1);
            return Ok(ArgValue::Value(Value::Array(vec![])));
        }
        loop {
            self.skip_ws();
            let elem = self.parse_arg_value()?;
            elements.push(elem);
            self.skip_ws();
            match self.peek() {
                Some(',') => {
                    self.advance(1);
                }
                Some(']') => {
                    self.advance(1);
                    break;
                }
                Some(c) => {
                    return Err(DslError::UnexpectedChar {
                        pos: self.pos,
                        found: c,
                        expected: "',' or ']'",
                    });
                }
                None => return Err(DslError::UnexpectedEof { expected: "']'" }),
            }
        }
        // If no element is a PrevRef/Array/Object, fold to Value for efficiency.
        let has_dynamic = elements.iter().any(|e| !matches!(e, ArgValue::Value(_)));
        if has_dynamic {
            Ok(ArgValue::Array(elements))
        } else {
            let vals: Vec<Value> = elements
                .into_iter()
                .map(|e| match e {
                    ArgValue::Value(v) => v,
                    _ => unreachable!(),
                })
                .collect();
            Ok(ArgValue::Value(Value::Array(vals)))
        }
    }

    /// Parse an object argument: `{"key": value, ...}`.
    ///
    /// Keys must be quoted strings (JSON-style). Values may contain `$prev` refs.
    /// Pure-JSON objects without any `$prev` fold back into `ArgValue::Value`.
    fn parse_object_arg(&mut self) -> Result<ArgValue, DslError> {
        self.advance(1); // consume '{'
        self.skip_ws();
        let mut pairs: Vec<(String, ArgValue)> = Vec::new();
        if self.peek() == Some('}') {
            self.advance(1);
            return Ok(ArgValue::Value(Value::Object(serde_json::Map::new())));
        }
        loop {
            self.skip_ws();
            // Key must be a quoted string — parse it directly (not via parse_value,
            // which uses scan_value_end and would greedily consume `:value`).
            let key = match self.peek() {
                Some('"') => {
                    let start = self.pos;
                    let end = scan_string_end(self.src, start)?;
                    let raw = std::str::from_utf8(&self.src[start..end]).expect("utf8 key literal");
                    let s: String =
                        serde_json::from_str(raw).map_err(|e| DslError::InvalidValue {
                            pos: start,
                            error: e.to_string(),
                        })?;
                    self.pos = end;
                    s
                }
                Some(c) => {
                    return Err(DslError::UnexpectedChar {
                        pos: self.pos,
                        found: c,
                        expected: "quoted string key",
                    });
                }
                None => {
                    return Err(DslError::UnexpectedEof {
                        expected: "object key",
                    })
                }
            };
            self.skip_ws();
            self.expect_char(':')?;
            self.skip_ws();
            let val = self.parse_arg_value()?;
            pairs.push((key, val));
            self.skip_ws();
            match self.peek() {
                Some(',') => {
                    self.advance(1);
                }
                Some('}') => {
                    self.advance(1);
                    break;
                }
                Some(c) => {
                    return Err(DslError::UnexpectedChar {
                        pos: self.pos,
                        found: c,
                        expected: "',' or '}'",
                    });
                }
                None => return Err(DslError::UnexpectedEof { expected: "'}'" }),
            }
        }
        // Fold pure-JSON objects back to Value.
        let has_dynamic = pairs.iter().any(|(_, v)| !matches!(v, ArgValue::Value(_)));
        if has_dynamic {
            Ok(ArgValue::Object(pairs))
        } else {
            let mut map = serde_json::Map::with_capacity(pairs.len());
            for (k, v) in pairs {
                match v {
                    ArgValue::Value(val) => {
                        map.insert(k, val);
                    }
                    _ => unreachable!(),
                }
            }
            Ok(ArgValue::Value(Value::Object(map)))
        }
    }

    /// Parse a `$prev` or `$prev.field.path` reference.
    ///
    /// Grammar: `$prev` optionally followed by a path composed of:
    /// - dot-separated identifiers: `.field`
    /// - bracket array indices:     `[N]`
    ///
    /// Examples: `$prev`, `$prev.id`, `$prev.items[0].id`, `$prev[0].name`
    /// (ue-dsl-chain H1: minimal array-index support added).
    fn parse_prev_ref(&mut self) -> Result<ArgValue, DslError> {
        let start = self.pos;
        // Consume `$`
        self.advance(1);
        // Must be followed by `prev`
        let ident = self
            .parse_identifier()
            .map_err(|_| DslError::InvalidValue {
                pos: start,
                error: "expected '$prev' — '$' must be followed by 'prev'".into(),
            })?;
        if ident != "prev" {
            return Err(DslError::InvalidValue {
                pos: start,
                error: format!("expected '$prev', found '${}'", ident),
            });
        }
        // Optional path — dot-segments and/or bracket indices.
        let mut path = String::new();
        loop {
            match self.peek() {
                Some('.') => {
                    self.advance(1); // consume '.'
                    let segment = self.parse_identifier()?;
                    if !path.is_empty() {
                        path.push('.');
                    }
                    path.push_str(&segment);
                }
                Some('[') => {
                    // Array index: `[N]`
                    self.advance(1); // consume '['
                    let idx_start = self.pos;
                    // Read digits
                    let mut idx_str = String::new();
                    while let Some(c) = self.peek() {
                        if c.is_ascii_digit() {
                            idx_str.push(c);
                            self.advance(1);
                        } else {
                            break;
                        }
                    }
                    if idx_str.is_empty() {
                        return Err(DslError::InvalidValue {
                            pos: idx_start,
                            error: "expected non-negative integer inside '[...]'".into(),
                        });
                    }
                    match self.peek() {
                        Some(']') => self.advance(1),
                        Some(c) => {
                            return Err(DslError::UnexpectedChar {
                                pos: self.pos,
                                found: c,
                                expected: "']'",
                            });
                        }
                        None => {
                            return Err(DslError::UnexpectedEof { expected: "']'" });
                        }
                    }
                    if !path.is_empty() {
                        path.push('.');
                    }
                    // Encode index as `[N]` so split_path can parse it back.
                    path.push('[');
                    path.push_str(&idx_str);
                    path.push(']');
                }
                _ => break,
            }
        }
        Ok(ArgValue::PrevRef { path })
    }

    fn parse_value(&mut self) -> Result<Value, DslError> {
        self.skip_ws();
        let start = self.pos;
        let end = self.scan_value_end()?;
        let slice = std::str::from_utf8(&self.src[start..end])
            .expect("ascii-or-utf8 maintained by scanner");
        let value: Value =
            serde_json::from_str(slice.trim()).map_err(|e| DslError::InvalidValue {
                pos: start,
                error: e.to_string(),
            })?;
        self.pos = end;
        Ok(value)
    }

    /// Check whether a parsed string value is a `$prev` reference written
    /// inside quotes (CC-3). Returns `Some(PrevRef)` if so, or
    /// `Some(Value(...))` if the string is an escaped literal, or `None` if
    /// neither (i.e. an ordinary string the caller should store as-is).
    ///
    /// ## Escape semantics (High-2 fix)
    ///
    /// A string like `"$prev.id"` deserializes to the Rust string `$prev.id`
    /// and is promoted to `ArgValue::PrevRef { path: "id" }`.
    ///
    /// To pass the **literal** string `$prev.id` as a value, write `"\\$prev.id"`
    /// in the DSL source. That deserializes to `\$prev.id` (one leading backslash).
    /// This function strips the leading `\` and returns
    /// `ArgValue::Value(json!("$prev.id"))` — so the handler receives the clean
    /// string without the escape marker.
    ///
    /// `$prevish.id` does NOT match (prefix boundary is `.` or `[` only).
    ///
    /// ## Bracket-index validation (Medium-1 fix)
    ///
    /// Quoted `$prev[...]` strings are routed through the same bracket-body
    /// validator as unquoted refs: only non-negative integers are accepted inside
    /// `[...]`. Malformed brackets (negative index, non-numeric, unclosed) return
    /// `None` (treated as a literal, consistent with the caller treating unknown
    /// forms as values).
    fn string_as_prev_ref(s: &str) -> Option<ArgValue> {
        // Escape: `\$prev...` → strip the leading backslash, return literal.
        if let Some(rest) = s.strip_prefix('\\') {
            if rest == "$prev" || rest.starts_with("$prev.") || rest.starts_with("$prev[") {
                return Some(ArgValue::Value(Value::String(rest.to_owned())));
            }
        }

        if s == "$prev" {
            return Some(ArgValue::PrevRef {
                path: String::new(),
            });
        }
        // "$prev.field..."
        if let Some(rest) = s.strip_prefix("$prev.") {
            if !rest.is_empty() {
                return Some(ArgValue::PrevRef {
                    path: rest.to_owned(),
                });
            }
        }
        // "$prev[N]..." — validate bracket body before promoting (Medium-1 fix).
        if let Some(after_bracket) = s.strip_prefix("$prev[") {
            // after_bracket is everything after "[", e.g. "0].id" or "-1].id"
            if let Some(close) = after_bracket.find(']') {
                let index_str = &after_bracket[..close];
                // Only non-negative integers are valid.
                if !index_str.is_empty() && index_str.chars().all(|c| c.is_ascii_digit()) {
                    let tail = &after_bracket[close + 1..]; // "].id" → ".id" after close
                                                            // path encodes as "[N]..." (used by split_path)
                    let path = format!("[{index_str}]{tail}");
                    return Some(ArgValue::PrevRef { path });
                }
            }
            // Malformed bracket (missing ']', negative, non-numeric) — treat as invalid.
            // Return None so the caller stores it as a literal Value.
            return None;
        }
        None
    }

    /// Walk forward through the input to find the end of a JSON value, respecting
    /// nested brackets / braces and string literals. The returned index is one
    /// past the last byte of the value (exclusive).
    fn scan_value_end(&self) -> Result<usize, DslError> {
        let mut i = self.pos;
        let mut depth_paren: i32 = 0; // `(` from the surrounding op
        let mut depth_brack: i32 = 0;
        let mut depth_brace: i32 = 0;
        while i < self.src.len() {
            let c = self.src[i] as char;
            match c {
                '"' => {
                    i = scan_string_end(self.src, i)?;
                    continue;
                }
                '[' => depth_brack += 1,
                ']' => {
                    if depth_brack == 0 {
                        if depth_paren == 0 && depth_brace == 0 {
                            return Ok(i);
                        }
                        // we never opened a paren here; this terminates the value.
                        return Ok(i);
                    }
                    depth_brack -= 1;
                }
                '{' => depth_brace += 1,
                '}' => {
                    if depth_brace == 0 {
                        // Closing brace outside any open brace — terminates the
                        // current value (e.g. a string value inside an object literal
                        // parsed by parse_object_arg).
                        if depth_paren == 0 && depth_brack == 0 {
                            return Ok(i);
                        }
                        return Err(DslError::UnclosedBracket { kind: '{' });
                    }
                    depth_brace -= 1;
                }
                '(' => depth_paren += 1,
                ')' => {
                    if depth_paren == 0 && depth_brack == 0 && depth_brace == 0 {
                        return Ok(i);
                    }
                    if depth_paren == 0 {
                        return Err(DslError::UnclosedBracket { kind: '(' });
                    }
                    depth_paren -= 1;
                }
                ',' => {
                    if depth_paren == 0 && depth_brack == 0 && depth_brace == 0 {
                        return Ok(i);
                    }
                }
                _ => {}
            }
            i += 1;
        }
        if depth_brack > 0 {
            return Err(DslError::UnclosedBracket { kind: '[' });
        }
        if depth_brace > 0 {
            return Err(DslError::UnclosedBracket { kind: '{' });
        }
        Ok(i)
    }
}

/// Return `true` if the string value is a `$prev` reference written inside JSON
/// quotes. Used to detect `"$prev.id"` literals in JSON-form input (ue-dsl-chain C1).
///
/// Matches exactly `$prev`, strings starting with `$prev.`, or strings starting
/// with `$prev[` (bracket-index form). Does NOT match `$prevish.id` — the prefix
/// boundary is `.` or `[` only.
fn is_prev_ref_string(s: &str) -> bool {
    s == "$prev" || s.starts_with("$prev.") || s.starts_with("$prev[")
}

/// Recursively scan a JSON value for any string that is a `$prev` reference.
///
/// This covers nested arrays and objects, so `{"ids": ["$prev.id"]}` and
/// `{"nested": {"id": "$prev[0].id"}}` are both detected (fix for High-1).
fn json_value_contains_prev_ref(v: &Value) -> bool {
    match v {
        Value::String(s) => is_prev_ref_string(s),
        Value::Array(arr) => arr.iter().any(json_value_contains_prev_ref),
        Value::Object(map) => map.values().any(json_value_contains_prev_ref),
        _ => false,
    }
}

/// A single segment in a `$prev` path — either a field name or an array index.
#[derive(Debug, Clone, PartialEq)]
enum PathSegment<'a> {
    Field(&'a str),
    Index(usize),
}

/// Split a dotted path that may contain bracket array indices into segments.
///
/// `"items[0].id"` → `[Field("items"), Index(0), Field("id")]`
/// `"[2].name"` → `[Index(2), Field("name")]`
/// `"plain.path"` → `[Field("plain"), Field("path")]`
fn split_path(path: &str) -> Vec<PathSegment<'_>> {
    let mut segments = Vec::new();
    let mut remaining = path;
    while !remaining.is_empty() {
        if let Some(rest) = remaining.strip_prefix('[') {
            // Array index: `[N]...`
            if let Some(close) = rest.find(']') {
                let index_str = &rest[..close];
                if let Ok(idx) = index_str.parse::<usize>() {
                    segments.push(PathSegment::Index(idx));
                    remaining = &rest[close + 1..];
                    // Strip leading '.' before next segment, if any.
                    remaining = remaining.strip_prefix('.').unwrap_or(remaining);
                    continue;
                }
            }
            // Malformed index — treat whole remainder as field (will fail lookup).
            segments.push(PathSegment::Field(remaining));
            break;
        }
        // Field name — up to next '.' or '['.
        let end = remaining.find(['.', '[']).unwrap_or(remaining.len());
        let field = &remaining[..end];
        if !field.is_empty() {
            segments.push(PathSegment::Field(field));
        }
        remaining = &remaining[end..];
        // Strip leading '.' separator.
        remaining = remaining.strip_prefix('.').unwrap_or(remaining);
    }
    segments
}

/// Apply one path segment to a JSON value — field lookup or array index.
fn apply_path_segment<'a>(cur: &'a Value, seg: PathSegment<'_>) -> Option<&'a Value> {
    match seg {
        PathSegment::Field(key) => cur.get(key),
        PathSegment::Index(idx) => cur.as_array()?.get(idx),
    }
}

/// Scan an op's args for any `PrevRef` (or `Array`/`Object` containing one) and
/// return a representative position (0 — we don't track source positions per-arg
/// at this stage) if any is found. Used to emit `PrevRefOutsideChain` at parse
/// time for Single and Parallel modes (adr-dsl-packs H1).
fn find_prev_ref_pos(op: &ParsedOp) -> Option<usize> {
    for av in op.args.values() {
        if arg_value_has_prev_ref(av) {
            return Some(0);
        }
    }
    None
}

fn arg_value_has_prev_ref(av: &ArgValue) -> bool {
    match av {
        ArgValue::PrevRef { .. } => true,
        ArgValue::Array(els) => els.iter().any(arg_value_has_prev_ref),
        ArgValue::Object(pairs) => pairs.iter().any(|(_, v)| arg_value_has_prev_ref(v)),
        ArgValue::Value(_) => false,
    }
}

fn scan_string_end(src: &[u8], start: usize) -> Result<usize, DslError> {
    let mut i = start + 1;
    while i < src.len() {
        match src[i] as char {
            '\\' => {
                i += 2; // skip escape pair
                continue;
            }
            '"' => return Ok(i + 1),
            _ => i += 1,
        }
    }
    Err(DslError::UnclosedString)
}

fn char_label(c: char) -> &'static str {
    match c {
        '(' => "'('",
        ')' => "')'",
        '[' => "'['",
        ']' => "']'",
        '=' => "'='",
        ',' => "','",
        _ => "expected char",
    }
}

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

    fn req(s: &str) -> ParsedRequest {
        parse_request(s).unwrap_or_else(|e| panic!("parse({s:?}) failed: {e}"))
    }

    fn ops(s: &str) -> Vec<ParsedOp> {
        req(s).ops
    }

    /// Extract the concrete `Value` from an `ArgValue::Value`, panicking on dynamic variants.
    fn val(arg: &ArgValue) -> &Value {
        match arg {
            ArgValue::Value(v) => v,
            ArgValue::PrevRef { path } => {
                panic!("expected Value, got PrevRef {{ path: {path:?} }}")
            }
            ArgValue::Array(els) => {
                panic!("expected Value, got Array with {} elements", els.len())
            }
            ArgValue::Object(pairs) => {
                panic!("expected Value, got Object with {} keys", pairs.len())
            }
        }
    }

    #[test]
    fn single_op_no_args() {
        let r = req("gtd.next()");
        assert_eq!(r.mode, ExecutionMode::Single);
        assert_eq!(r.ops.len(), 1);
        assert_eq!(r.ops[0].tool, "gtd.next");
        assert!(r.ops[0].args.is_empty());
    }

    #[test]
    fn single_op_with_string_arg() {
        let v = ops(r#"gtd.assign(title="ship release")"#);
        assert_eq!(v[0].tool, "gtd.assign");
        assert_eq!(val(&v[0].args["title"]), &json!("ship release"));
    }

    #[test]
    fn single_op_with_multiple_typed_args() {
        let v = ops(
            r#"create(kind="entity", entity_kind="concept", name="LoRA", weight=0.9, active=true)"#,
        );
        assert_eq!(v[0].tool, "create");
        assert_eq!(val(&v[0].args["kind"]), &json!("entity"));
        assert_eq!(val(&v[0].args["weight"]), &json!(0.9));
        assert_eq!(val(&v[0].args["active"]), &json!(true));
    }

    #[test]
    fn batch_three_ops() {
        let r = req(
            r#"[create(kind="entity", name="A"), create(kind="entity", name="B"), link(source_id="x", target_id="y", relation="extends")]"#,
        );
        assert_eq!(r.mode, ExecutionMode::Parallel);
        assert_eq!(r.ops.len(), 3);
        assert_eq!(r.ops[0].tool, "create");
        assert_eq!(r.ops[2].tool, "link");
        assert_eq!(val(&r.ops[2].args["relation"]), &json!("extends"));
    }

    #[test]
    fn empty_batch_rejected() {
        // UE4-H2: empty batch must be rejected with EmptyBatch error.
        let err = parse_request("[]").unwrap_err();
        assert!(
            matches!(err, DslError::EmptyBatch),
            "expected EmptyBatch, got {err:?}"
        );
        // JSON form empty array is also rejected.
        let err2 = parse_request("[]").unwrap_err();
        assert!(matches!(err2, DslError::EmptyBatch));
    }

    #[test]
    fn nested_array_and_object_values() {
        let v = ops(r#"gtd.assign(title="x", tags=["a","b"], properties={"k":"v","n":1})"#);
        assert_eq!(val(&v[0].args["tags"]), &json!(["a", "b"]));
        assert_eq!(val(&v[0].args["properties"]), &json!({"k": "v", "n": 1}));
    }

    #[test]
    fn string_with_comma_and_paren_inside() {
        let v = ops(r#"gtd.assign(title="hello, world (now)")"#);
        assert_eq!(val(&v[0].args["title"]), &json!("hello, world (now)"));
    }

    #[test]
    fn string_with_escaped_quote() {
        let v = ops(r#"gtd.assign(title="he said \"hi\"")"#);
        assert_eq!(val(&v[0].args["title"]), &json!("he said \"hi\""));
    }

    #[test]
    fn null_and_negative_number() {
        let v = ops(r#"update(id="x", description=null, weight=-0.5)"#);
        assert_eq!(val(&v[0].args["description"]), &json!(null));
        assert_eq!(val(&v[0].args["weight"]), &json!(-0.5));
    }

    #[test]
    fn json_form_batch_parses() {
        let r =
            req(r#"[{"tool":"gtd.next","args":{}}, {"tool":"gtd.complete","args":{"id":"abc"}}]"#);
        assert_eq!(r.mode, ExecutionMode::Parallel);
        assert_eq!(r.ops.len(), 2);
        assert_eq!(r.ops[1].tool, "gtd.complete");
        assert_eq!(val(&r.ops[1].args["id"]), &json!("abc"));
    }

    #[test]
    fn json_form_with_leading_whitespace_inside_array_parses() {
        // Pretty-printers commonly emit `[ {...} ]` with spaces or newlines after `[`.
        // The whitespace is legal JSON, so the parser must route this to the JSON
        // path rather than the function-call batch parser.
        let v = ops(r#"[  {"tool":"gtd.next","args":{}} ]"#);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].tool, "gtd.next");

        let v = ops("[\n  {\"tool\":\"gtd.next\",\"args\":{}},\n  {\"tool\":\"gtd.complete\",\"args\":{\"id\":\"x\"}}\n]");
        assert_eq!(v.len(), 2);
        assert_eq!(v[1].tool, "gtd.complete");
    }

    #[test]
    fn json_form_single_object_is_treated_as_one_op() {
        let r = req(r#"{"tool":"gtd.next","args":{}}"#);
        assert_eq!(r.mode, ExecutionMode::Single);
        assert_eq!(r.ops.len(), 1);
        assert_eq!(r.ops[0].tool, "gtd.next");
    }

    #[test]
    fn duplicate_arg_rejected() {
        let err = parse_request(r#"gtd.assign(title="a", title="b")"#).unwrap_err();
        assert!(matches!(err, DslError::DuplicateArg { ref name } if name == "title"));
    }

    #[test]
    fn unknown_token_after_op_rejected() {
        let err = parse_request(r#"gtd.next() garbage"#).unwrap_err();
        assert!(matches!(err, DslError::UnexpectedChar { .. }));
    }

    #[test]
    fn unclosed_paren_rejected() {
        let err = parse_request(r#"gtd.assign(title="a""#).unwrap_err();
        // The string is closed; the args list isn't.
        assert!(matches!(err, DslError::UnexpectedEof { .. }));
    }

    #[test]
    fn unterminated_string_rejected() {
        let err = parse_request(r#"gtd.assign(title="oops)"#).unwrap_err();
        assert!(matches!(err, DslError::UnclosedString));
    }

    #[test]
    fn too_many_ops_rejected() {
        let one = r#"gtd.next(),"#;
        let mut s = String::from("[");
        for _ in 0..MAX_OPS + 1 {
            s.push_str(one);
        }
        s.push_str("gtd.next()]");
        let err = parse_request(&s).unwrap_err();
        assert!(matches!(err, DslError::TooManyOps { .. }));
    }

    #[test]
    fn empty_request_rejected() {
        let err = parse_request("   ").unwrap_err();
        assert!(matches!(err, DslError::Empty));
    }

    // ── Required prompt examples ───────────────────────────────────────────────

    #[test]
    fn recall_with_query_arg() {
        let v = ops(r#"memory.recall(query="test")"#);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].tool, "memory.recall");
        assert_eq!(val(&v[0].args["query"]), &json!("test"));
    }

    #[test]
    fn search_with_query_and_limit() {
        let v = ops(r#"search(query="test", limit=5)"#);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].tool, "search");
        assert_eq!(val(&v[0].args["query"]), &json!("test"));
        assert_eq!(val(&v[0].args["limit"]), &json!(5));
    }

    #[test]
    fn parallel_recall_and_inbox() {
        let r = req(r#"[memory.recall(query="x"), comm.inbox()]"#);
        assert_eq!(r.mode, ExecutionMode::Parallel);
        assert_eq!(r.ops.len(), 2);
        assert_eq!(r.ops[0].tool, "memory.recall");
        assert_eq!(val(&r.ops[0].args["query"]), &json!("x"));
        assert_eq!(r.ops[1].tool, "comm.inbox");
        assert!(r.ops[1].args.is_empty());
    }

    // ── JSON form edge cases ───────────────────────────────────────────────────

    #[test]
    fn json_missing_args_defaults_to_empty_map() {
        let v = ops(r#"{"tool":"comm.inbox"}"#);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].tool, "comm.inbox");
        assert!(v[0].args.is_empty());
    }

    #[test]
    fn json_args_as_array_rejected() {
        let err = parse_request(r#"{"tool":"x","args":[]}"#).unwrap_err();
        assert!(matches!(err, DslError::InvalidJson { .. }));
    }

    // ── Identifier grammar ────────────────────────────────────────────────────

    #[test]
    fn dotted_tool_name_parsed() {
        let v = ops("brain.state()");
        assert_eq!(v[0].tool, "brain.state");
        assert!(v[0].args.is_empty());
    }

    #[test]
    fn dotted_tool_with_args() {
        let v = ops(r#"memory.recall_candidates(query="test", limit=5)"#);
        assert_eq!(v[0].tool, "memory.recall_candidates");
        assert_eq!(val(&v[0].args["query"]), &json!("test"));
        assert_eq!(val(&v[0].args["limit"]), &json!(5));
    }

    #[test]
    fn dotted_tool_in_batch() {
        let v = ops(r#"[brain.state(), memory.recall_fuse(query="x")]"#);
        assert_eq!(v.len(), 2);
        assert_eq!(v[0].tool, "brain.state");
        assert_eq!(v[1].tool, "memory.recall_fuse");
    }

    #[test]
    fn leading_underscore_identifier_is_valid() {
        let v = ops("_internal()");
        assert_eq!(v[0].tool, "_internal");
        assert!(v[0].args.is_empty());
    }

    #[test]
    fn identifier_starting_with_digit_rejected() {
        let err = parse_request("1bad()").unwrap_err();
        assert!(matches!(err, DslError::InvalidIdentifier { pos: 0 }));
    }

    // ── Argument value edge cases ─────────────────────────────────────────────

    #[test]
    fn boolean_false_as_arg_value() {
        let v = ops("flag(active=false)");
        assert_eq!(val(&v[0].args["active"]), &json!(false));
    }

    #[test]
    fn unicode_string_arg_preserved() {
        let v = ops(r#"gtd.assign(title="café")"#);
        assert_eq!(val(&v[0].args["title"]), &json!("café"));
    }

    // ── Chain mode (ADR-016) ──────────────────────────────────────────────────

    #[test]
    fn chain_two_ops_with_prev_ref() {
        let r = req(
            r#"create(kind="entity", entity_kind="concept", name="A") | link(source_id=$prev.id, target_id="abc", relation="extends")"#,
        );
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(r.ops.len(), 2);
        assert_eq!(r.ops[0].tool, "create");
        assert_eq!(r.ops[1].tool, "link");
        // The second op's source_id should be a PrevRef
        assert_eq!(
            r.ops[1].args["source_id"],
            ArgValue::PrevRef { path: "id".into() }
        );
        // target_id is a concrete value
        assert_eq!(val(&r.ops[1].args["target_id"]), &json!("abc"));
    }

    #[test]
    fn chain_three_ops_mode() {
        let r = req(
            r#"create(kind="entity", name="A") | link(source_id=$prev.id, target_id="b", relation="extends") | update(id=$prev.id, description="desc")"#,
        );
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(r.ops.len(), 3);
        assert_eq!(r.ops[2].args["id"], ArgValue::PrevRef { path: "id".into() });
    }

    #[test]
    fn chain_prev_no_field_selector() {
        // $prev alone (no dot path) refers to the whole prior result.
        let r = req(r#"gtd.next() | update(id=$prev)"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(r.ops[1].args["id"], ArgValue::PrevRef { path: "".into() });
    }

    #[test]
    fn chain_prev_deep_path() {
        let r = req(
            r#"create(kind="entity", name="A") | link(source_id=$prev.result.id, target_id="b", relation="extends")"#,
        );
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(
            r.ops[1].args["source_id"],
            ArgValue::PrevRef {
                path: "result.id".into()
            }
        );
    }

    #[test]
    fn single_op_mode() {
        let r = req("gtd.next()");
        assert_eq!(r.mode, ExecutionMode::Single);
    }

    #[test]
    fn chain_too_many_ops_rejected() {
        let mut s = String::from("gtd.next()");
        for _ in 0..MAX_OPS {
            s.push_str(" | gtd.next()");
        }
        let err = parse_request(&s).unwrap_err();
        assert!(matches!(err, DslError::TooManyOps { .. }));
    }

    // ── ArgValue helpers ──────────────────────────────────────────────────────

    #[test]
    fn arg_value_resolve_prev_simple() {
        let prev = json!({"id": "abc-123", "name": "A"});
        let r = ArgValue::PrevRef { path: "id".into() };
        assert_eq!(r.resolve_prev(&prev), Some(&json!("abc-123")));
    }

    #[test]
    fn arg_value_resolve_prev_empty_path() {
        let prev = json!({"id": "x"});
        let r = ArgValue::PrevRef { path: "".into() };
        assert_eq!(r.resolve_prev(&prev), Some(&prev));
    }

    #[test]
    fn arg_value_resolve_prev_nested_path() {
        let prev = json!({"result": {"id": "nested-id"}});
        let r = ArgValue::PrevRef {
            path: "result.id".into(),
        };
        assert_eq!(r.resolve_prev(&prev), Some(&json!("nested-id")));
    }

    #[test]
    fn arg_value_resolve_prev_missing_field_returns_none() {
        let prev = json!({"id": "x"});
        let r = ArgValue::PrevRef {
            path: "nonexistent".into(),
        };
        assert_eq!(r.resolve_prev(&prev), None);
    }

    #[test]
    fn arg_value_value_returns_none_for_resolve_prev() {
        let r = ArgValue::Value(json!("hello"));
        assert_eq!(r.resolve_prev(&json!({})), None);
    }

    // ── G-C1: $prev inside array / object literals (regression) ──────────────

    #[test]
    fn chain_prev_in_single_element_array() {
        // `gtd.assign(title="root") | gtd.assign(title="dep", depends_on=[$prev.full_id])`
        let r = req(
            r#"gtd.assign(title="root") | gtd.assign(title="dep", depends_on=[$prev.full_id])"#,
        );
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(r.ops.len(), 2);
        match &r.ops[1].args["depends_on"] {
            ArgValue::Array(els) => {
                assert_eq!(els.len(), 1);
                assert_eq!(
                    els[0],
                    ArgValue::PrevRef {
                        path: "full_id".into()
                    }
                );
            }
            other => panic!("expected Array, got {other:?}"),
        }
    }

    #[test]
    fn chain_prev_in_mixed_array() {
        // `[$prev.id, "literal-uuid"]` — first element is PrevRef, second is literal.
        let r = req(
            r#"gtd.assign(title="root") | gtd.assign(title="dep", depends_on=[$prev.id, "literal-uuid"])"#,
        );
        assert_eq!(r.mode, ExecutionMode::Chain);
        match &r.ops[1].args["depends_on"] {
            ArgValue::Array(els) => {
                assert_eq!(els.len(), 2);
                assert_eq!(els[0], ArgValue::PrevRef { path: "id".into() });
                assert_eq!(els[1], ArgValue::Value(json!("literal-uuid")));
            }
            other => panic!("expected Array, got {other:?}"),
        }
    }

    #[test]
    fn chain_prev_multiple_in_array() {
        // `depends_on=[$prev.field.deep, $prev.other]`
        let r = req(
            r#"gtd.assign(title="root") | gtd.assign(title="dep", depends_on=[$prev.field.deep, $prev.other])"#,
        );
        assert_eq!(r.mode, ExecutionMode::Chain);
        match &r.ops[1].args["depends_on"] {
            ArgValue::Array(els) => {
                assert_eq!(els.len(), 2);
                assert_eq!(
                    els[0],
                    ArgValue::PrevRef {
                        path: "field.deep".into()
                    }
                );
                assert_eq!(
                    els[1],
                    ArgValue::PrevRef {
                        path: "other".into()
                    }
                );
            }
            other => panic!("expected Array, got {other:?}"),
        }
    }

    #[test]
    fn chain_prev_inside_object_inside_array() {
        // `properties={"refs":[$prev.id]}` — nested: object containing array containing PrevRef
        let r = req(
            r#"gtd.assign(title="root") | gtd.assign(title="dep", properties={"refs": [$prev.id]})"#,
        );
        assert_eq!(r.mode, ExecutionMode::Chain);
        match &r.ops[1].args["properties"] {
            ArgValue::Object(pairs) => {
                assert_eq!(pairs.len(), 1);
                assert_eq!(pairs[0].0, "refs");
                match &pairs[0].1 {
                    ArgValue::Array(els) => {
                        assert_eq!(els.len(), 1);
                        assert_eq!(els[0], ArgValue::PrevRef { path: "id".into() });
                    }
                    other => panic!("expected inner Array, got {other:?}"),
                }
            }
            other => panic!("expected Object, got {other:?}"),
        }
    }

    #[test]
    fn pure_json_array_folds_to_value() {
        // An array with no $prev refs should still produce ArgValue::Value(Array(...))
        let v = ops(r#"gtd.assign(title="x", depends_on=["a", "b"])"#);
        assert_eq!(val(&v[0].args["depends_on"]), &json!(["a", "b"]));
    }

    #[test]
    fn pure_json_object_folds_to_value() {
        // An object with no $prev refs should still produce ArgValue::Value(Object(...))
        let v = ops(r#"gtd.assign(title="x", properties={"k": "v"})"#);
        assert_eq!(val(&v[0].args["properties"]), &json!({"k": "v"}));
    }

    #[test]
    fn resolve_all_on_array_with_prev_ref() {
        let prev = json!({"full_id": "abc-def-123"});
        let arr = ArgValue::Array(vec![ArgValue::PrevRef {
            path: "full_id".into(),
        }]);
        assert_eq!(arr.resolve_all(&prev), Some(json!(["abc-def-123"])));
    }

    #[test]
    fn resolve_all_on_mixed_array() {
        let prev = json!({"id": "x"});
        let arr = ArgValue::Array(vec![
            ArgValue::PrevRef { path: "id".into() },
            ArgValue::Value(json!("literal")),
        ]);
        assert_eq!(arr.resolve_all(&prev), Some(json!(["x", "literal"])));
    }

    #[test]
    fn resolve_all_on_nested_object() {
        let prev = json!({"id": "obj-id"});
        let obj = ArgValue::Object(vec![(
            "refs".into(),
            ArgValue::Array(vec![ArgValue::PrevRef { path: "id".into() }]),
        )]);
        assert_eq!(obj.resolve_all(&prev), Some(json!({"refs": ["obj-id"]})));
    }

    #[test]
    fn resolve_all_missing_path_returns_none() {
        let prev = json!({"id": "x"});
        let arr = ArgValue::Array(vec![ArgValue::PrevRef {
            path: "missing".into(),
        }]);
        assert_eq!(arr.resolve_all(&prev), None);
    }

    // ── CC-3: Quoted "$prev.id" substitutes the same as unquoted $prev.id ─────

    #[test]
    fn quoted_prev_ref_chain_parses_as_prev_ref() {
        // CC-3: `get(id="$prev.id")` must produce PrevRef, not Value("$prev.id").
        let r = req(r#"create(kind="concept", name="A") | get(id="$prev.id")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(r.ops[1].args["id"], ArgValue::PrevRef { path: "id".into() });
    }

    #[test]
    fn quoted_bare_prev_ref_parses_as_prev_ref() {
        // CC-3: `"$prev"` (no path) must also promote.
        let r = req(r#"next() | update(id="$prev")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(r.ops[1].args["id"], ArgValue::PrevRef { path: "".into() });
    }

    #[test]
    fn quoted_prev_ref_deep_path_parses_as_prev_ref() {
        // CC-3: `"$prev.result.id"` — multi-segment dotted quoted ref.
        let r = req(r#"create(kind="concept", name="A") | get(id="$prev.result.id")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(
            r.ops[1].args["id"],
            ArgValue::PrevRef {
                path: "result.id".into()
            }
        );
    }

    #[test]
    fn escaped_dollar_prev_stays_literal() {
        // CC-3 escape (High-2 fix): `"\\$prev.id"` → the literal string `$prev.id`.
        // The DSL source `"\\$prev.id"` deserializes to `\$prev.id` (one backslash).
        // string_as_prev_ref strips the leading `\` and returns Value("$prev.id").
        let r = req(r#"create(kind="concept", name="A") | get(id="\\$prev.id")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        // After stripping the escape marker the handler sees the clean literal.
        assert_eq!(r.ops[1].args["id"], ArgValue::Value(json!("$prev.id")));
    }

    // ── ue-dsl-chain C1: JSON-form with $prev string is rejected clearly ──────

    #[test]
    fn json_form_with_prev_ref_string_is_rejected() {
        // ue-dsl-chain C1: JSON form `[{...}, {"args":{"id":"$prev.id"}}]` must
        // be rejected with PrevRefInJsonForm, not silently passed through.
        let err = parse_request(
            r#"[{"tool":"create","args":{"kind":"concept","name":"A"}},{"tool":"get","args":{"id":"$prev.id"}}]"#,
        )
        .unwrap_err();
        assert!(
            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "id"),
            "expected PrevRefInJsonForm, got {err:?}"
        );
    }

    #[test]
    fn json_form_with_bare_prev_string_is_rejected() {
        // ue-dsl-chain C1: bare `"$prev"` in JSON form is also rejected.
        let err = parse_request(r#"[{"tool":"get","args":{"id":"$prev"}}]"#).unwrap_err();
        assert!(
            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "id"),
            "expected PrevRefInJsonForm, got {err:?}"
        );
    }

    #[test]
    fn json_form_without_prev_ref_still_works() {
        // ue-dsl-chain C1 guard: make sure normal JSON form is not broken.
        let r = req(r#"[{"tool":"next","args":{}}, {"tool":"complete","args":{"id":"abc"}}]"#);
        assert_eq!(r.mode, ExecutionMode::Parallel);
        assert_eq!(r.ops.len(), 2);
    }

    // ── adr-dsl-packs H1: PrevRefOutsideChain emitted at parse time ───────────

    #[test]
    fn prev_ref_in_single_op_is_rejected() {
        // adr-dsl-packs H1: `get(id=$prev.id)` without chain must be rejected.
        let err = parse_request(r#"get(id=$prev.id)"#).unwrap_err();
        assert!(
            matches!(err, DslError::PrevRefOutsideChain { .. }),
            "expected PrevRefOutsideChain, got {err:?}"
        );
    }

    #[test]
    fn prev_ref_in_fn_batch_is_rejected() {
        // adr-dsl-packs H1: PrevRef inside `[create(...), get(id=$prev.id)]` is
        // parallel (no `|`) — must be rejected at parse time.
        let err =
            parse_request(r#"[create(kind="concept", name="A"), get(id=$prev.id)]"#).unwrap_err();
        assert!(
            matches!(err, DslError::PrevRefOutsideChain { .. }),
            "expected PrevRefOutsideChain, got {err:?}"
        );
    }

    // ── adr-dsl-packs H3: MixedSeparators emitted at parse time ──────────────

    #[test]
    fn mixed_separators_in_fn_batch_rejected() {
        // adr-dsl-packs H3: `[a() | b(), c()]` mixes `|` and `,` at top level.
        let err = parse_request("[a() | b(), c()]").unwrap_err();
        assert!(
            matches!(err, DslError::MixedSeparators),
            "expected MixedSeparators, got {err:?}"
        );
    }

    #[test]
    fn mixed_separator_after_chain_rejected() {
        // adr-dsl-packs H3: `a() | b(), c()` mixes `|` chain with trailing `,`.
        let err = parse_request("a() | b(), c()").unwrap_err();
        assert!(
            matches!(err, DslError::MixedSeparators),
            "expected MixedSeparators, got {err:?}"
        );
    }

    #[test]
    fn comma_only_parallel_accepted() {
        // adr-dsl-packs H3: `[a(), b(), c()]` is valid comma-only parallel batch.
        let req = parse_request("[a(), b(), c()]").unwrap();
        assert_eq!(req.mode, ExecutionMode::Parallel);
        assert_eq!(req.ops.len(), 3);
    }

    #[test]
    fn pipe_only_chain_accepted() {
        // adr-dsl-packs H3: `a() | b() | c()` is valid pipe-only chain.
        let req = parse_request("a() | b() | c()").unwrap();
        assert_eq!(req.mode, ExecutionMode::Chain);
        assert_eq!(req.ops.len(), 3);
    }

    // ── adr-dsl-packs H2: multi-segment dotted verb → clear error ─────────────

    #[test]
    fn three_segment_verb_name_rejected() {
        // adr-dsl-packs H2: `brain.state.debug()` must produce UnsupportedVerbNesting,
        // not the misleading "expected '|' or end of input, found '.'".
        let err = parse_request("brain.state.debug()").unwrap_err();
        assert!(
            matches!(err, DslError::UnsupportedVerbNesting { .. }),
            "expected UnsupportedVerbNesting, got {err:?}"
        );
    }

    // ── ue-dsl-chain H1: array indexing in $prev paths ────────────────────────

    #[test]
    fn chain_prev_array_index_at_root() {
        // `$prev[0].id` — index at the root of a prev result.
        let r = req(r#"list(kind="concept") | get(id=$prev[0].id)"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(
            r.ops[1].args["id"],
            ArgValue::PrevRef {
                path: "[0].id".into()
            }
        );
    }

    #[test]
    fn chain_prev_array_index_nested() {
        // `$prev.items[2].name` — index inside a named field.
        let r = req(r#"list(kind="concept") | get(id=$prev.items[2].name)"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(
            r.ops[1].args["id"],
            ArgValue::PrevRef {
                path: "items.[2].name".into()
            }
        );
    }

    #[test]
    fn resolve_prev_array_index_at_root() {
        let prev = json!([{"id": "first"}, {"id": "second"}]);
        let r = ArgValue::PrevRef {
            path: "[0].id".into(),
        };
        assert_eq!(r.resolve_prev(&prev), Some(&json!("first")));
    }

    #[test]
    fn resolve_prev_array_index_nested() {
        let prev = json!({"items": [{"name": "alpha"}, {"name": "beta"}]});
        let r = ArgValue::PrevRef {
            path: "items.[1].name".into(),
        };
        assert_eq!(r.resolve_prev(&prev), Some(&json!("beta")));
    }

    #[test]
    fn resolve_prev_array_index_out_of_bounds_returns_none() {
        let prev = json!([{"id": "only"}]);
        let r = ArgValue::PrevRef {
            path: "[5].id".into(),
        };
        assert_eq!(r.resolve_prev(&prev), None);
    }

    // ── CC-3 + H1: quoted prev ref with array index ───────────────────────────

    #[test]
    fn quoted_prev_ref_with_array_index_parses() {
        // `"$prev[0].id"` quoted with bracket index should also promote.
        let r = req(r#"list(kind="concept") | get(id="$prev[0].id")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(
            r.ops[1].args["id"],
            ArgValue::PrevRef {
                path: "[0].id".into()
            }
        );
    }

    // ── High-1 regression: JSON-form recursive $prev detection ───────────────

    #[test]
    fn json_form_nested_array_with_prev_ref_is_rejected() {
        // High-1: `{"ids": ["$prev.id"]}` — $prev inside an array arg must be detected.
        let err = parse_request(
            r#"[{"tool":"create","args":{"kind":"concept","name":"A"}},{"tool":"search","args":{"ids":["$prev.id"]}}]"#,
        )
        .unwrap_err();
        assert!(
            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "ids"),
            "expected PrevRefInJsonForm for nested array, got {err:?}"
        );
    }

    #[test]
    fn json_form_nested_object_with_prev_ref_is_rejected() {
        // High-1: `{"filter": {"id": "$prev.id"}}` — $prev inside an object arg must be detected.
        let err = parse_request(
            r#"[{"tool":"create","args":{"kind":"concept","name":"A"}},{"tool":"search","args":{"filter":{"id":"$prev.id"}}}]"#,
        )
        .unwrap_err();
        assert!(
            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "filter"),
            "expected PrevRefInJsonForm for nested object, got {err:?}"
        );
    }

    #[test]
    fn json_form_bracket_prev_ref_is_rejected() {
        // High-1: `{"id": "$prev[0].id"}` — bracket-index form must also be detected.
        let err = parse_request(
            r#"[{"tool":"create","args":{"kind":"concept","name":"A"}},{"tool":"get","args":{"id":"$prev[0].id"}}]"#,
        )
        .unwrap_err();
        assert!(
            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "id"),
            "expected PrevRefInJsonForm for $prev[0].id, got {err:?}"
        );
    }

    #[test]
    fn json_form_prevish_id_stays_literal() {
        // High-1 boundary: `$prevish.id` is NOT a $prev ref and must pass through.
        let r = req(r#"[{"tool":"get","args":{"id":"$prevish.id"}}]"#);
        assert_eq!(r.mode, ExecutionMode::Parallel);
        assert_eq!(r.ops[0].args["id"], ArgValue::Value(json!("$prevish.id")));
    }

    // ── High-2 regression: escape semantics produce clean literal ────────────

    #[test]
    fn escaped_dollar_prev_without_path_stays_literal() {
        // High-2: `"\\$prev"` → literal `$prev` (no path), not a PrevRef.
        let r = req(r#"create(kind="concept", name="A") | get(id="\\$prev")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(r.ops[1].args["id"], ArgValue::Value(json!("$prev")));
    }

    #[test]
    fn escaped_dollar_prev_bracket_stays_literal() {
        // High-2: `"\\$prev[0].id"` → literal `$prev[0].id`, not a PrevRef.
        let r = req(r#"create(kind="concept", name="A") | get(id="\\$prev[0].id")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert_eq!(r.ops[1].args["id"], ArgValue::Value(json!("$prev[0].id")));
    }

    // ── Medium-1 regression: quoted bracket index validation ─────────────────

    #[test]
    fn quoted_prev_ref_negative_index_treated_as_literal() {
        // Medium-1: `"$prev[-1].id"` — negative index is invalid in bracket grammar.
        // string_as_prev_ref returns None → stored as literal Value, not PrevRef.
        // In a chain, the value is a concrete string (no $prev substitution needed).
        let r = req(r#"list(kind="concept") | get(id="$prev[-1].id")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        // Should be a Value (literal), NOT a PrevRef.
        assert!(
            matches!(r.ops[1].args["id"], ArgValue::Value(_)),
            "negative index quoted ref must be literal Value, not PrevRef; got {:?}",
            r.ops[1].args["id"]
        );
    }

    #[test]
    fn quoted_prev_ref_missing_close_bracket_treated_as_literal() {
        // Medium-1: `"$prev[0.id"` — missing ']' is a malformed bracket.
        let r = req(r#"list(kind="concept") | get(id="$prev[0.id")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert!(
            matches!(r.ops[1].args["id"], ArgValue::Value(_)),
            "unclosed bracket quoted ref must be literal Value, not PrevRef; got {:?}",
            r.ops[1].args["id"]
        );
    }

    #[test]
    fn quoted_prev_ref_non_numeric_index_treated_as_literal() {
        // Medium-1: `"$prev[abc].id"` — non-numeric index is invalid.
        let r = req(r#"list(kind="concept") | get(id="$prev[abc].id")"#);
        assert_eq!(r.mode, ExecutionMode::Chain);
        assert!(
            matches!(r.ops[1].args["id"], ArgValue::Value(_)),
            "non-numeric bracket index quoted ref must be literal Value; got {:?}",
            r.ops[1].args["id"]
        );
    }

    #[test]
    fn unquoted_negative_index_rejected_at_parse_time() {
        // Regression: unquoted `$prev[-1].id` — the `-` is not a digit, so the
        // digit-reader finds an empty index string and returns InvalidValue.
        let err = parse_request(r#"list(kind="concept") | get(id=$prev[-1].id)"#).unwrap_err();
        assert!(
            matches!(err, DslError::InvalidValue { .. }),
            "expected InvalidValue for negative index in unquoted ref, got {err:?}"
        );
    }

    // ── ADR-038: write-key conflict detection ─────────────────────────────────

    #[test]
    fn no_conflict_on_non_write_ops() {
        // search + list ops share no write keys; must pass.
        let r =
            parse_request(r#"[list(kind="entity"), search(kind="entity", query="x")]"#).unwrap();
        check_write_key_conflicts(&r).unwrap();
    }

    #[test]
    fn update_and_delete_same_id_conflict() {
        // Two ops targeting the same UUID should be rejected.
        // Keys are substrate-prefixed: entity:<uuid>.
        let r =
            parse_request(r#"[update(id="abc-123", name="new"), delete(id="abc-123")]"#).unwrap();
        let err = check_write_key_conflicts(&r).unwrap_err();
        assert!(
            matches!(&err, DslError::WriteKeyConflict { id, first_op, second_op }
                if id == "entity:abc-123" && first_op == "update" && second_op == "delete"),
            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
        );
    }

    #[test]
    fn two_updates_same_id_conflict() {
        let r = parse_request(
            r#"[update(id="uuid-1", name="a"), update(id="uuid-1", description="b")]"#,
        )
        .unwrap();
        let err = check_write_key_conflicts(&r).unwrap_err();
        assert!(
            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:uuid-1"),
            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
        );
    }

    #[test]
    fn merge_from_id_conflicts_with_delete() {
        // merge's from_id overlaps a delete's id — both are entity writes.
        let r =
            parse_request(r#"[merge(into_id="new-id", from_id="old-id"), delete(id="old-id")]"#)
                .unwrap();
        let err = check_write_key_conflicts(&r).unwrap_err();
        assert!(
            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
        );
    }

    #[test]
    fn different_ids_no_conflict() {
        // Each op has a distinct UUID; no conflict.
        let r = parse_request(
            r#"[update(id="id-1", name="a"), delete(id="id-2"), update(id="id-3", name="c")]"#,
        )
        .unwrap();
        check_write_key_conflicts(&r).unwrap();
    }

    #[test]
    fn chain_mode_skips_conflict_detection() {
        // Chain ops run sequentially; write-key preflight is skipped.
        let r = parse_request(r#"update(id="same-id", name="a") | delete(id="same-id")"#).unwrap();
        assert_eq!(r.mode, ExecutionMode::Chain);
        // Must not return an error even though the same id appears in both ops.
        check_write_key_conflicts(&r).unwrap();
    }

    #[test]
    fn link_source_id_does_not_conflict_with_entity_update() {
        // update(id="X") + link(source_id="X", ...) must NOT conflict — `link` writes an
        // edge record, not the entity at "X".  Substrate-prefixed keys distinguish them:
        // entity:X vs edge-natural:X:Y:rel.
        let r = parse_request(
            r#"[update(id="node-1", name="x"), link(source_id="node-1", target_id="node-2", relation="extends")]"#,
        )
        .unwrap();
        check_write_key_conflicts(&r).unwrap();
    }

    #[test]
    fn two_links_same_natural_key_conflict() {
        // Two link ops targeting the same (source, target, relation) triple conflict
        // because they would produce duplicate edges.
        let r = parse_request(
            r#"[link(source_id="a", target_id="b", relation="extends"), link(source_id="a", target_id="b", relation="extends")]"#,
        )
        .unwrap();
        let err = check_write_key_conflicts(&r).unwrap_err();
        assert!(
            matches!(&err, DslError::WriteKeyConflict { id, .. }
                if id == "edge-natural:a:b:extends"),
            "expected WriteKeyConflict on edge-natural key, got {err:?}"
        );
    }

    #[test]
    fn single_write_op_no_conflict() {
        let r = parse_request(r#"delete(id="solo-id")"#).unwrap();
        assert_eq!(r.mode, ExecutionMode::Single);
        check_write_key_conflicts(&r).unwrap();
    }
}