khive-request 0.2.2

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
//! `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.
#[derive(Debug, Clone, PartialEq)]
pub enum ArgValue {
    /// A concrete JSON value.
    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 },
}

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 { .. } => 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`.
    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 path.split('.') {
            cur = cur.get(segment)?;
        }
        Some(cur)
    }
}

/// 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.
    PrevRefOutsideChain {
        pos: usize,
    },
    /// Mixing `,` and `|` at the top level.
    MixedSeparators,
}

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"
                )
            }
            DslError::MixedSeparators => {
                write!(
                    f,
                    "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
                )
            }
        }
    }
}

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

/// 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.
        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() {
        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.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.
        let args: BTreeMap<String, ArgValue> = args_map
            .into_iter()
            .map(|(k, v)| (k, ArgValue::Value(v)))
            .collect();
        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 Ok(ParsedRequest {
            ops,
            mode: ExecutionMode::Parallel,
        });
    }
    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(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",
        });
    }
    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}");
        }
        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 or a JSON literal.
    fn parse_arg_value(&mut self) -> Result<ArgValue, DslError> {
        self.skip_ws();
        if self.peek() == Some('$') {
            return self.parse_prev_ref();
        }
        let v = self.parse_value()?;
        Ok(ArgValue::Value(v))
    }

    /// Parse a `$prev` or `$prev.field.path` reference.
    ///
    /// Grammar: `$prev` optionally followed by `.identifier(.identifier)*`
    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 dot-path
        let mut path = String::new();
        while self.peek() == Some('.') {
            self.advance(1); // consume '.'
            let segment = self.parse_identifier()?;
            if !path.is_empty() {
                path.push('.');
            }
            path.push_str(&segment);
        }
        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)
    }

    /// 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 {
                        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)
    }
}

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 `PrevRef`.
    fn val(arg: &ArgValue) -> &Value {
        match arg {
            ArgValue::Value(v) => v,
            ArgValue::PrevRef { path } => {
                panic!("expected Value, got PrevRef {{ path: {path:?} }}")
            }
        }
    }

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

    #[test]
    fn single_op_with_string_arg() {
        let v = ops(r#"assign(title="ship release")"#);
        assert_eq!(v[0].tool, "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_is_legal() {
        let r = req("[]");
        assert_eq!(r.mode, ExecutionMode::Parallel);
        assert!(r.ops.is_empty());
    }

    #[test]
    fn nested_array_and_object_values() {
        let v = ops(r#"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#"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#"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":"next","args":{}}, {"tool":"complete","args":{"id":"abc"}}]"#);
        assert_eq!(r.mode, ExecutionMode::Parallel);
        assert_eq!(r.ops.len(), 2);
        assert_eq!(r.ops[1].tool, "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":"next","args":{}} ]"#);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].tool, "next");

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

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

    #[test]
    fn duplicate_arg_rejected() {
        let err = parse_request(r#"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#"next() garbage"#).unwrap_err();
        assert!(matches!(err, DslError::UnexpectedChar { .. }));
    }

    #[test]
    fn unclosed_paren_rejected() {
        let err = parse_request(r#"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#"assign(title="oops)"#).unwrap_err();
        assert!(matches!(err, DslError::UnclosedString));
    }

    #[test]
    fn too_many_ops_rejected() {
        let one = r#"next(),"#;
        let mut s = String::from("[");
        for _ in 0..MAX_OPS + 1 {
            s.push_str(one);
        }
        s.push_str("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#"recall(query="test")"#);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].tool, "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#"[recall(query="x"), inbox()]"#);
        assert_eq!(r.mode, ExecutionMode::Parallel);
        assert_eq!(r.ops.len(), 2);
        assert_eq!(r.ops[0].tool, "recall");
        assert_eq!(val(&r.ops[0].args["query"]), &json!("x"));
        assert_eq!(r.ops[1].tool, "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":"inbox"}"#);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].tool, "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#"recall.candidates(query="test", limit=5)"#);
        assert_eq!(v[0].tool, "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(), recall.fuse(query="x")]"#);
        assert_eq!(v.len(), 2);
        assert_eq!(v[0].tool, "brain.state");
        assert_eq!(v[1].tool, "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#"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#"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("next()");
        assert_eq!(r.mode, ExecutionMode::Single);
    }

    #[test]
    fn chain_too_many_ops_rejected() {
        let mut s = String::from("next()");
        for _ in 0..MAX_OPS {
            s.push_str(" | 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);
    }
}