khive-request 0.8.0

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
//! Integration tests for the `khive-request` DSL parser.
//!
//! All tests exercise the public API (`parse_request`, public types). Tests that
//! require access to `pub(crate)` helpers (`check_write_key_conflicts`) live in
//! `src/conflict.rs` under `#[cfg(test)] mod tests`.

use khive_request::{
    parse_request, parse_typed_json_batch, ArgValue, DslError, ExecutionMode, TypedJsonOp, MAX_OPS,
    MAX_OPS_INPUT_LEN, NESTING_DEPTH_LIMIT, RESERVED_ENVELOPE_ARGS,
};
use serde_json::json;

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

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

/// Extract the concrete `Value` from an `ArgValue::Value`, panicking on dynamic variants.
fn val(arg: &ArgValue) -> &serde_json::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())
        }
    }
}

// ── Basic single op ───────────────────────────────────────────────────────────

#[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));
}

// ── Batch ─────────────────────────────────────────────────────────────────────

#[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 multiline_string_value_round_trips() {
    // A literal raw newline (0x0A) inside a double-quoted value, as an agent
    // client would send it directly rather than escaping it to `\n` text.
    let src = "gtd.assign(title=\"line one\nline two\")";
    let v = ops(src);
    assert_eq!(val(&v[0].args["title"]), &json!("line one\nline two"));
}

#[test]
fn tab_and_carriage_return_literal_in_string() {
    let src = "gtd.assign(title=\"a\tb\rc\")";
    let v = ops(src);
    assert_eq!(val(&v[0].args["title"]), &json!("a\tb\rc"));
}

#[test]
fn mixed_literal_newline_and_escaped_sequences() {
    // A literal raw newline sits next to escaped-quote and escaped-backslash
    // pairs in the same value, proving the control-char rewrite does not
    // disturb adjacent backslash-escape pairs.
    let src = "comm.reply(content=\"line one \\\"quoted\\\"\nline two a\\\\b\")";
    let v = ops(src);
    assert_eq!(
        val(&v[0].args["content"]),
        &json!("line one \"quoted\"\nline two a\\b")
    );
}

#[test]
fn unterminated_multiline_string_rejected() {
    // A raw newline mid-string does not make an unclosed string legal; the
    // closing quote is still required somewhere in the input.
    let src = "gtd.assign(title=\"line one\nline two)";
    let err = parse_request(src).unwrap_err();
    assert!(matches!(err, DslError::UnclosedString));
}

#[test]
fn json_form_rejects_literal_newline_in_string() {
    // JSON form stays strict JSON: a raw control character inside a quoted
    // string is a parse error there, unlike the function-call form above.
    let src = "[{\"tool\":\"gtd.next\",\"args\":{\"note\":\"line one\nline two\"}}]";
    let err = parse_request(src).unwrap_err();
    assert!(matches!(err, DslError::InvalidJson { .. }));
}

// ── ADR-016 grammar-boundary matrix (round-1 review, PR #957) ────────────────

#[test]
fn crlf_preserved_exact_in_quoted_value() {
    // A literal CRLF pair (not just LF or CR alone) inside a quoted value
    // round-trips byte-for-byte, proving both bytes are rewritten
    // independently rather than the pair being collapsed or reordered.
    let src = "gtd.assign(title=\"line one\r\nline two\")";
    let v = ops(src);
    assert_eq!(val(&v[0].args["title"]), &json!("line one\r\nline two"));
}

#[test]
fn literal_newline_immediately_before_closing_quote() {
    // The raw newline is the very last byte before the closing `"`, with no
    // trailing content — the scanner must not mistake it for trailing
    // whitespace to trim, nor the rewrite skip the final byte.
    let src = "gtd.assign(title=\"abc\n\")";
    let v = ops(src);
    assert_eq!(val(&v[0].args["title"]), &json!("abc\n"));
}

#[test]
fn raw_newline_immediately_after_escaped_quote_boundary() {
    // A `\"` escape pair is immediately followed by a raw literal newline.
    // `scan_string_end` must consume the escape pair as a unit (not treat
    // its second byte as the closing quote), and the rewrite must copy the
    // escape pair through untouched before rewriting the adjacent raw LF.
    let src = "gtd.assign(title=\"a\\\"\nb\")";
    let v = ops(src);
    assert_eq!(val(&v[0].args["title"]), &json!("a\"\nb"));
}

#[test]
fn raw_control_char_in_bareword_position_rejected() {
    // The literal-control-char exception only applies inside a
    // double-quoted string value (`parse_value` only calls
    // `normalize_quoted_string` when the trimmed slice starts with
    // `"`). A raw NUL embedded in an unquoted (bareword) numeric value must
    // still fail to parse as JSON, exactly as before this PR.
    let src = format!("gtd.assign(weight=1{}0)", '\u{0}');
    let err = parse_request(&src).unwrap_err();
    assert!(
        matches!(err, DslError::InvalidValue { .. }),
        "expected InvalidValue for a raw control byte in bareword position, got {err:?}"
    );
}

#[test]
fn other_raw_control_chars_in_quoted_string_still_rejected() {
    // Only `\n`, `\r`, and `\t` are exempted (ADR-016). Every other raw
    // U+0000-U+001F byte inside a quoted value must remain a parse error,
    // matching pre-PR behavior — NUL, form feed, and ESC here.
    for raw in ['\u{0}', '\u{c}', '\u{1b}'] {
        let src = format!("gtd.assign(title=\"a{raw}b\")");
        let err = parse_request(&src).unwrap_err();
        assert!(
            matches!(err, DslError::InvalidValue { .. }),
            "expected InvalidValue for raw control byte {:#04x}, got {err:?}",
            raw as u32
        );
    }
}

#[test]
fn control_char_error_teaches_escape_syntax_without_transport_guidance() {
    // #491: the bare serde message ("control character ... found while
    // parsing a string") teaches nothing. The wrapped error must name the
    // JSON escape grammar while remaining transport-neutral; wire encoding
    // guidance belongs to the transport boundary, not this parser.
    let src = format!("gtd.assign(title=\"a{}b\")", '\u{c}');
    let err = parse_request(&src).unwrap_err();
    let msg = err.to_string();
    assert!(
        matches!(err, DslError::InvalidValue { .. }),
        "expected InvalidValue, got {err:?}"
    );
    assert!(
        msg.contains(r#"\n"#) && msg.contains(r#"\t"#) && msg.contains(r#"\""#),
        "error should name the JSON escape grammar, got: {msg}"
    );
    assert!(
        !msg.contains("MCP") && !msg.to_lowercase().contains("transport"),
        "generic parser error should stay transport-neutral, got: {msg}"
    );
}

#[test]
fn control_char_error_reports_value_relative_byte_index() {
    // #491: the diagnostic byte index is relative to the value, not the raw
    // quoted span; it must not count the opening quote. A control byte that is
    // the first byte of the value is reported as "byte 0 of the value", not
    // "byte 1".
    let src = format!("gtd.assign(title=\"{}b\")", '\u{c}');
    let err = parse_request(&src).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("byte 0 of the value"),
        "byte index must be value-relative (exclude the opening quote), got: {msg}"
    );
}

#[test]
fn control_char_in_object_key_rejected_with_plain_serde_message() {
    // #491: quoted object KEYS decode through a separate, strict path from
    // quoted values (`parse_object_arg_body` vs `parse_value`) — the
    // value-path escape-grammar teaching diagnostic is scoped to values only
    // (ADR-016, PR #957). A raw control byte in a key still fails to parse,
    // but with the plain serde message rather than the value-path
    // enrichment.
    let src = format!("gtd.assign(properties={{\"a{}b\":\"x\"}})", '\u{c}');
    let err = parse_request(&src).unwrap_err();
    let msg = err.to_string();
    assert!(
        matches!(err, DslError::InvalidValue { .. }),
        "expected InvalidValue, got {err:?}"
    );
    assert!(
        !msg.contains("DSL string escapes follow JSON"),
        "key-path error should not carry the value-path escape teaching, got: {msg}"
    );
}

#[test]
fn raw_control_byte_in_object_key_rejected() {
    // #491: the literal-newline/CR/tab carve-out (ADR-016, PR #957) is scoped
    // to quoted argument VALUES only. A quoted object KEY containing one of
    // these bytes raw must still be rejected — only the escaped form (`\n`,
    // `\r`, `\t`) is legal inside a key.
    for raw in ['\n', '\r', '\t'] {
        let src = format!("gtd.assign(properties={{\"a{raw}b\":\"x\"}})");
        let err = parse_request(&src).unwrap_err();
        assert!(
            matches!(err, DslError::InvalidValue { .. }),
            "expected InvalidValue for raw control byte {:#04x} in an object key, got {err:?}",
            raw as u32
        );
    }
}

#[test]
fn bareword_value_names_the_quoting_fix() {
    // `id=abc` is the most common invalid-value mistake: a string typed
    // without its surrounding quotes. The message must say it is a
    // bareword, that string values need double quotes, and — since the
    // argument name is known here — show the exact corrected call.
    let err = parse_request("get(id=abc)").unwrap_err();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    let msg = err.to_string();
    assert!(
        msg.contains("bareword") && msg.contains("double-quoted"),
        "must name the bareword and the quoting fix, got: {msg}"
    );
    assert!(
        msg.contains(r#"id="abc""#),
        "must show the corrected call, got: {msg}"
    );
}

#[test]
fn bareword_value_in_object_literal_uses_the_key_as_hint() {
    // Same mistake, inside a JSON-object-shaped argument value: the key is
    // known there too, so the reconstructed call still names it.
    let err = parse_request(r#"update(patch={"name": abc})"#).unwrap_err();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    let msg = err.to_string();
    assert!(
        msg.contains(r#"name="abc""#),
        "must show the corrected key:value, got: {msg}"
    );
}

#[test]
fn bareword_value_in_array_element_has_no_reconstruction_to_guess() {
    // Same mistake, as a bare array element: there is no argument name to
    // anchor a reconstruction to, so the message must describe the fix
    // without inventing a call it cannot verify.
    let err = parse_request("get(id=[abc])").unwrap_err();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    let msg = err.to_string();
    assert!(
        msg.contains("bareword") && msg.contains("double-quoted"),
        "must still name the bareword mistake, got: {msg}"
    );
}

#[test]
fn invalid_value_position_and_message_no_longer_disagree() {
    // Before this fix, a non-bareword invalid value (e.g. `1.2.3`) leaked
    // serde_json's own "at line 1 column N" — always relative to that
    // single value's isolated slice, so it disagreed with the DSL-absolute
    // "at position N" this crate reports for the same failure. The
    // descriptive part of the message stays; the contradicting position
    // clause must be gone.
    let err = parse_request("get(id=1.2.3)").unwrap_err();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    let msg = err.to_string();
    assert!(
        msg.starts_with("at position 7:"),
        "expected the DSL-absolute position, got: {msg}"
    );
    assert!(
        !msg.contains("line 1 column"),
        "must not leak serde's own, disagreeing position, got: {msg}"
    );
    assert!(
        msg.contains("trailing characters"),
        "must keep serde's descriptive text, got: {msg}"
    );
}

#[test]
fn json_request_form_keeps_its_own_serde_position() {
    // The JSON request form (an object/array of objects sent as `ops`) is
    // genuinely JSON end to end — its serde `line`/`column` IS the real
    // location of the problem, so it must NOT be stripped the way the
    // function-call form's per-value serde fragment is.
    let err = parse_request(r#"{"tool": "get", "args": {"id": }}"#).unwrap_err();
    assert!(matches!(err, DslError::InvalidJson { .. }));
    let msg = err.to_string();
    assert!(
        msg.contains("line 1 column"),
        "JSON form's own serde position is meaningful and must be kept, got: {msg}"
    );
}

#[test]
fn invalid_backslash_escape_in_quoted_string_rejected() {
    // A negative invalid-escape case: `\q` is not a JSON escape sequence.
    // This must fail regardless of the literal-newline carve-out.
    let src = r#"gtd.assign(title="bad \q escape")"#;
    let err = parse_request(src).unwrap_err();
    assert!(matches!(err, DslError::InvalidValue { .. }));
}

#[test]
fn invalid_escape_with_unrelated_control_byte_not_misattributed() {
    // #491 round-2 blocking fix 1(a): a `\q` invalid escape occurs before an
    // unrelated form-feed later in the same span. The failure is the `\q`,
    // not the control byte, so the control-char teaching diagnostic must NOT
    // fire — misattributing the error to the wrong byte would send a caller
    // chasing the wrong fix.
    let src = format!("gtd.assign(title=\"bad \\q escape{}tail\")", '\u{c}');
    let err = parse_request(&src).unwrap_err();
    let msg = err.to_string();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    assert!(
        !msg.contains("DSL string escapes follow JSON"),
        "an invalid \\q escape must not be enriched with the control-char diagnostic, got: {msg}"
    );
}

#[test]
fn malformed_unicode_escape_adjacent_to_control_byte_not_misattributed() {
    // A malformed `\u` escape (only 3 hex digits) followed immediately by a
    // raw control byte fails with serde's `InvalidEscape`, not a
    // control-character error — but the failure's byte offset can coincide
    // with the recorded control-byte hit (the 4th hex-digit slot serde reads
    // is the control byte itself). Offset alone is not enough to gate the
    // enrichment; the error's kind must also be checked, or this lands the
    // control-character escape guidance on an invalid-escape failure.
    let src = format!("gtd.assign(title=\"bad \\u123{}tail\")", '\u{c}');
    let err = parse_request(&src).unwrap_err();
    let msg = err.to_string();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    assert!(
        msg.contains("invalid escape"),
        "expected the plain serde invalid-escape message, got: {msg}"
    );
    assert!(
        !msg.contains("DSL string escapes follow JSON"),
        "a malformed \\u escape must not be enriched with the control-char diagnostic, got: {msg}"
    );
}

#[test]
fn short_unicode_escape_backslash_adjacent_control_byte_not_misattributed() {
    // A `\u` escape short by exactly 2 hex digits has its 3rd slot land on a
    // raw backslash and its 4th slot land on a raw control byte — so the
    // control byte IS physically adjacent to a backslash, unlike the
    // 3-hex-digit case above. That adjacency is spurious: both bytes are
    // consumed as `\u`'s own hex-digit slots, never reinterpreted as a fresh
    // `\<ctrl>` escape pair. The failure must stay the plain malformed
    // unicode-escape message with no control-character escape guidance.
    let src = format!("gtd.assign(title=\"bad \\u12\\{}tail\")", '\u{c}');
    let err = parse_request(&src).unwrap_err();
    let msg = err.to_string();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    assert!(
        msg.contains("invalid escape"),
        "expected the plain serde invalid-escape message, got: {msg}"
    );
    assert!(
        !msg.contains("DSL string escapes follow JSON"),
        "a short \\u escape landing on a backslash+control-byte pair must not be \
         enriched with the control-char diagnostic, got: {msg}"
    );

    // A genuine broken `\<ctrl>` pair with no preceding `\u` run still gets
    // the teaching diagnostic — the fix must not blind the guard to the
    // legitimate case.
    let genuine_src = format!("gtd.assign(title=\"before\\{}after\")", '\u{c}');
    let genuine_err = parse_request(&genuine_src).unwrap_err();
    let genuine_msg = genuine_err.to_string();
    assert!(matches!(genuine_err, DslError::InvalidValue { .. }));
    assert!(
        genuine_msg.contains("DSL string escapes follow JSON"),
        "a genuine broken \\<ctrl> pair must still get the escape guidance, got: {genuine_msg}"
    );
}

#[test]
fn leading_surrogate_escape_followed_by_control_byte_not_misattributed() {
    // #491 round-5: a well-formed high-surrogate `\u` escape (U+D800-U+DBFF)
    // must be followed by a `\u` low-surrogate escape. When the byte after the
    // continuation backslash is a raw control byte instead, `serde_json` fails
    // on the malformed surrogate continuation, not on a broken `\<ctrl>`
    // escape. Scan's general backslash-pair walk resets after the high
    // surrogate's 4 hex slots, so without the surrogate-continuation guard it
    // would record that `\<ctrl>` as a genuine broken pair
    // (`preceded_by_backslash: true`) and land the escape teaching on a
    // failure it does not explain. The continuation control byte must not be
    // recorded, so the error stays serde's own surrogate message.
    let src = format!("gtd.assign(title=\"bad \\uD800\\{}tail\")", '\u{c}');
    let err = parse_request(&src).unwrap_err();
    let msg = err.to_string();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    assert!(
        !msg.contains("DSL string escapes follow JSON"),
        "a control byte on a surrogate-continuation path must not be enriched \
         with the control-char escape diagnostic, got: {msg}"
    );

    // A broken `\<ctrl>` pair AFTER a complete surrogate pair (high + low) is a
    // real broken escape and still gets the teaching; the suppression is scoped
    // to the immediate continuation, not to everything after any `\u`.
    let after_pair = format!("gtd.assign(title=\"ok \\uD800\\uDC00\\{}tail\")", '\u{c}');
    let after_pair_err = parse_request(&after_pair).unwrap_err();
    let after_pair_msg = after_pair_err.to_string();
    assert!(matches!(after_pair_err, DslError::InvalidValue { .. }));
    assert!(
        after_pair_msg.contains("DSL string escapes follow JSON"),
        "a broken \\<ctrl> pair after a complete surrogate pair must still get \
         the escape guidance, got: {after_pair_msg}"
    );
}

#[test]
fn raw_newline_immediately_after_backslash_caught_as_control_char_cause() {
    // #491 round-2 blocking fix 1(b): a raw LF directly following a
    // backslash is not a valid two-byte JSON escape (valid escapes are
    // backslash + an ASCII letter, never backslash + a literal control
    // byte). This must be caught as a control-char cause and receive the
    // teaching diagnostic, not silently fall through to the bare serde
    // message.
    let src = "gtd.assign(title=\"before\\\nafter\")";
    let err = parse_request(src).unwrap_err();
    let msg = err.to_string();
    assert!(matches!(err, DslError::InvalidValue { .. }));
    assert!(
        msg.contains(r#"\n"#) && msg.contains(r#"\t"#) && msg.contains(r#"\""#),
        "error should name the JSON escape grammar, got: {msg}"
    );
    assert!(msg.contains("DSL string escapes follow JSON"));
}

#[test]
fn raw_carriage_return_and_tab_after_backslash_also_caught() {
    // Same defect as the LF case above, for CR and TAB.
    for raw in ['\r', '\t'] {
        let src = format!("gtd.assign(title=\"before\\{raw}after\")");
        let err = parse_request(&src).unwrap_err();
        assert!(
            matches!(err, DslError::InvalidValue { .. }),
            "expected InvalidValue for backslash + raw {:#04x}, got {err:?}",
            raw as u32
        );
        let msg = err.to_string();
        assert!(
            msg.contains("DSL string escapes follow JSON"),
            "error should explain DSL escape syntax for {:#04x}, got: {msg}",
            raw as u32
        );
    }
}

#[test]
fn backslash_followed_by_other_raw_control_bytes_also_caught() {
    // #491 round-2 blocking fix 2: the post-backslash branch previously
    // recorded a hit only for `\n`/`\r`/`\t`. A backslash followed by any
    // OTHER raw U+0000-U+001F byte — NUL, form feed, and ESC here — is
    // equally not a valid JSON escape and must reach the same teaching
    // diagnostic instead of the bare serde message.
    for raw in ['\u{0}', '\u{c}', '\u{1b}'] {
        let src = format!("gtd.assign(title=\"before\\{raw}after\")");
        let err = parse_request(&src).unwrap_err();
        assert!(
            matches!(err, DslError::InvalidValue { .. }),
            "expected InvalidValue for backslash + raw {:#04x}, got {err:?}",
            raw as u32
        );
        let msg = err.to_string();
        assert!(
            msg.contains("DSL string escapes follow JSON"),
            "error should explain DSL escape syntax for {:#04x}, got: {msg}",
            raw as u32
        );
    }
}

#[test]
fn batch_ops_separated_by_raw_newlines() {
    // The top-level batch `,` separator may be split across literal
    // newlines between ops, since `skip_ws` treats `\n` as ordinary
    // whitespace around the separator.
    let src = "[create(kind=\"entity\", name=\"A\"),\ncreate(kind=\"entity\", name=\"B\")]";
    let r = req(src);
    assert_eq!(r.mode, ExecutionMode::Parallel);
    assert_eq!(r.ops.len(), 2);
    assert_eq!(val(&r.ops[0].args["name"]), &json!("A"));
    assert_eq!(val(&r.ops[1].args["name"]), &json!("B"));
}

#[test]
fn chain_ops_separated_by_raw_newlines() {
    // The chain `|` separator may likewise be split across literal
    // newlines between ops.
    let src = "create(kind=\"entity\", name=\"A\")\n|\ncreate(kind=\"entity\", name=\"B\")";
    let r = req(src);
    assert_eq!(r.mode, ExecutionMode::Chain);
    assert_eq!(r.ops.len(), 2);
    assert_eq!(val(&r.ops[0].args["name"]), &json!("A"));
    assert_eq!(val(&r.ops[1].args["name"]), &json!("B"));
}

#[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));
}

// ── JSON form ─────────────────────────────────────────────────────────────────

#[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");
}

// ── Error cases ───────────────────────────────────────────────────────────────

#[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 ───────────────────────────────────────────────────────────────

#[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: `"\\$prev.id"` produces 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);
}

// ── PrevRefOutsideChain emitted at parse time ─────────────────────────────────

#[test]
fn prev_ref_in_single_op_is_rejected() {
    // `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() {
    // 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:?}"
    );
}

// ── MixedSeparators emitted at parse time ─────────────────────────────────────

#[test]
fn mixed_separators_in_fn_batch_rejected() {
    // `[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() {
    // `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() {
    // `[a(), b(), c()]` is valid comma-only parallel batch.
    let r = parse_request("[a(), b(), c()]").unwrap();
    assert_eq!(r.mode, ExecutionMode::Parallel);
    assert_eq!(r.ops.len(), 3);
}

#[test]
fn mixed_separator_before_any_chain_pipe_reaches_the_same_message() {
    // `a(), b() | c()` hits the mixed-separator mistake on the very first
    // op, before a chain `|` has ever been seen — a third code path from
    // the other two `MixedSeparators` tests above (`[a() | b(), c()]` and
    // `a() | b(), c()`). All three must reach the same actionable message,
    // not fall through to a generic "expected '|' or end of input" report.
    let err = parse_request("a(), b() | c()").unwrap_err();
    assert!(
        matches!(err, DslError::MixedSeparators),
        "expected MixedSeparators, got {err:?}"
    );
    let msg = err.to_string();
    assert!(
        msg.contains("cannot mix ',' (parallel) and '|' (chain) separators"),
        "message must name the mix mistake, got: {msg}"
    );
    assert!(
        msg.contains("two `request` calls")
            && msg.contains("one `[...]` batch")
            && msg.contains("a() | b(arg=$prev.id)"),
        "message must prescribe the documented two-call split, got: {msg}"
    );
}

#[test]
fn trailing_comma_before_batch_close_bracket_named() {
    // `[gtd.next(),]` used to fail with a confusing "invalid identifier"
    // report pointing at the `]` — the real mistake is the trailing `,`.
    let err = parse_request("[gtd.next(),]").unwrap_err();
    assert!(
        matches!(err, DslError::TrailingComma { .. }),
        "expected TrailingComma, got {err:?}"
    );
    let msg = err.to_string();
    assert!(
        msg.contains("trailing comma"),
        "message must name the trailing comma, got: {msg}"
    );
}

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

// ── multi-segment dotted verb → clear error ───────────────────────────────────

#[test]
fn three_segment_verb_name_rejected() {
    // `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#"search(kind="concept", query="root index") | 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#"search(kind="concept", query="quoted root index") | get(id="$prev[0].id")"#);
    assert_eq!(r.mode, ExecutionMode::Chain);
    assert_eq!(
        r.ops[1].args["id"],
        ArgValue::PrevRef {
            path: "[0].id".into()
        }
    );
}

// ── JSON-form recursive $prev detection ──────────────────────────────────────

#[test]
fn json_form_nested_array_with_prev_ref_is_rejected() {
    // `$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() {
    // `$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() {
    // 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() {
    // 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")));
}

// ── Escape semantics produce clean literal ───────────────────────────────────

#[test]
fn escaped_dollar_prev_without_path_stays_literal() {
    // `"\\$prev"` produces 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() {
    // `"\\$prev[0].id"` produces 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")));
}

// ── Quoted bracket index validation ──────────────────────────────────────────

#[test]
fn quoted_prev_ref_negative_index_treated_as_literal() {
    // `"$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() {
    // `"$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() {
    // `"$prev[abc].id"`: a 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"]
    );
}

// ── #484 regression: nested malformed bracket paths in a quoted dotted ref ────

#[test]
fn quoted_prev_ref_nested_negative_index_treated_as_literal() {
    // #484: `"$prev.items[-1].id"` — malformed bracket after a field segment
    // must stay a literal Value, not be promoted to PrevRef.
    let r = req(r#"list(kind="concept") | get(id="$prev.items[-1].id")"#);
    assert_eq!(r.mode, ExecutionMode::Chain);
    assert_eq!(
        r.ops[1].args["id"],
        ArgValue::Value(json!("$prev.items[-1].id"))
    );
}

#[test]
fn quoted_prev_ref_nested_non_numeric_index_treated_as_literal() {
    // #484: `"$prev.items[abc].id"` — non-numeric nested index is malformed.
    let r = req(r#"list(kind="concept") | get(id="$prev.items[abc].id")"#);
    assert_eq!(r.mode, ExecutionMode::Chain);
    assert_eq!(
        r.ops[1].args["id"],
        ArgValue::Value(json!("$prev.items[abc].id"))
    );
}

#[test]
fn quoted_prev_ref_nested_missing_close_bracket_treated_as_literal() {
    // #484: `"$prev.items[0.id"` — unclosed nested bracket is malformed.
    let r = req(r#"list(kind="concept") | get(id="$prev.items[0.id")"#);
    assert_eq!(r.mode, ExecutionMode::Chain);
    assert_eq!(
        r.ops[1].args["id"],
        ArgValue::Value(json!("$prev.items[0.id"))
    );
}

#[test]
fn quoted_prev_ref_nested_valid_index_still_promotes_and_resolves() {
    // #484 non-regression: a well-formed nested bracket path must still
    // promote to PrevRef and resolve correctly.
    let r = req(r#"list(kind="concept") | get(id="$prev.items[0].id")"#);
    assert_eq!(r.mode, ExecutionMode::Chain);
    assert_eq!(
        r.ops[1].args["id"],
        ArgValue::PrevRef {
            path: "items[0].id".into()
        }
    );
    let prev = json!({"items": [{"id": "ok"}]});
    assert_eq!(r.ops[1].args["id"].resolve_prev(&prev), Some(&json!("ok")));
}

#[test]
fn quoted_prev_ref_root_bracket_with_malformed_nested_tail_treated_as_literal() {
    // #484 risk flag: the root `$prev[N]...` branch must also validate
    // malformed brackets in its tail, e.g. `"$prev[0].items[-1].id"`.
    let r = req(r#"list(kind="concept") | get(id="$prev[0].items[-1].id")"#);
    assert_eq!(r.mode, ExecutionMode::Chain);
    assert_eq!(
        r.ops[1].args["id"],
        ArgValue::Value(json!("$prev[0].items[-1].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:?}"
    );
}

// ── write_keys_for_op_pub (public extraction helper for MCP server) ────────────

#[test]
fn write_keys_for_op_pub_update() {
    use khive_request::write_keys_for_op_pub;
    use std::collections::BTreeMap;
    let op = khive_request::ParsedOp {
        tool: "update".into(),
        args: {
            let mut m = BTreeMap::new();
            m.insert("id".into(), ArgValue::Value(json!("some-uuid")));
            m
        },
    };
    assert_eq!(write_keys_for_op_pub(&op), vec!["entity:some-uuid"]);
}

#[test]
fn write_keys_for_op_pub_link() {
    use khive_request::write_keys_for_op_pub;
    use std::collections::BTreeMap;
    let op = khive_request::ParsedOp {
        tool: "link".into(),
        args: {
            let mut m = BTreeMap::new();
            m.insert("source_id".into(), ArgValue::Value(json!("a")));
            m.insert("target_id".into(), ArgValue::Value(json!("b")));
            m.insert("relation".into(), ArgValue::Value(json!("extends")));
            m
        },
    };
    assert_eq!(write_keys_for_op_pub(&op), vec!["edge-natural:a:b:extends"]);
}

// ── ADR-045: reserved envelope args rejected inside verb args ─────────────────

#[test]
fn presentation_in_fn_call_args_rejected() {
    let err = parse_request(r#"list(kind="task", presentation="agent")"#).unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::ReservedEnvelopeArg { arg_name, verb }
            if arg_name == "presentation" && verb == "list"
        ),
        "expected ReservedEnvelopeArg, got {err:?}"
    );
}

#[test]
fn presentation_per_op_in_fn_call_args_rejected() {
    let err = parse_request(r#"list(kind="task", presentation_per_op="verbose")"#).unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::ReservedEnvelopeArg { arg_name, verb }
            if arg_name == "presentation_per_op" && verb == "list"
        ),
        "expected ReservedEnvelopeArg, got {err:?}"
    );
}

#[test]
fn presentation_in_json_form_args_rejected() {
    let err = parse_request(r#"{"tool":"list","args":{"kind":"task","presentation":"agent"}}"#)
        .unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::ReservedEnvelopeArg { arg_name, verb }
            if arg_name == "presentation" && verb == "list"
        ),
        "expected ReservedEnvelopeArg, got {err:?}"
    );
}

#[test]
fn presentation_in_fn_batch_args_rejected() {
    let err = parse_request(r#"[list(kind="task", presentation="agent"), search(query="x")]"#)
        .unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::ReservedEnvelopeArg { arg_name, verb }
            if arg_name == "presentation" && verb == "list"
        ),
        "expected ReservedEnvelopeArg, got {err:?}"
    );
}

#[test]
fn presentation_in_chain_args_rejected() {
    let err = parse_request(r#"list(kind="task") | get(id=$prev.id, presentation="verbose")"#)
        .unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::ReservedEnvelopeArg { arg_name, verb }
            if arg_name == "presentation" && verb == "get"
        ),
        "expected ReservedEnvelopeArg, got {err:?}"
    );
}

#[test]
fn non_reserved_presentation_like_arg_accepted() {
    let r = req(r#"list(kind="task", present="yes")"#);
    assert_eq!(r.mode, ExecutionMode::Single);
    assert_eq!(val(&r.ops[0].args["present"]), &json!("yes"));
}

#[test]
fn preference_verbs_share_the_envelope_reserved_argument_contract() {
    for verb in [
        "moodboard.serve",
        "moodboard.judge",
        "moodboard.train_preference",
        "moodboard.preference",
    ] {
        for argument in RESERVED_ENVELOPE_ARGS {
            let error = parse_typed_json_batch(vec![TypedJsonOp {
                tool: verb.to_string(),
                args: serde_json::Map::from_iter([((*argument).to_string(), json!("verbose"))]),
            }])
            .expect_err("envelope-owned names must fail before every preference handler");
            assert!(
                matches!(
                    error,
                    DslError::ReservedEnvelopeArg { ref arg_name, verb: ref error_verb }
                        if arg_name == argument && error_verb == verb
                ),
                "unexpected error for {verb}.{argument}: {error:?}"
            );
        }
    }
}

/// RUNTIME-AUD-002 (#433): the JSON-form parser must preserve a present-but
/// non-string `namespace` verbatim (as `ArgValue::Value`), never dropping or
/// coercing it. This is the ingress link that carries the malformed value into
/// `VerbRegistry::dispatch`, where `namespace_null_rejected_not_coerced` proves
/// it is rejected with `InvalidInput` before the gate is ever consulted.
/// Together the two tests cover the full MCP JSON-form path end to end.
#[test]
fn json_form_namespace_non_string_preserved_for_dispatch_rejection() {
    let cases = [
        json!(null),
        json!(42),
        json!(true),
        json!(["local"]),
        json!({ "ns": "local" }),
    ];
    for ns in cases {
        let body = json!([{
            "tool": "create",
            "args": { "kind": "entity", "entity_kind": "concept", "name": "N", "namespace": ns },
        }]);
        let r = req(&body.to_string());
        assert_eq!(r.ops.len(), 1, "namespace={ns} should parse to one op");
        // `namespace` is NOT a reserved envelope arg — it survives parsing as a
        // raw Value and reaches the runtime dispatch chokepoint unchanged.
        assert_eq!(
            val(&r.ops[0].args["namespace"]),
            &ns,
            "namespace={ns} must be preserved verbatim, not dropped or coerced"
        );
    }
}

// --- #771: bounded input length + bounded container-nesting depth ---
//
// Regression coverage for CWE-674 (unbounded recursive descent). Three
// independent recursion sites are guarded: the function-call array/object
// parser (`parse_array_arg`/`parse_object_arg`), the JSON-form pre-pass scan
// ahead of `serde_json::from_str`, and `$prev` nesting inside chain mode
// (covered for free since `ArgValue::Array`/`Object` are only ever
// constructed inside the same depth-guarded parser functions).

fn nested_array_arg(depth: usize) -> String {
    format!("verb(x={}{})", "[".repeat(depth), "]".repeat(depth))
}

fn nested_object_arg(depth: usize) -> String {
    format!("verb(x={}1{})", "{\"a\":".repeat(depth), "}".repeat(depth))
}

/// JSON-form envelope overhead before the user's own nesting begins: the
/// batch array `[`, the op object `{`, and the `args` object `{`, 3 levels total.
const JSON_FORM_ENVELOPE_DEPTH: usize = 3;

fn nested_json_form(inner_depth: usize) -> String {
    format!(
        "[{{\"tool\":\"x\",\"args\":{{\"a\":{}{}}}}}]",
        "[".repeat(inner_depth),
        "]".repeat(inner_depth)
    )
}

fn nested_prev_ref_in_chain(depth: usize) -> String {
    format!(
        "op1() | op2(x={}$prev{})",
        "[".repeat(depth),
        "]".repeat(depth)
    )
}

#[test]
fn array_nesting_at_limit_succeeds() {
    let r = parse_request(&nested_array_arg(NESTING_DEPTH_LIMIT));
    assert!(
        r.is_ok(),
        "depth {NESTING_DEPTH_LIMIT} (at limit) must parse: {r:?}"
    );
}

#[test]
fn array_nesting_over_limit_rejects_cleanly() {
    let err = parse_request(&nested_array_arg(NESTING_DEPTH_LIMIT + 1)).unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::NestingTooDeep { depth, max, .. }
            if *depth == NESTING_DEPTH_LIMIT + 1 && *max == NESTING_DEPTH_LIMIT
        ),
        "expected NestingTooDeep, got {err:?}"
    );
}

#[test]
fn object_nesting_at_limit_succeeds() {
    let r = parse_request(&nested_object_arg(NESTING_DEPTH_LIMIT));
    assert!(
        r.is_ok(),
        "depth {NESTING_DEPTH_LIMIT} (at limit) must parse: {r:?}"
    );
}

#[test]
fn object_nesting_over_limit_rejects_cleanly() {
    let err = parse_request(&nested_object_arg(NESTING_DEPTH_LIMIT + 1)).unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::NestingTooDeep { depth, max, .. }
            if *depth == NESTING_DEPTH_LIMIT + 1 && *max == NESTING_DEPTH_LIMIT
        ),
        "expected NestingTooDeep, got {err:?}"
    );
}

#[test]
fn json_form_nesting_at_limit_succeeds() {
    let inner = NESTING_DEPTH_LIMIT - JSON_FORM_ENVELOPE_DEPTH;
    let r = parse_request(&nested_json_form(inner));
    assert!(r.is_ok(), "at-limit JSON-form nesting must parse: {r:?}");
}

#[test]
fn json_form_nesting_over_limit_rejects_cleanly() {
    let inner = NESTING_DEPTH_LIMIT - JSON_FORM_ENVELOPE_DEPTH + 1;
    let err = parse_request(&nested_json_form(inner)).unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::NestingTooDeep { depth, max, .. }
            if *depth == NESTING_DEPTH_LIMIT + 1 && *max == NESTING_DEPTH_LIMIT
        ),
        "expected NestingTooDeep, got {err:?}"
    );
}

#[test]
fn prev_ref_nesting_in_chain_at_limit_succeeds() {
    let r = parse_request(&nested_prev_ref_in_chain(NESTING_DEPTH_LIMIT));
    assert!(
        r.is_ok(),
        "at-limit $prev nesting in chain mode must parse: {r:?}"
    );
    assert_eq!(r.unwrap().mode, ExecutionMode::Chain);
}

#[test]
fn prev_ref_nesting_in_chain_over_limit_rejects_cleanly() {
    let err = parse_request(&nested_prev_ref_in_chain(NESTING_DEPTH_LIMIT + 1)).unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::NestingTooDeep { depth, max, .. }
            if *depth == NESTING_DEPTH_LIMIT + 1 && *max == NESTING_DEPTH_LIMIT
        ),
        "expected NestingTooDeep, got {err:?}"
    );
}

#[test]
fn oversized_ops_input_rejected_before_parsing() {
    let huge = format!("verb(x=\"{}\")", "a".repeat(MAX_OPS_INPUT_LEN + 1));
    let err = parse_request(&huge).unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::InputTooLarge { len, max }
            if *len > MAX_OPS_INPUT_LEN && *max == MAX_OPS_INPUT_LEN
        ),
        "expected InputTooLarge, got {err:?}"
    );
}

#[test]
fn typed_json_batch_uses_transport_bounds_instead_of_raw_dsl_cap() {
    let mut args = serde_json::Map::new();
    args.insert(
        "payload".to_string(),
        json!("x".repeat(MAX_OPS_INPUT_LEN + 1)),
    );

    let parsed = parse_typed_json_batch(vec![TypedJsonOp {
        tool: "blob.put".to_string(),
        args,
    }])
    .expect("the bounded typed transport must not reapply the raw DSL byte cap");

    assert_eq!(parsed.mode, ExecutionMode::Parallel);
    assert_eq!(parsed.ops.len(), 1);
    assert_eq!(parsed.ops[0].tool, "blob.put");
    assert_eq!(
        val(&parsed.ops[0].args["payload"]).as_str().unwrap().len(),
        MAX_OPS_INPUT_LEN + 1
    );
}

#[test]
fn typed_json_batch_preserves_json_form_structural_guards() {
    assert!(matches!(
        parse_typed_json_batch(Vec::new()),
        Err(DslError::EmptyBatch)
    ));
    let over_count = (0..=MAX_OPS)
        .map(|index| TypedJsonOp {
            tool: format!("probe_{index}"),
            args: serde_json::Map::new(),
        })
        .collect();
    assert!(matches!(
        parse_typed_json_batch(over_count),
        Err(DslError::TooManyOps { count, max }) if count == MAX_OPS + 1 && max == MAX_OPS
    ));

    let reserved = TypedJsonOp {
        tool: "list".to_string(),
        args: serde_json::Map::from_iter([
            ("kind".to_string(), json!("concept")),
            ("presentation".to_string(), json!("verbose")),
        ]),
    };
    assert!(matches!(
        parse_typed_json_batch(vec![reserved]),
        Err(DslError::ReservedEnvelopeArg { arg_name, .. }) if arg_name == "presentation"
    ));

    let exposure = TypedJsonOp {
        tool: "moodboard.serve".to_string(),
        args: serde_json::Map::from_iter([(
            "exposure".to_string(),
            json!({"preference_probability_shown": false, "source_rank_shown": true}),
        )]),
    };
    let parsed = parse_typed_json_batch(vec![exposure])
        .expect("business exposure provenance must not collide with the request envelope");
    assert_eq!(
        val(&parsed.ops[0].args["exposure"])["source_rank_shown"],
        true
    );

    let prev = TypedJsonOp {
        tool: "get".to_string(),
        args: serde_json::Map::from_iter([("id".to_string(), json!({"nested": "$prev.id"}))]),
    };
    assert!(matches!(
        parse_typed_json_batch(vec![prev]),
        Err(DslError::PrevRefInJsonForm { arg_name }) if arg_name == "id"
    ));

    let mut at_limit = json!(null);
    for _ in 0..(NESTING_DEPTH_LIMIT - 3) {
        at_limit = json!([at_limit]);
    }
    let at_limit = TypedJsonOp {
        tool: "stats".to_string(),
        args: serde_json::Map::from_iter([("payload".to_string(), at_limit)]),
    };
    assert!(parse_typed_json_batch(vec![at_limit]).is_ok());

    let mut over_limit = json!(null);
    for _ in 0..(NESTING_DEPTH_LIMIT - 2) {
        over_limit = json!([over_limit]);
    }
    let over_limit = TypedJsonOp {
        tool: "stats".to_string(),
        args: serde_json::Map::from_iter([("payload".to_string(), over_limit)]),
    };
    assert!(matches!(
        parse_typed_json_batch(vec![over_limit]),
        Err(DslError::NestingTooDeep { max, .. }) if max == NESTING_DEPTH_LIMIT
    ));
}

#[test]
fn ops_input_at_max_len_boundary_still_parses() {
    // Pad a trivially valid op with a comment-free string arg up to exactly
    // MAX_OPS_INPUT_LEN bytes, proving the length cap does not reject
    // legitimate input sitting right at the boundary.
    let prefix = "verb(x=\"";
    let suffix = "\")";
    let pad_len = MAX_OPS_INPUT_LEN - prefix.len() - suffix.len();
    let input = format!("{prefix}{}{suffix}", "a".repeat(pad_len));
    assert_eq!(input.len(), MAX_OPS_INPUT_LEN);
    let r = parse_request(&input);
    assert!(
        r.is_ok(),
        "input at exactly the length cap must parse: {r:?}"
    );
}

/// Build a JSON-form `create` op carrying `count` bulk `items`, each with a
/// `description` of `desc_len` bytes, mirrors the ADR-038 1000-item bulk
/// contract (`crates/khive-pack-kg/src/handler_defs.rs` `items` param).
fn bulk_create_payload(count: usize, desc_len: usize) -> String {
    let items: Vec<serde_json::Value> = (0..count)
        .map(|i| {
            json!({
                "kind": "concept",
                "name": format!("item-{i}"),
                "description": "d".repeat(desc_len),
            })
        })
        .collect();
    let payload = json!([{ "tool": "create", "args": { "kind": "concept", "items": items } }]);
    payload.to_string()
}

#[test]
fn bulk_create_1000_items_at_220_byte_descriptions_parses() {
    // ADR-038 promises up to 1000 items per bulk `create`; 220-byte
    // descriptions land the realistic payload around 276 KB, comfortably
    // under MAX_OPS_INPUT_LEN (1 MiB) but well over the old 256 KiB cap this
    // finding raised the limit to fix.
    let input = bulk_create_payload(1000, 220);
    assert!(
        input.len() > 256 * 1024 && input.len() < MAX_OPS_INPUT_LEN,
        "expected a realistic ~276 KB bulk payload, got {} bytes",
        input.len()
    );
    let parsed = parse_request(&input)
        .unwrap_or_else(|e| panic!("realistic 1000-item bulk create must parse: {e}"));
    assert_eq!(parsed.ops.len(), 1);
    assert_eq!(parsed.ops[0].tool, "create");
}

#[test]
fn oversized_bulk_create_payload_rejected_before_parsing() {
    // Same bulk-create shape, but padded well past MAX_OPS_INPUT_LEN, the
    // cap must still reject pathological input even in the documented-contract
    // shape it was raised to accommodate.
    let input = bulk_create_payload(1000, 2000);
    assert!(
        input.len() > MAX_OPS_INPUT_LEN,
        "test payload must exceed the cap, got {} bytes",
        input.len()
    );
    let err = parse_request(&input).unwrap_err();
    assert!(
        matches!(
            &err,
            DslError::InputTooLarge { len, max }
            if *len > MAX_OPS_INPUT_LEN && *max == MAX_OPS_INPUT_LEN
        ),
        "expected InputTooLarge, got {err:?}"
    );
}

#[test]
fn realistic_nested_payload_well_under_limit_still_parses() {
    // Regression guard (test plan item 5): a `kg.propose`-shaped nested
    // changeset payload, several levels deep, must keep parsing under the
    // new depth guard exactly as it did before this change.
    let r = req(
        r#"propose(title="t", description="d", changeset=[{"op":"create","fields":{"tags":["a","b"],"props":{"nested":{"deep":[1,2,3]}}}}])"#,
    );
    assert_eq!(r.mode, ExecutionMode::Single);
}

// ── ArgValue::find_prev_failure — $prev substitution error diagnosis ───────
//
// These exercise `find_prev_failure` directly against hand-built `ArgValue`s
// rather than through `parse_request`, because the DSL parser (both the
// unquoted `$prev[..]` grammar above and `quoted_prev_path_is_valid` for the
// quoted-string form) already rejects malformed bracket syntax before an
// `ArgValue::PrevRef` is ever constructed — that parser-level rejection is
// covered in `khive-mcp`'s integration suite
// (`test_prev_malformed_index_rejected_at_parse_time`). The substituter's own
// `PrevFailure::Unsupported` defense is otherwise unreachable through the
// public DSL surface today, so it is verified here, directly, as
// defense-in-depth against a future caller that builds an `ArgValue` some
// other way (e.g. a second parser front-end).

use khive_request::PrevFailure;
use serde_json::Value as JsonValue;

fn prev_ref(path: &str) -> ArgValue {
    ArgValue::PrevRef {
        path: path.to_string(),
    }
}

#[test]
fn find_prev_failure_reports_not_found_for_missing_field() {
    let prev: JsonValue = json!({"id": "abc", "kind": "concept"});
    let failure = prev_ref("bogus").find_prev_failure(&prev);
    match failure {
        Some(PrevFailure::NotFound {
            missing, available, ..
        }) => {
            assert_eq!(missing, "bogus");
            assert!(available.contains(&"id".to_string()));
        }
        other => panic!("expected NotFound, got {other:?}"),
    }
}

#[test]
fn find_prev_failure_renders_root_index_as_valid_dsl_path() {
    let parsed = req(r#"search(kind="concept", query="missing root index") | get(id=$prev[2])"#);
    let failure = parsed.ops[1].args["id"]
        .find_prev_failure(&json!([]))
        .expect("out-of-range index must report a substitution failure");
    let rendered = failure.to_string();
    assert_eq!(
        rendered.split_once(':').map(|(path, _)| path),
        Some("$prev[2]")
    );
}

#[test]
fn find_prev_failure_renders_nested_index_as_valid_dsl_path() {
    let parsed = req(r#"list(kind="concept") | get(id=$prev.items[0].id)"#);
    let failure = parsed.ops[1].args["id"]
        .find_prev_failure(&json!({"items": []}))
        .expect("out-of-range index must report a substitution failure");
    let rendered = failure.to_string();
    assert_eq!(
        rendered.split_once(':').map(|(path, _)| path),
        Some("$prev.items[0].id")
    );
}

#[test]
fn find_prev_failure_reports_wrong_type_for_field_on_scalar() {
    let prev: JsonValue = json!({"name": "concept-1"});
    let failure = prev_ref("name.sub").find_prev_failure(&prev);
    match failure {
        Some(PrevFailure::WrongType {
            expected, found, ..
        }) => {
            assert_eq!(expected, "object");
            assert_eq!(found, "string");
        }
        other => panic!("expected WrongType, got {other:?}"),
    }
}

#[test]
fn find_prev_failure_reports_wrong_type_for_index_on_object() {
    let prev: JsonValue = json!({"items": {"not": "an array"}});
    let failure = prev_ref("items[0]").find_prev_failure(&prev);
    match failure {
        Some(PrevFailure::WrongType {
            expected, found, ..
        }) => {
            assert_eq!(expected, "array");
            assert_eq!(found, "object");
        }
        other => panic!("expected WrongType, got {other:?}"),
    }
}

#[test]
fn find_prev_failure_reports_unsupported_for_malformed_bracket() {
    // `ArgValue::PrevRef` built directly (bypassing the parser, which never
    // produces this shape) to exercise the substituter's own defense.
    let prev: JsonValue = json!({"id": "abc"});
    let failure = prev_ref("[bad]").find_prev_failure(&prev);
    match failure {
        Some(PrevFailure::Unsupported { segment, .. }) => {
            assert_eq!(segment, "[bad]");
        }
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

#[test]
fn find_prev_failure_none_when_resolve_all_succeeds() {
    let prev: JsonValue = json!({"id": "abc", "nested": {"x": 1}});
    let arg = prev_ref("nested.x");
    assert!(arg.resolve_all(&prev).is_some());
    assert!(arg.find_prev_failure(&prev).is_none());
}