Skip to main content

khive_request/
lib.rs

1//! `khive-request` — request-DSL parser, transport-agnostic.
2//!
3//! ## Scope
4//!
5//! Conceptually every transport into khive walks the same pipeline:
6//!
7//! ```text
8//! request string  →  parse  →  ParsedRequest  →  dispatch (VerbRegistry)  →  result
9//! ```
10//!
11//! This crate owns only the *parse* step. The AST it produces (`ParsedRequest`,
12//! `ParsedOp`) is consumed by transports (MCP today; HTTP gateway, FFI, CLI
13//! in future) which then dispatch through `khive-runtime`'s [`VerbRegistry`].
14//!
15//! Keeping the parser in its own crate frees us to grow the syntax — pipe
16//! chains, `$prev` substitution, LNDL-style natural-language declarations,
17//! bash-flavoured redirections — without touching the runtime layering.
18//!
19//! ## Today's syntax (ADR-016)
20//!
21//! - **Single op**: `tool_name(arg=value, arg=value)` — `ExecutionMode::Single`
22//! - **Parallel batch**: `[tool_name(...), tool_name(...)]` — `ExecutionMode::Parallel`
23//! - **Sequential chain**: `op1(...) | op2(id=$prev.id)` — `ExecutionMode::Chain`
24//! - **JSON form**: `[{"tool":"...", "args": {...}}, ...]` (or a single object)
25//!
26//! Argument values are JSON literals — strings, numbers, booleans, `null`,
27//! arrays, objects. Chain-only: `$prev` and `$prev.field.path` references resolve
28//! at dispatch time against the preceding op's result.
29
30use std::collections::BTreeMap;
31use std::fmt;
32
33use serde_json::{Map, Value};
34
35/// Hard cap on operations per request. ADR-016 §Why-100.
36pub const MAX_OPS: usize = 100;
37
38/// Execution mode for a [`ParsedRequest`] (ADR-016).
39///
40/// - `Single`: one operation, no batching.
41/// - `Parallel`: operations separated by `,` inside `[...]`; run concurrently,
42///   results in input order.
43/// - `Chain`: operations separated by `|`; run sequentially, each op may
44///   reference the prior op's result via `$prev` / `$prev.field.path`.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum ExecutionMode {
47    /// One operation, no batching or chaining.
48    Single,
49    /// `[op1(...), op2(...)]` — parallel, best-effort, independent results.
50    Parallel,
51    /// `op1(...) | op2(id=$prev.id)` — sequential, abort-on-failure.
52    Chain,
53}
54
55/// An argument value in a [`ParsedOp`].
56///
57/// Most arguments are concrete JSON values. In chain ops (ADR-016 §Chain
58/// semantics), arguments may reference the preceding op's result via `$prev`
59/// or `$prev.dotted.path`. Substitution happens at dispatch time, not at parse
60/// time, because the prior result isn't known until runtime.
61#[derive(Debug, Clone, PartialEq)]
62pub enum ArgValue {
63    /// A concrete JSON value.
64    Value(Value),
65    /// A `$prev` or `$prev.field.path` reference — chain mode only.
66    ///
67    /// `path` is the dot-separated field path after `$prev`. Empty string means
68    /// the whole prior result (`$prev` with no field selector).
69    PrevRef { path: String },
70}
71
72impl ArgValue {
73    /// Returns the contained [`Value`] if this is `ArgValue::Value`.
74    pub fn as_value(&self) -> Option<&Value> {
75        match self {
76            ArgValue::Value(v) => Some(v),
77            ArgValue::PrevRef { .. } => None,
78        }
79    }
80
81    /// Returns `true` if this is a `$prev` reference.
82    pub fn is_prev_ref(&self) -> bool {
83        matches!(self, ArgValue::PrevRef { .. })
84    }
85
86    /// Resolve a `$prev` reference against a preceding op's result.
87    ///
88    /// Returns the extracted field value, or `None` if the path doesn't
89    /// exist in `prev_result`. Non-`PrevRef` variants return `None`.
90    pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
91        let ArgValue::PrevRef { path } = self else {
92            return None;
93        };
94        if path.is_empty() {
95            return Some(prev_result);
96        }
97        let mut cur = prev_result;
98        for segment in path.split('.') {
99            cur = cur.get(segment)?;
100        }
101        Some(cur)
102    }
103}
104
105/// A single parsed operation: tool name + named argument bag.
106///
107/// Arguments may be concrete [`ArgValue::Value`]s or `$prev` references
108/// ([`ArgValue::PrevRef`]) that the dispatcher resolves against the prior op's
109/// result (chain mode only).
110#[derive(Debug, Clone, PartialEq)]
111pub struct ParsedOp {
112    pub tool: String,
113    pub args: BTreeMap<String, ArgValue>,
114}
115
116/// Result of parsing a `request` input string (ADR-016).
117///
118/// The `mode` field tells the dispatcher how to execute the operations:
119/// - `Single`: dispatch the one op, wrap in a single-element envelope.
120/// - `Parallel`: dispatch all ops concurrently via `join_all`, collect in order.
121/// - `Chain`: dispatch ops sequentially; substitute `$prev` references between
122///   ops; abort remaining ops when any op or substitution fails.
123#[derive(Debug, Clone, PartialEq)]
124pub struct ParsedRequest {
125    pub ops: Vec<ParsedOp>,
126    pub mode: ExecutionMode,
127}
128
129/// Parser error — surfaced as `invalid_params` at the MCP boundary.
130#[derive(Debug, Clone, PartialEq)]
131pub enum DslError {
132    Empty,
133    TooManyOps {
134        count: usize,
135        max: usize,
136    },
137    UnexpectedChar {
138        pos: usize,
139        found: char,
140        expected: &'static str,
141    },
142    UnexpectedEof {
143        expected: &'static str,
144    },
145    InvalidIdentifier {
146        pos: usize,
147    },
148    DuplicateArg {
149        name: String,
150    },
151    InvalidValue {
152        pos: usize,
153        error: String,
154    },
155    InvalidJson {
156        error: String,
157    },
158    UnclosedString,
159    UnclosedBracket {
160        kind: char,
161    },
162    /// `$prev` reference used outside a chain context.
163    PrevRefOutsideChain {
164        pos: usize,
165    },
166    /// Mixing `,` and `|` at the top level.
167    MixedSeparators,
168}
169
170impl fmt::Display for DslError {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        match self {
173            DslError::Empty => write!(f, "request is empty"),
174            DslError::TooManyOps { count, max } => {
175                write!(f, "batch has {count} ops; max is {max}")
176            }
177            DslError::UnexpectedChar {
178                pos,
179                found,
180                expected,
181            } => {
182                write!(f, "at position {pos}: expected {expected}, found {found:?}")
183            }
184            DslError::UnexpectedEof { expected } => {
185                write!(f, "unexpected end of input; expected {expected}")
186            }
187            DslError::InvalidIdentifier { pos } => {
188                write!(
189                    f,
190                    "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
191                )
192            }
193            DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
194            DslError::InvalidValue { pos, error } => {
195                write!(f, "at position {pos}: invalid value: {error}")
196            }
197            DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
198            DslError::UnclosedString => write!(f, "unterminated string literal"),
199            DslError::UnclosedBracket { kind } => {
200                write!(f, "unclosed bracket: {kind:?} has no matching close")
201            }
202            DslError::PrevRefOutsideChain { pos } => {
203                write!(
204                    f,
205                    "at position {pos}: $prev reference is only valid in chain (|) mode"
206                )
207            }
208            DslError::MixedSeparators => {
209                write!(
210                    f,
211                    "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
212                )
213            }
214        }
215    }
216}
217
218impl std::error::Error for DslError {}
219
220/// Parse a request input string, returning either a single op or a batch.
221pub fn parse_request(input: &str) -> Result<ParsedRequest, DslError> {
222    let trimmed = input.trim();
223    if trimmed.is_empty() {
224        return Err(DslError::Empty);
225    }
226
227    // JSON form: `[{...}, ...]` or `{...}`. After `[`, JSON whitespace is legal
228    // before the first element — common when pretty-printers emit `[ {...} ]`.
229    let first = trimmed.as_bytes()[0];
230    let looks_like_json = first == b'{'
231        || (first == b'['
232            && trimmed
233                .as_bytes()
234                .iter()
235                .skip(1)
236                .find(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
237                .is_some_and(|b| *b == b'{'));
238    if looks_like_json {
239        return parse_json_form(trimmed);
240    }
241
242    // Function-call batch `[...]` — parallel.
243    if first == b'[' {
244        return parse_fn_batch(trimmed);
245    }
246
247    // Chain or single: starts with an identifier.
248    // Parse the first op, then check for `|` to detect chain mode.
249    let mut p = Parser::new(trimmed);
250    let first_op = p.parse_op()?;
251    p.skip_ws();
252
253    if p.eof() {
254        // Single op — no separator follows.
255        return Ok(ParsedRequest {
256            ops: vec![first_op],
257            mode: ExecutionMode::Single,
258        });
259    }
260
261    if p.peek() == Some('|') {
262        // Chain mode: `op1 | op2 | ...`
263        return parse_chain_tail(p, first_op);
264    }
265
266    // Unexpected trailing content after a single op.
267    Err(DslError::UnexpectedChar {
268        pos: p.pos,
269        found: p.peek().unwrap(),
270        expected: "'|' or end of input",
271    })
272}
273
274/// Parse the rest of a chain after the first op has been consumed.
275///
276/// Called when we've seen `first_op` followed by `|`. Parses one or more
277/// `| op` segments and returns a `Chain` request.
278fn parse_chain_tail(mut p: Parser<'_>, first_op: ParsedOp) -> Result<ParsedRequest, DslError> {
279    let mut ops = vec![first_op];
280    while p.peek() == Some('|') {
281        if ops.len() >= MAX_OPS {
282            return Err(DslError::TooManyOps {
283                count: ops.len() + 1,
284                max: MAX_OPS,
285            });
286        }
287        p.advance(1); // consume '|'
288        p.skip_ws();
289        let op = p.parse_op()?;
290        ops.push(op);
291        p.skip_ws();
292    }
293    if !p.eof() {
294        return Err(DslError::UnexpectedChar {
295            pos: p.pos,
296            found: p.peek().unwrap(),
297            expected: "'|' or end of input",
298        });
299    }
300    Ok(ParsedRequest {
301        ops,
302        mode: ExecutionMode::Chain,
303    })
304}
305
306fn parse_json_form(input: &str) -> Result<ParsedRequest, DslError> {
307    let v: Value = serde_json::from_str(input).map_err(|e| DslError::InvalidJson {
308        error: e.to_string(),
309    })?;
310    let (arr, is_single) = match v {
311        Value::Array(arr) => (arr, false),
312        Value::Object(_) => (vec![v], true),
313        other => {
314            return Err(DslError::InvalidJson {
315                error: format!("expected object or array of objects, got {other}"),
316            })
317        }
318    };
319    if arr.len() > MAX_OPS {
320        return Err(DslError::TooManyOps {
321            count: arr.len(),
322            max: MAX_OPS,
323        });
324    }
325    let mut ops = Vec::with_capacity(arr.len());
326    for entry in arr {
327        let obj = entry.as_object().ok_or_else(|| DslError::InvalidJson {
328            error: "each batch entry must be an object".into(),
329        })?;
330        let tool = obj
331            .get("tool")
332            .and_then(Value::as_str)
333            .ok_or_else(|| DslError::InvalidJson {
334                error: "each entry needs a \"tool\" string".into(),
335            })?
336            .to_owned();
337        let args = obj
338            .get("args")
339            .cloned()
340            .unwrap_or_else(|| Value::Object(Map::new()));
341        let args_map = match args {
342            Value::Object(m) => m,
343            other => {
344                return Err(DslError::InvalidJson {
345                    error: format!("\"args\" must be an object, got {other}"),
346                })
347            }
348        };
349        // JSON form does not support $prev references — all args are Values.
350        let args: BTreeMap<String, ArgValue> = args_map
351            .into_iter()
352            .map(|(k, v)| (k, ArgValue::Value(v)))
353            .collect();
354        ops.push(ParsedOp { tool, args });
355    }
356    let mode = if is_single {
357        ExecutionMode::Single
358    } else {
359        ExecutionMode::Parallel
360    };
361    Ok(ParsedRequest { ops, mode })
362}
363
364fn parse_fn_batch(input: &str) -> Result<ParsedRequest, DslError> {
365    let mut p = Parser::new(input);
366    p.expect_char('[')?;
367    p.skip_ws();
368    let mut ops = Vec::new();
369    if p.peek() == Some(']') {
370        p.advance(1);
371        return Ok(ParsedRequest {
372            ops,
373            mode: ExecutionMode::Parallel,
374        });
375    }
376    loop {
377        if ops.len() >= MAX_OPS {
378            return Err(DslError::TooManyOps {
379                count: ops.len() + 1,
380                max: MAX_OPS,
381            });
382        }
383        let op = p.parse_op()?;
384        ops.push(op);
385        p.skip_ws();
386        match p.peek() {
387            Some(',') => {
388                p.advance(1);
389                p.skip_ws();
390            }
391            Some(']') => {
392                p.advance(1);
393                break;
394            }
395            Some(c) => {
396                return Err(DslError::UnexpectedChar {
397                    pos: p.pos,
398                    found: c,
399                    expected: "',' or ']'",
400                });
401            }
402            None => return Err(DslError::UnexpectedEof { expected: "']'" }),
403        }
404    }
405    p.skip_ws();
406    if !p.eof() {
407        return Err(DslError::UnexpectedChar {
408            pos: p.pos,
409            found: p.peek().unwrap(),
410            expected: "end of input",
411        });
412    }
413    Ok(ParsedRequest {
414        ops,
415        mode: ExecutionMode::Parallel,
416    })
417}
418
419// ── recursive-descent parser ────────────────────────────────────────────────
420
421struct Parser<'a> {
422    src: &'a [u8],
423    pos: usize,
424}
425
426impl<'a> Parser<'a> {
427    fn new(src: &'a str) -> Self {
428        Self {
429            src: src.as_bytes(),
430            pos: 0,
431        }
432    }
433
434    fn eof(&self) -> bool {
435        self.pos >= self.src.len()
436    }
437
438    fn peek(&self) -> Option<char> {
439        self.src.get(self.pos).map(|b| *b as char)
440    }
441
442    fn advance(&mut self, n: usize) {
443        self.pos = (self.pos + n).min(self.src.len());
444    }
445
446    fn skip_ws(&mut self) {
447        while let Some(c) = self.peek() {
448            if c.is_ascii_whitespace() {
449                self.advance(1);
450            } else {
451                break;
452            }
453        }
454    }
455
456    fn expect_char(&mut self, want: char) -> Result<(), DslError> {
457        self.skip_ws();
458        match self.peek() {
459            Some(c) if c == want => {
460                self.advance(1);
461                Ok(())
462            }
463            Some(c) => Err(DslError::UnexpectedChar {
464                pos: self.pos,
465                found: c,
466                expected: char_label(want),
467            }),
468            None => Err(DslError::UnexpectedEof {
469                expected: char_label(want),
470            }),
471        }
472    }
473
474    fn parse_identifier(&mut self) -> Result<String, DslError> {
475        self.skip_ws();
476        let start = self.pos;
477        match self.peek() {
478            Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
479            _ => return Err(DslError::InvalidIdentifier { pos: self.pos }),
480        }
481        while let Some(c) = self.peek() {
482            if c.is_ascii_alphanumeric() || c == '_' {
483                self.advance(1);
484            } else {
485                break;
486            }
487        }
488        Ok(std::str::from_utf8(&self.src[start..self.pos])
489            .expect("ascii-only chunk")
490            .to_owned())
491    }
492
493    fn parse_op(&mut self) -> Result<ParsedOp, DslError> {
494        let mut tool = self.parse_identifier()?;
495        // One-level dotted verbs: brain.state, recall.candidates
496        if self.peek() == Some('.') {
497            self.advance(1);
498            let sub = self.parse_identifier()?;
499            tool = format!("{tool}.{sub}");
500        }
501        self.expect_char('(')?;
502        self.skip_ws();
503        let mut args: BTreeMap<String, ArgValue> = BTreeMap::new();
504        if self.peek() == Some(')') {
505            self.advance(1);
506            return Ok(ParsedOp { tool, args });
507        }
508        loop {
509            let name = self.parse_identifier()?;
510            self.expect_char('=')?;
511            self.skip_ws();
512            let arg_val = self.parse_arg_value()?;
513            if args.contains_key(&name) {
514                return Err(DslError::DuplicateArg { name });
515            }
516            args.insert(name, arg_val);
517            self.skip_ws();
518            match self.peek() {
519                Some(',') => {
520                    self.advance(1);
521                    self.skip_ws();
522                }
523                Some(')') => {
524                    self.advance(1);
525                    return Ok(ParsedOp { tool, args });
526                }
527                Some(c) => {
528                    return Err(DslError::UnexpectedChar {
529                        pos: self.pos,
530                        found: c,
531                        expected: "',' or ')'",
532                    });
533                }
534                None => return Err(DslError::UnexpectedEof { expected: "')'" }),
535            }
536        }
537    }
538
539    /// Parse an argument value — either a `$prev` reference or a JSON literal.
540    fn parse_arg_value(&mut self) -> Result<ArgValue, DslError> {
541        self.skip_ws();
542        if self.peek() == Some('$') {
543            return self.parse_prev_ref();
544        }
545        let v = self.parse_value()?;
546        Ok(ArgValue::Value(v))
547    }
548
549    /// Parse a `$prev` or `$prev.field.path` reference.
550    ///
551    /// Grammar: `$prev` optionally followed by `.identifier(.identifier)*`
552    fn parse_prev_ref(&mut self) -> Result<ArgValue, DslError> {
553        let start = self.pos;
554        // Consume `$`
555        self.advance(1);
556        // Must be followed by `prev`
557        let ident = self
558            .parse_identifier()
559            .map_err(|_| DslError::InvalidValue {
560                pos: start,
561                error: "expected '$prev' — '$' must be followed by 'prev'".into(),
562            })?;
563        if ident != "prev" {
564            return Err(DslError::InvalidValue {
565                pos: start,
566                error: format!("expected '$prev', found '${}'", ident),
567            });
568        }
569        // Optional dot-path
570        let mut path = String::new();
571        while self.peek() == Some('.') {
572            self.advance(1); // consume '.'
573            let segment = self.parse_identifier()?;
574            if !path.is_empty() {
575                path.push('.');
576            }
577            path.push_str(&segment);
578        }
579        Ok(ArgValue::PrevRef { path })
580    }
581
582    fn parse_value(&mut self) -> Result<Value, DslError> {
583        self.skip_ws();
584        let start = self.pos;
585        let end = self.scan_value_end()?;
586        let slice = std::str::from_utf8(&self.src[start..end])
587            .expect("ascii-or-utf8 maintained by scanner");
588        let value: Value =
589            serde_json::from_str(slice.trim()).map_err(|e| DslError::InvalidValue {
590                pos: start,
591                error: e.to_string(),
592            })?;
593        self.pos = end;
594        Ok(value)
595    }
596
597    /// Walk forward through the input to find the end of a JSON value, respecting
598    /// nested brackets / braces and string literals. The returned index is one
599    /// past the last byte of the value (exclusive).
600    fn scan_value_end(&self) -> Result<usize, DslError> {
601        let mut i = self.pos;
602        let mut depth_paren: i32 = 0; // `(` from the surrounding op
603        let mut depth_brack: i32 = 0;
604        let mut depth_brace: i32 = 0;
605        while i < self.src.len() {
606            let c = self.src[i] as char;
607            match c {
608                '"' => {
609                    i = scan_string_end(self.src, i)?;
610                    continue;
611                }
612                '[' => depth_brack += 1,
613                ']' => {
614                    if depth_brack == 0 {
615                        if depth_paren == 0 && depth_brace == 0 {
616                            return Ok(i);
617                        }
618                        // we never opened a paren here; this terminates the value.
619                        return Ok(i);
620                    }
621                    depth_brack -= 1;
622                }
623                '{' => depth_brace += 1,
624                '}' => {
625                    if depth_brace == 0 {
626                        return Err(DslError::UnclosedBracket { kind: '{' });
627                    }
628                    depth_brace -= 1;
629                }
630                '(' => depth_paren += 1,
631                ')' => {
632                    if depth_paren == 0 && depth_brack == 0 && depth_brace == 0 {
633                        return Ok(i);
634                    }
635                    if depth_paren == 0 {
636                        return Err(DslError::UnclosedBracket { kind: '(' });
637                    }
638                    depth_paren -= 1;
639                }
640                ',' => {
641                    if depth_paren == 0 && depth_brack == 0 && depth_brace == 0 {
642                        return Ok(i);
643                    }
644                }
645                _ => {}
646            }
647            i += 1;
648        }
649        if depth_brack > 0 {
650            return Err(DslError::UnclosedBracket { kind: '[' });
651        }
652        if depth_brace > 0 {
653            return Err(DslError::UnclosedBracket { kind: '{' });
654        }
655        Ok(i)
656    }
657}
658
659fn scan_string_end(src: &[u8], start: usize) -> Result<usize, DslError> {
660    let mut i = start + 1;
661    while i < src.len() {
662        match src[i] as char {
663            '\\' => {
664                i += 2; // skip escape pair
665                continue;
666            }
667            '"' => return Ok(i + 1),
668            _ => i += 1,
669        }
670    }
671    Err(DslError::UnclosedString)
672}
673
674fn char_label(c: char) -> &'static str {
675    match c {
676        '(' => "'('",
677        ')' => "')'",
678        '[' => "'['",
679        ']' => "']'",
680        '=' => "'='",
681        ',' => "','",
682        _ => "expected char",
683    }
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689    use serde_json::json;
690
691    fn req(s: &str) -> ParsedRequest {
692        parse_request(s).unwrap_or_else(|e| panic!("parse({s:?}) failed: {e}"))
693    }
694
695    fn ops(s: &str) -> Vec<ParsedOp> {
696        req(s).ops
697    }
698
699    /// Extract the concrete `Value` from an `ArgValue::Value`, panicking on `PrevRef`.
700    fn val(arg: &ArgValue) -> &Value {
701        match arg {
702            ArgValue::Value(v) => v,
703            ArgValue::PrevRef { path } => {
704                panic!("expected Value, got PrevRef {{ path: {path:?} }}")
705            }
706        }
707    }
708
709    #[test]
710    fn single_op_no_args() {
711        let r = req("next()");
712        assert_eq!(r.mode, ExecutionMode::Single);
713        assert_eq!(r.ops.len(), 1);
714        assert_eq!(r.ops[0].tool, "next");
715        assert!(r.ops[0].args.is_empty());
716    }
717
718    #[test]
719    fn single_op_with_string_arg() {
720        let v = ops(r#"assign(title="ship release")"#);
721        assert_eq!(v[0].tool, "assign");
722        assert_eq!(val(&v[0].args["title"]), &json!("ship release"));
723    }
724
725    #[test]
726    fn single_op_with_multiple_typed_args() {
727        let v = ops(
728            r#"create(kind="entity", entity_kind="concept", name="LoRA", weight=0.9, active=true)"#,
729        );
730        assert_eq!(v[0].tool, "create");
731        assert_eq!(val(&v[0].args["kind"]), &json!("entity"));
732        assert_eq!(val(&v[0].args["weight"]), &json!(0.9));
733        assert_eq!(val(&v[0].args["active"]), &json!(true));
734    }
735
736    #[test]
737    fn batch_three_ops() {
738        let r = req(
739            r#"[create(kind="entity", name="A"), create(kind="entity", name="B"), link(source_id="x", target_id="y", relation="extends")]"#,
740        );
741        assert_eq!(r.mode, ExecutionMode::Parallel);
742        assert_eq!(r.ops.len(), 3);
743        assert_eq!(r.ops[0].tool, "create");
744        assert_eq!(r.ops[2].tool, "link");
745        assert_eq!(val(&r.ops[2].args["relation"]), &json!("extends"));
746    }
747
748    #[test]
749    fn empty_batch_is_legal() {
750        let r = req("[]");
751        assert_eq!(r.mode, ExecutionMode::Parallel);
752        assert!(r.ops.is_empty());
753    }
754
755    #[test]
756    fn nested_array_and_object_values() {
757        let v = ops(r#"assign(title="x", tags=["a","b"], properties={"k":"v","n":1})"#);
758        assert_eq!(val(&v[0].args["tags"]), &json!(["a", "b"]));
759        assert_eq!(val(&v[0].args["properties"]), &json!({"k": "v", "n": 1}));
760    }
761
762    #[test]
763    fn string_with_comma_and_paren_inside() {
764        let v = ops(r#"assign(title="hello, world (now)")"#);
765        assert_eq!(val(&v[0].args["title"]), &json!("hello, world (now)"));
766    }
767
768    #[test]
769    fn string_with_escaped_quote() {
770        let v = ops(r#"assign(title="he said \"hi\"")"#);
771        assert_eq!(val(&v[0].args["title"]), &json!("he said \"hi\""));
772    }
773
774    #[test]
775    fn null_and_negative_number() {
776        let v = ops(r#"update(id="x", description=null, weight=-0.5)"#);
777        assert_eq!(val(&v[0].args["description"]), &json!(null));
778        assert_eq!(val(&v[0].args["weight"]), &json!(-0.5));
779    }
780
781    #[test]
782    fn json_form_batch_parses() {
783        let r = req(r#"[{"tool":"next","args":{}}, {"tool":"complete","args":{"id":"abc"}}]"#);
784        assert_eq!(r.mode, ExecutionMode::Parallel);
785        assert_eq!(r.ops.len(), 2);
786        assert_eq!(r.ops[1].tool, "complete");
787        assert_eq!(val(&r.ops[1].args["id"]), &json!("abc"));
788    }
789
790    #[test]
791    fn json_form_with_leading_whitespace_inside_array_parses() {
792        // Pretty-printers commonly emit `[ {...} ]` with spaces or newlines after `[`.
793        // The whitespace is legal JSON, so the parser must route this to the JSON
794        // path rather than the function-call batch parser.
795        let v = ops(r#"[  {"tool":"next","args":{}} ]"#);
796        assert_eq!(v.len(), 1);
797        assert_eq!(v[0].tool, "next");
798
799        let v = ops("[\n  {\"tool\":\"next\",\"args\":{}},\n  {\"tool\":\"complete\",\"args\":{\"id\":\"x\"}}\n]");
800        assert_eq!(v.len(), 2);
801        assert_eq!(v[1].tool, "complete");
802    }
803
804    #[test]
805    fn json_form_single_object_is_treated_as_one_op() {
806        let r = req(r#"{"tool":"next","args":{}}"#);
807        assert_eq!(r.mode, ExecutionMode::Single);
808        assert_eq!(r.ops.len(), 1);
809        assert_eq!(r.ops[0].tool, "next");
810    }
811
812    #[test]
813    fn duplicate_arg_rejected() {
814        let err = parse_request(r#"assign(title="a", title="b")"#).unwrap_err();
815        assert!(matches!(err, DslError::DuplicateArg { ref name } if name == "title"));
816    }
817
818    #[test]
819    fn unknown_token_after_op_rejected() {
820        let err = parse_request(r#"next() garbage"#).unwrap_err();
821        assert!(matches!(err, DslError::UnexpectedChar { .. }));
822    }
823
824    #[test]
825    fn unclosed_paren_rejected() {
826        let err = parse_request(r#"assign(title="a""#).unwrap_err();
827        // The string is closed; the args list isn't.
828        assert!(matches!(err, DslError::UnexpectedEof { .. }));
829    }
830
831    #[test]
832    fn unterminated_string_rejected() {
833        let err = parse_request(r#"assign(title="oops)"#).unwrap_err();
834        assert!(matches!(err, DslError::UnclosedString));
835    }
836
837    #[test]
838    fn too_many_ops_rejected() {
839        let one = r#"next(),"#;
840        let mut s = String::from("[");
841        for _ in 0..MAX_OPS + 1 {
842            s.push_str(one);
843        }
844        s.push_str("next()]");
845        let err = parse_request(&s).unwrap_err();
846        assert!(matches!(err, DslError::TooManyOps { .. }));
847    }
848
849    #[test]
850    fn empty_request_rejected() {
851        let err = parse_request("   ").unwrap_err();
852        assert!(matches!(err, DslError::Empty));
853    }
854
855    // ── Required prompt examples ───────────────────────────────────────────────
856
857    #[test]
858    fn recall_with_query_arg() {
859        let v = ops(r#"recall(query="test")"#);
860        assert_eq!(v.len(), 1);
861        assert_eq!(v[0].tool, "recall");
862        assert_eq!(val(&v[0].args["query"]), &json!("test"));
863    }
864
865    #[test]
866    fn search_with_query_and_limit() {
867        let v = ops(r#"search(query="test", limit=5)"#);
868        assert_eq!(v.len(), 1);
869        assert_eq!(v[0].tool, "search");
870        assert_eq!(val(&v[0].args["query"]), &json!("test"));
871        assert_eq!(val(&v[0].args["limit"]), &json!(5));
872    }
873
874    #[test]
875    fn parallel_recall_and_inbox() {
876        let r = req(r#"[recall(query="x"), inbox()]"#);
877        assert_eq!(r.mode, ExecutionMode::Parallel);
878        assert_eq!(r.ops.len(), 2);
879        assert_eq!(r.ops[0].tool, "recall");
880        assert_eq!(val(&r.ops[0].args["query"]), &json!("x"));
881        assert_eq!(r.ops[1].tool, "inbox");
882        assert!(r.ops[1].args.is_empty());
883    }
884
885    // ── JSON form edge cases ───────────────────────────────────────────────────
886
887    #[test]
888    fn json_missing_args_defaults_to_empty_map() {
889        let v = ops(r#"{"tool":"inbox"}"#);
890        assert_eq!(v.len(), 1);
891        assert_eq!(v[0].tool, "inbox");
892        assert!(v[0].args.is_empty());
893    }
894
895    #[test]
896    fn json_args_as_array_rejected() {
897        let err = parse_request(r#"{"tool":"x","args":[]}"#).unwrap_err();
898        assert!(matches!(err, DslError::InvalidJson { .. }));
899    }
900
901    // ── Identifier grammar ────────────────────────────────────────────────────
902
903    #[test]
904    fn dotted_tool_name_parsed() {
905        let v = ops("brain.state()");
906        assert_eq!(v[0].tool, "brain.state");
907        assert!(v[0].args.is_empty());
908    }
909
910    #[test]
911    fn dotted_tool_with_args() {
912        let v = ops(r#"recall.candidates(query="test", limit=5)"#);
913        assert_eq!(v[0].tool, "recall.candidates");
914        assert_eq!(val(&v[0].args["query"]), &json!("test"));
915        assert_eq!(val(&v[0].args["limit"]), &json!(5));
916    }
917
918    #[test]
919    fn dotted_tool_in_batch() {
920        let v = ops(r#"[brain.state(), recall.fuse(query="x")]"#);
921        assert_eq!(v.len(), 2);
922        assert_eq!(v[0].tool, "brain.state");
923        assert_eq!(v[1].tool, "recall.fuse");
924    }
925
926    #[test]
927    fn leading_underscore_identifier_is_valid() {
928        let v = ops("_internal()");
929        assert_eq!(v[0].tool, "_internal");
930        assert!(v[0].args.is_empty());
931    }
932
933    #[test]
934    fn identifier_starting_with_digit_rejected() {
935        let err = parse_request("1bad()").unwrap_err();
936        assert!(matches!(err, DslError::InvalidIdentifier { pos: 0 }));
937    }
938
939    // ── Argument value edge cases ─────────────────────────────────────────────
940
941    #[test]
942    fn boolean_false_as_arg_value() {
943        let v = ops("flag(active=false)");
944        assert_eq!(val(&v[0].args["active"]), &json!(false));
945    }
946
947    #[test]
948    fn unicode_string_arg_preserved() {
949        let v = ops(r#"assign(title="café")"#);
950        assert_eq!(val(&v[0].args["title"]), &json!("café"));
951    }
952
953    // ── Chain mode (ADR-016) ──────────────────────────────────────────────────
954
955    #[test]
956    fn chain_two_ops_with_prev_ref() {
957        let r = req(
958            r#"create(kind="entity", entity_kind="concept", name="A") | link(source_id=$prev.id, target_id="abc", relation="extends")"#,
959        );
960        assert_eq!(r.mode, ExecutionMode::Chain);
961        assert_eq!(r.ops.len(), 2);
962        assert_eq!(r.ops[0].tool, "create");
963        assert_eq!(r.ops[1].tool, "link");
964        // The second op's source_id should be a PrevRef
965        assert_eq!(
966            r.ops[1].args["source_id"],
967            ArgValue::PrevRef { path: "id".into() }
968        );
969        // target_id is a concrete value
970        assert_eq!(val(&r.ops[1].args["target_id"]), &json!("abc"));
971    }
972
973    #[test]
974    fn chain_three_ops_mode() {
975        let r = req(
976            r#"create(kind="entity", name="A") | link(source_id=$prev.id, target_id="b", relation="extends") | update(id=$prev.id, description="desc")"#,
977        );
978        assert_eq!(r.mode, ExecutionMode::Chain);
979        assert_eq!(r.ops.len(), 3);
980        assert_eq!(r.ops[2].args["id"], ArgValue::PrevRef { path: "id".into() });
981    }
982
983    #[test]
984    fn chain_prev_no_field_selector() {
985        // $prev alone (no dot path) refers to the whole prior result.
986        let r = req(r#"next() | update(id=$prev)"#);
987        assert_eq!(r.mode, ExecutionMode::Chain);
988        assert_eq!(r.ops[1].args["id"], ArgValue::PrevRef { path: "".into() });
989    }
990
991    #[test]
992    fn chain_prev_deep_path() {
993        let r = req(
994            r#"create(kind="entity", name="A") | link(source_id=$prev.result.id, target_id="b", relation="extends")"#,
995        );
996        assert_eq!(r.mode, ExecutionMode::Chain);
997        assert_eq!(
998            r.ops[1].args["source_id"],
999            ArgValue::PrevRef {
1000                path: "result.id".into()
1001            }
1002        );
1003    }
1004
1005    #[test]
1006    fn single_op_mode() {
1007        let r = req("next()");
1008        assert_eq!(r.mode, ExecutionMode::Single);
1009    }
1010
1011    #[test]
1012    fn chain_too_many_ops_rejected() {
1013        let mut s = String::from("next()");
1014        for _ in 0..MAX_OPS {
1015            s.push_str(" | next()");
1016        }
1017        let err = parse_request(&s).unwrap_err();
1018        assert!(matches!(err, DslError::TooManyOps { .. }));
1019    }
1020
1021    // ── ArgValue helpers ──────────────────────────────────────────────────────
1022
1023    #[test]
1024    fn arg_value_resolve_prev_simple() {
1025        let prev = json!({"id": "abc-123", "name": "A"});
1026        let r = ArgValue::PrevRef { path: "id".into() };
1027        assert_eq!(r.resolve_prev(&prev), Some(&json!("abc-123")));
1028    }
1029
1030    #[test]
1031    fn arg_value_resolve_prev_empty_path() {
1032        let prev = json!({"id": "x"});
1033        let r = ArgValue::PrevRef { path: "".into() };
1034        assert_eq!(r.resolve_prev(&prev), Some(&prev));
1035    }
1036
1037    #[test]
1038    fn arg_value_resolve_prev_nested_path() {
1039        let prev = json!({"result": {"id": "nested-id"}});
1040        let r = ArgValue::PrevRef {
1041            path: "result.id".into(),
1042        };
1043        assert_eq!(r.resolve_prev(&prev), Some(&json!("nested-id")));
1044    }
1045
1046    #[test]
1047    fn arg_value_resolve_prev_missing_field_returns_none() {
1048        let prev = json!({"id": "x"});
1049        let r = ArgValue::PrevRef {
1050            path: "nonexistent".into(),
1051        };
1052        assert_eq!(r.resolve_prev(&prev), None);
1053    }
1054
1055    #[test]
1056    fn arg_value_value_returns_none_for_resolve_prev() {
1057        let r = ArgValue::Value(json!("hello"));
1058        assert_eq!(r.resolve_prev(&json!({})), None);
1059    }
1060}