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///
62/// `$prev` references may also appear inside array or object literals, which is
63/// why `Array` and `Object` variants exist alongside the flat `PrevRef` variant.
64/// The dispatcher resolves these recursively before calling the verb handler.
65#[derive(Debug, Clone, PartialEq)]
66pub enum ArgValue {
67    /// A concrete JSON value (no `$prev` references anywhere inside).
68    Value(Value),
69    /// A `$prev` or `$prev.field.path` reference — chain mode only.
70    ///
71    /// `path` is the dot-separated field path after `$prev`. Empty string means
72    /// the whole prior result (`$prev` with no field selector).
73    PrevRef { path: String },
74    /// An array literal whose elements may themselves be `ArgValue`s (including
75    /// nested `PrevRef` or further `Array`/`Object`).  Used when at least one
76    /// element contains a `$prev` reference; pure-JSON arrays are still
77    /// represented as `Value(Value::Array(_))` for efficiency.
78    Array(Vec<ArgValue>),
79    /// An object literal whose values may themselves be `ArgValue`s.  Used when
80    /// at least one value contains a `$prev` reference; pure-JSON objects are
81    /// still represented as `Value(Value::Object(_))`.
82    Object(Vec<(String, ArgValue)>),
83}
84
85impl ArgValue {
86    /// Returns the contained [`Value`] if this is `ArgValue::Value`.
87    pub fn as_value(&self) -> Option<&Value> {
88        match self {
89            ArgValue::Value(v) => Some(v),
90            ArgValue::PrevRef { .. } | ArgValue::Array(_) | ArgValue::Object(_) => None,
91        }
92    }
93
94    /// Returns `true` if this is a `$prev` reference.
95    pub fn is_prev_ref(&self) -> bool {
96        matches!(self, ArgValue::PrevRef { .. })
97    }
98
99    /// Resolve a `$prev` reference against a preceding op's result.
100    ///
101    /// Returns the extracted field value, or `None` if the path doesn't
102    /// exist in `prev_result`. Non-`PrevRef` variants return `None`.
103    ///
104    /// Path segments may include array indices: `$prev.items[0].id` or
105    /// `$prev[0].name`. Bracket indices are parsed as `usize` (ue-dsl-chain H1).
106    pub fn resolve_prev<'a>(&self, prev_result: &'a Value) -> Option<&'a Value> {
107        let ArgValue::PrevRef { path } = self else {
108            return None;
109        };
110        if path.is_empty() {
111            return Some(prev_result);
112        }
113        let mut cur = prev_result;
114        for segment in split_path(path) {
115            cur = apply_path_segment(cur, segment)?;
116        }
117        Some(cur)
118    }
119
120    /// Recursively resolve all `$prev` references within this value.
121    ///
122    /// - `PrevRef`: resolved via `resolve_prev`.
123    /// - `Array`/`Object`: each element/value is resolved recursively.
124    /// - `Value`: returned as-is (no `$prev` anywhere inside).
125    ///
126    /// Returns `None` if any `$prev` path is missing from `prev_result`.
127    pub fn resolve_all<'a>(&'a self, prev_result: &'a Value) -> Option<Value> {
128        match self {
129            ArgValue::Value(v) => Some(v.clone()),
130            ArgValue::PrevRef { .. } => self.resolve_prev(prev_result).cloned(),
131            ArgValue::Array(elements) => {
132                let mut out = Vec::with_capacity(elements.len());
133                for el in elements {
134                    out.push(el.resolve_all(prev_result)?);
135                }
136                Some(Value::Array(out))
137            }
138            ArgValue::Object(pairs) => {
139                let mut map = serde_json::Map::with_capacity(pairs.len());
140                for (key, val) in pairs {
141                    map.insert(key.clone(), val.resolve_all(prev_result)?);
142                }
143                Some(Value::Object(map))
144            }
145        }
146    }
147}
148
149/// A single parsed operation: tool name + named argument bag.
150///
151/// Arguments may be concrete [`ArgValue::Value`]s or `$prev` references
152/// ([`ArgValue::PrevRef`]) that the dispatcher resolves against the prior op's
153/// result (chain mode only).
154#[derive(Debug, Clone, PartialEq)]
155pub struct ParsedOp {
156    pub tool: String,
157    pub args: BTreeMap<String, ArgValue>,
158}
159
160/// Result of parsing a `request` input string (ADR-016).
161///
162/// The `mode` field tells the dispatcher how to execute the operations:
163/// - `Single`: dispatch the one op, wrap in a single-element envelope.
164/// - `Parallel`: dispatch all ops concurrently via `join_all`, collect in order.
165/// - `Chain`: dispatch ops sequentially; substitute `$prev` references between
166///   ops; abort remaining ops when any op or substitution fails.
167#[derive(Debug, Clone, PartialEq)]
168pub struct ParsedRequest {
169    pub ops: Vec<ParsedOp>,
170    pub mode: ExecutionMode,
171}
172
173/// Parser error — surfaced as `invalid_params` at the MCP boundary.
174#[derive(Debug, Clone, PartialEq)]
175pub enum DslError {
176    Empty,
177    TooManyOps {
178        count: usize,
179        max: usize,
180    },
181    UnexpectedChar {
182        pos: usize,
183        found: char,
184        expected: &'static str,
185    },
186    UnexpectedEof {
187        expected: &'static str,
188    },
189    InvalidIdentifier {
190        pos: usize,
191    },
192    DuplicateArg {
193        name: String,
194    },
195    InvalidValue {
196        pos: usize,
197        error: String,
198    },
199    InvalidJson {
200        error: String,
201    },
202    UnclosedString,
203    UnclosedBracket {
204        kind: char,
205    },
206    /// `$prev` reference used outside a chain context (emitted by the parser for
207    /// Single-op and Parallel-batch forms, and for JSON form).
208    ///
209    /// # Policy
210    ///
211    /// `$prev` references are only meaningful in chain (`|`) mode. If they appear
212    /// in a non-chain context the parser rejects the request here so downstream
213    /// consumers that pattern-match on `DslError` get a typed error rather than
214    /// a runtime string.
215    PrevRefOutsideChain {
216        pos: usize,
217    },
218    /// `$prev` found in JSON-form input — JSON form does not support chains.
219    ///
220    /// JSON form (`[{"tool":"...","args":{...}},...]`) always runs in parallel.
221    /// To use `$prev` substitution, use the function-call DSL with the `|` chain
222    /// operator: `verb1(...) | verb2(id=$prev.id)`.
223    PrevRefInJsonForm {
224        arg_name: String,
225    },
226    /// Mixing `,` and `|` at the top level.
227    MixedSeparators,
228    /// Empty batch `[]` — no ops provided.
229    EmptyBatch,
230    /// Dotted verb name with more than one level (e.g. `a.b.c`). Only
231    /// single-level dotted names are supported (`a.b`).
232    UnsupportedVerbNesting {
233        pos: usize,
234    },
235    /// Two or more ops in a parallel batch write to the same UUID (ADR-038).
236    ///
237    /// Write-key conflict detection is a preflight check applied after parsing.
238    /// Write ops are: `update`, `delete`, `merge`, `link`. When two ops share the
239    /// same `id` (or `into_id` / `from_id` for `merge`, `source_id`/`target_id`
240    /// for `link`) the batch is rejected before any op is dispatched.
241    WriteKeyConflict {
242        /// The duplicated UUID.
243        id: String,
244        /// Name of the first op that claimed the key.
245        first_op: String,
246        /// Name of the second op that conflicts.
247        second_op: String,
248    },
249}
250
251impl fmt::Display for DslError {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        match self {
254            DslError::Empty => write!(f, "request is empty"),
255            DslError::TooManyOps { count, max } => {
256                write!(f, "batch has {count} ops; max is {max}")
257            }
258            DslError::UnexpectedChar {
259                pos,
260                found,
261                expected,
262            } => {
263                write!(f, "at position {pos}: expected {expected}, found {found:?}")
264            }
265            DslError::UnexpectedEof { expected } => {
266                write!(f, "unexpected end of input; expected {expected}")
267            }
268            DslError::InvalidIdentifier { pos } => {
269                write!(
270                    f,
271                    "at position {pos}: invalid identifier (expected [A-Za-z_][A-Za-z0-9_]*)"
272                )
273            }
274            DslError::DuplicateArg { name } => write!(f, "duplicate argument {name:?}"),
275            DslError::InvalidValue { pos, error } => {
276                write!(f, "at position {pos}: invalid value: {error}")
277            }
278            DslError::InvalidJson { error } => write!(f, "invalid JSON form: {error}"),
279            DslError::UnclosedString => write!(f, "unterminated string literal"),
280            DslError::UnclosedBracket { kind } => {
281                write!(f, "unclosed bracket: {kind:?} has no matching close")
282            }
283            DslError::PrevRefOutsideChain { pos } => {
284                write!(
285                    f,
286                    "at position {pos}: $prev reference is only valid in chain (|) mode; \
287                     use function-call form with '|' to chain ops"
288                )
289            }
290            DslError::PrevRefInJsonForm { arg_name } => {
291                write!(
292                    f,
293                    "argument {arg_name:?}: $prev substitution requires the function-call DSL \
294                     with the chain (|) operator; JSON form does not support chains. \
295                     Use: verb1(...) | verb2({arg_name}=$prev.id)"
296                )
297            }
298            DslError::MixedSeparators => {
299                write!(
300                    f,
301                    "cannot mix ',' (parallel) and '|' (chain) separators at the top level"
302                )
303            }
304            DslError::EmptyBatch => {
305                write!(f, "empty batch not allowed; provide at least one op")
306            }
307            DslError::UnsupportedVerbNesting { pos } => {
308                write!(
309                    f,
310                    "at position {pos}: only single-level dotted verb names are supported \
311                     (e.g. brain.state); use a shorter name or register a pack alias"
312                )
313            }
314            DslError::WriteKeyConflict {
315                id,
316                first_op,
317                second_op,
318            } => {
319                write!(
320                    f,
321                    "write-key conflict: id {id:?} is targeted by both {first_op:?} and \
322                     {second_op:?} in the same batch; split into separate requests"
323                )
324            }
325        }
326    }
327}
328
329impl std::error::Error for DslError {}
330
331/// Check a parsed batch for write-key conflicts (ADR-038 preflight).
332///
333/// Write operations (`update`, `delete`, `merge`, `link`) target specific UUIDs.
334/// If two ops in the same parallel (or single-op) batch write to the same UUID,
335/// the batch is rejected before any op is dispatched.
336///
337/// Chain mode is excluded: sequential ops intentionally build on prior results
338/// and the runtime resolves `$prev` references between them.
339///
340/// The checked keys per verb:
341/// - `update` / `delete`: `id`
342/// - `merge`:             `into_id`, `from_id`
343/// - `link`:              `source_id`, `target_id`
344///
345/// Only concrete `ArgValue::Value(String)` arguments are checked; `$prev`
346/// references are skipped because their target is not known until dispatch time.
347pub fn check_write_key_conflicts(req: &ParsedRequest) -> Result<(), DslError> {
348    // Chain mode is sequentially ordered; skip conflict detection.
349    if req.mode == ExecutionMode::Chain {
350        return Ok(());
351    }
352    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
353    for op in &req.ops {
354        let keys = write_keys_for_op(op);
355        for key in keys {
356            if let Some(first) = seen.get(&key) {
357                return Err(DslError::WriteKeyConflict {
358                    id: key,
359                    first_op: first.clone(),
360                    second_op: op.tool.clone(),
361                });
362            }
363            seen.insert(key, op.tool.clone());
364        }
365    }
366    Ok(())
367}
368
369/// Extract write-conflict keys from a single op for preflight conflict detection (ADR-038).
370///
371/// Keys are substrate-prefixed to avoid false positives between different substrates:
372/// - Entity write ops (`update`, `delete`, `merge`): `entity:<uuid>`
373/// - Edge write ops (`link`): `edge-natural:<source_id>:<target_id>:<relation>`
374///   — `link` creates an edge record, NOT an entity write, so source/target entity
375///   IDs must NOT be used as entity-level keys.
376///
377/// Only concrete `ArgValue::Value(String)` args are checked; `$prev` refs are skipped.
378///
379/// # Why `create` is excluded
380///
381/// `create` generates its UUID server-side and the ID is not statically known at parse
382/// time, so there is no key to conflict on.  The existing DB-level serialization handles
383/// concurrent creates safely (unique constraint on the generated UUID).
384///
385/// This function is `pub` so the MCP server can call it directly without the full
386/// `check_write_key_conflicts` batch-level function.
387pub fn write_keys_for_op_pub(op: &ParsedOp) -> Vec<String> {
388    let mut keys = Vec::new();
389    match op.tool.as_str() {
390        "update" | "delete" => {
391            if let Some(ArgValue::Value(Value::String(s))) = op.args.get("id") {
392                keys.push(format!("entity:{s}"));
393            }
394        }
395        "merge" => {
396            for name in &["into_id", "from_id"] {
397                if let Some(ArgValue::Value(Value::String(s))) = op.args.get(*name) {
398                    keys.push(format!("entity:{s}"));
399                }
400            }
401        }
402        "link" => {
403            // `link` writes an edge, not an entity.  Use a natural-key format so
404            // update(id="X") + link(source_id="X", ...) do NOT conflict (they target
405            // different substrates).
406            let src = op.args.get("source_id");
407            let tgt = op.args.get("target_id");
408            let rel = op.args.get("relation");
409            if let (
410                Some(ArgValue::Value(Value::String(s))),
411                Some(ArgValue::Value(Value::String(t))),
412                Some(ArgValue::Value(Value::String(r))),
413            ) = (src, tgt, rel)
414            {
415                keys.push(format!("edge-natural:{s}:{t}:{r}"));
416            }
417        }
418        _ => {}
419    }
420    keys
421}
422
423/// Extract the write-key UUIDs from a single op (internal helper, kept for tests).
424fn write_keys_for_op(op: &ParsedOp) -> Vec<String> {
425    write_keys_for_op_pub(op)
426}
427
428/// Parse a request input string, returning either a single op or a batch.
429pub fn parse_request(input: &str) -> Result<ParsedRequest, DslError> {
430    let trimmed = input.trim();
431    if trimmed.is_empty() {
432        return Err(DslError::Empty);
433    }
434
435    // JSON form: `[{...}, ...]` or `{...}`. After `[`, JSON whitespace is legal
436    // before the first element — common when pretty-printers emit `[ {...} ]`.
437    let first = trimmed.as_bytes()[0];
438    let looks_like_json = first == b'{'
439        || (first == b'['
440            && trimmed
441                .as_bytes()
442                .iter()
443                .skip(1)
444                .find(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
445                .is_some_and(|b| *b == b'{'));
446    if looks_like_json {
447        return parse_json_form(trimmed);
448    }
449
450    // Function-call batch `[...]` — parallel.
451    if first == b'[' {
452        return parse_fn_batch(trimmed);
453    }
454
455    // Chain or single: starts with an identifier.
456    // Parse the first op, then check for `|` to detect chain mode.
457    let mut p = Parser::new(trimmed);
458    let first_op = p.parse_op()?;
459    p.skip_ws();
460
461    if p.eof() {
462        // Single op — no separator follows.
463        // PrevRef in a single op is always invalid (adr-dsl-packs H1).
464        if let Some(pos) = find_prev_ref_pos(&first_op) {
465            return Err(DslError::PrevRefOutsideChain { pos });
466        }
467        return Ok(ParsedRequest {
468            ops: vec![first_op],
469            mode: ExecutionMode::Single,
470        });
471    }
472
473    if p.peek() == Some('|') {
474        // Chain mode: `op1 | op2 | ...`
475        return parse_chain_tail(p, first_op);
476    }
477
478    // Unexpected trailing content after a single op.
479    Err(DslError::UnexpectedChar {
480        pos: p.pos,
481        found: p.peek().unwrap(),
482        expected: "'|' or end of input",
483    })
484}
485
486/// Parse the rest of a chain after the first op has been consumed.
487///
488/// Called when we've seen `first_op` followed by `|`. Parses one or more
489/// `| op` segments and returns a `Chain` request.
490fn parse_chain_tail(mut p: Parser<'_>, first_op: ParsedOp) -> Result<ParsedRequest, DslError> {
491    let mut ops = vec![first_op];
492    while p.peek() == Some('|') {
493        if ops.len() >= MAX_OPS {
494            return Err(DslError::TooManyOps {
495                count: ops.len() + 1,
496                max: MAX_OPS,
497            });
498        }
499        p.advance(1); // consume '|'
500        p.skip_ws();
501        let op = p.parse_op()?;
502        ops.push(op);
503        p.skip_ws();
504    }
505    if !p.eof() {
506        if p.peek() == Some(',') {
507            return Err(DslError::MixedSeparators);
508        }
509        return Err(DslError::UnexpectedChar {
510            pos: p.pos,
511            found: p.peek().unwrap(),
512            expected: "'|' or end of input",
513        });
514    }
515    Ok(ParsedRequest {
516        ops,
517        mode: ExecutionMode::Chain,
518    })
519}
520
521fn parse_json_form(input: &str) -> Result<ParsedRequest, DslError> {
522    let v: Value = serde_json::from_str(input).map_err(|e| DslError::InvalidJson {
523        error: e.to_string(),
524    })?;
525    let (arr, is_single) = match v {
526        Value::Array(arr) => (arr, false),
527        Value::Object(_) => (vec![v], true),
528        other => {
529            return Err(DslError::InvalidJson {
530                error: format!("expected object or array of objects, got {other}"),
531            })
532        }
533    };
534    if arr.is_empty() && !is_single {
535        return Err(DslError::EmptyBatch);
536    }
537    if arr.len() > MAX_OPS {
538        return Err(DslError::TooManyOps {
539            count: arr.len(),
540            max: MAX_OPS,
541        });
542    }
543    let mut ops = Vec::with_capacity(arr.len());
544    for entry in arr {
545        let obj = entry.as_object().ok_or_else(|| DslError::InvalidJson {
546            error: "each batch entry must be an object".into(),
547        })?;
548        let tool = obj
549            .get("tool")
550            .and_then(Value::as_str)
551            .ok_or_else(|| DslError::InvalidJson {
552                error: "each entry needs a \"tool\" string".into(),
553            })?
554            .to_owned();
555        let args = obj
556            .get("args")
557            .cloned()
558            .unwrap_or_else(|| Value::Object(Map::new()));
559        let args_map = match args {
560            Value::Object(m) => m,
561            other => {
562                return Err(DslError::InvalidJson {
563                    error: format!("\"args\" must be an object, got {other}"),
564                })
565            }
566        };
567        // JSON form does not support $prev references — all args are Values.
568        // Recursively scan every arg value (including nested arrays/objects) for
569        // any string matching $prev, $prev.*, or $prev[* and reject with a typed
570        // PrevRefInJsonForm error (ue-dsl-chain C1, fix: recursive scan).
571        let mut args: BTreeMap<String, ArgValue> = BTreeMap::new();
572        for (k, v) in args_map {
573            if json_value_contains_prev_ref(&v) {
574                return Err(DslError::PrevRefInJsonForm { arg_name: k });
575            }
576            args.insert(k, ArgValue::Value(v));
577        }
578        ops.push(ParsedOp { tool, args });
579    }
580    let mode = if is_single {
581        ExecutionMode::Single
582    } else {
583        ExecutionMode::Parallel
584    };
585    Ok(ParsedRequest { ops, mode })
586}
587
588fn parse_fn_batch(input: &str) -> Result<ParsedRequest, DslError> {
589    let mut p = Parser::new(input);
590    p.expect_char('[')?;
591    p.skip_ws();
592    let mut ops = Vec::new();
593    if p.peek() == Some(']') {
594        p.advance(1);
595        return Err(DslError::EmptyBatch);
596    }
597    loop {
598        if ops.len() >= MAX_OPS {
599            return Err(DslError::TooManyOps {
600                count: ops.len() + 1,
601                max: MAX_OPS,
602            });
603        }
604        let op = p.parse_op()?;
605        ops.push(op);
606        p.skip_ws();
607        match p.peek() {
608            Some(',') => {
609                p.advance(1);
610                p.skip_ws();
611            }
612            Some(']') => {
613                p.advance(1);
614                break;
615            }
616            Some('|') => return Err(DslError::MixedSeparators),
617            Some(c) => {
618                return Err(DslError::UnexpectedChar {
619                    pos: p.pos,
620                    found: c,
621                    expected: "',' or ']'",
622                });
623            }
624            None => return Err(DslError::UnexpectedEof { expected: "']'" }),
625        }
626    }
627    p.skip_ws();
628    if !p.eof() {
629        return Err(DslError::UnexpectedChar {
630            pos: p.pos,
631            found: p.peek().unwrap(),
632            expected: "end of input",
633        });
634    }
635    // PrevRef inside a function-call parallel batch is invalid (adr-dsl-packs H1).
636    for op in &ops {
637        if let Some(pos) = find_prev_ref_pos(op) {
638            return Err(DslError::PrevRefOutsideChain { pos });
639        }
640    }
641    Ok(ParsedRequest {
642        ops,
643        mode: ExecutionMode::Parallel,
644    })
645}
646
647// ── recursive-descent parser ────────────────────────────────────────────────
648
649struct Parser<'a> {
650    src: &'a [u8],
651    pos: usize,
652}
653
654impl<'a> Parser<'a> {
655    fn new(src: &'a str) -> Self {
656        Self {
657            src: src.as_bytes(),
658            pos: 0,
659        }
660    }
661
662    fn eof(&self) -> bool {
663        self.pos >= self.src.len()
664    }
665
666    fn peek(&self) -> Option<char> {
667        self.src.get(self.pos).map(|b| *b as char)
668    }
669
670    fn advance(&mut self, n: usize) {
671        self.pos = (self.pos + n).min(self.src.len());
672    }
673
674    fn skip_ws(&mut self) {
675        while let Some(c) = self.peek() {
676            if c.is_ascii_whitespace() {
677                self.advance(1);
678            } else {
679                break;
680            }
681        }
682    }
683
684    fn expect_char(&mut self, want: char) -> Result<(), DslError> {
685        self.skip_ws();
686        match self.peek() {
687            Some(c) if c == want => {
688                self.advance(1);
689                Ok(())
690            }
691            Some(c) => Err(DslError::UnexpectedChar {
692                pos: self.pos,
693                found: c,
694                expected: char_label(want),
695            }),
696            None => Err(DslError::UnexpectedEof {
697                expected: char_label(want),
698            }),
699        }
700    }
701
702    fn parse_identifier(&mut self) -> Result<String, DslError> {
703        self.skip_ws();
704        let start = self.pos;
705        match self.peek() {
706            Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
707            _ => return Err(DslError::InvalidIdentifier { pos: self.pos }),
708        }
709        while let Some(c) = self.peek() {
710            if c.is_ascii_alphanumeric() || c == '_' {
711                self.advance(1);
712            } else {
713                break;
714            }
715        }
716        Ok(std::str::from_utf8(&self.src[start..self.pos])
717            .expect("ascii-only chunk")
718            .to_owned())
719    }
720
721    fn parse_op(&mut self) -> Result<ParsedOp, DslError> {
722        let mut tool = self.parse_identifier()?;
723        // One-level dotted verbs: brain.state, recall.candidates
724        if self.peek() == Some('.') {
725            self.advance(1);
726            let sub = self.parse_identifier()?;
727            tool = format!("{tool}.{sub}");
728            // Only one level of dotting is supported. A second '.' is a clear
729            // error (adr-dsl-packs H2) — emit UnsupportedVerbNesting instead of
730            // the misleading "expected '|' or end of input, found '.'" message.
731            if self.peek() == Some('.') {
732                return Err(DslError::UnsupportedVerbNesting { pos: self.pos });
733            }
734        }
735        self.expect_char('(')?;
736        self.skip_ws();
737        let mut args: BTreeMap<String, ArgValue> = BTreeMap::new();
738        if self.peek() == Some(')') {
739            self.advance(1);
740            return Ok(ParsedOp { tool, args });
741        }
742        loop {
743            let name = self.parse_identifier()?;
744            self.expect_char('=')?;
745            self.skip_ws();
746            let arg_val = self.parse_arg_value()?;
747            if args.contains_key(&name) {
748                return Err(DslError::DuplicateArg { name });
749            }
750            args.insert(name, arg_val);
751            self.skip_ws();
752            match self.peek() {
753                Some(',') => {
754                    self.advance(1);
755                    self.skip_ws();
756                }
757                Some(')') => {
758                    self.advance(1);
759                    return Ok(ParsedOp { tool, args });
760                }
761                Some(c) => {
762                    return Err(DslError::UnexpectedChar {
763                        pos: self.pos,
764                        found: c,
765                        expected: "',' or ')'",
766                    });
767                }
768                None => return Err(DslError::UnexpectedEof { expected: "')'" }),
769            }
770        }
771    }
772
773    /// Parse an argument value — either a `$prev` reference, an array/object
774    /// literal (which may contain `$prev` refs), or a plain JSON literal.
775    ///
776    /// CC-3: a quoted string like `"$prev.id"` is treated identically to the
777    /// unquoted token `$prev.id`. Both resolve to `ArgValue::PrevRef { path: "id" }`.
778    /// To pass the literal string `$prev.id` as a value, escape the leading `$`
779    /// in the JSON string: `"\\$prev.id"` deserializes to `\$prev.id`, which is
780    /// stripped to `$prev.id` and returned as a concrete `ArgValue::Value`.
781    fn parse_arg_value(&mut self) -> Result<ArgValue, DslError> {
782        self.skip_ws();
783        if self.peek() == Some('$') {
784            return self.parse_prev_ref();
785        }
786        if self.peek() == Some('[') {
787            return self.parse_array_arg();
788        }
789        if self.peek() == Some('{') {
790            return self.parse_object_arg();
791        }
792        let v = self.parse_value()?;
793        // CC-3: promote quoted "$prev[.path]" strings to PrevRef.
794        if let Value::String(s) = &v {
795            if let Some(prev_ref) = Self::string_as_prev_ref(s) {
796                return Ok(prev_ref);
797            }
798        }
799        Ok(ArgValue::Value(v))
800    }
801
802    /// Parse an array argument: `[elem, elem, ...]` where each element may be
803    /// a `$prev` reference, a nested array/object, or a plain JSON literal.
804    ///
805    /// When no element contains a `$prev` reference, the result is folded back
806    /// into an `ArgValue::Value(Array(_))` so pure-JSON callers see no change.
807    fn parse_array_arg(&mut self) -> Result<ArgValue, DslError> {
808        self.advance(1); // consume '['
809        self.skip_ws();
810        let mut elements: Vec<ArgValue> = Vec::new();
811        if self.peek() == Some(']') {
812            self.advance(1);
813            return Ok(ArgValue::Value(Value::Array(vec![])));
814        }
815        loop {
816            self.skip_ws();
817            let elem = self.parse_arg_value()?;
818            elements.push(elem);
819            self.skip_ws();
820            match self.peek() {
821                Some(',') => {
822                    self.advance(1);
823                }
824                Some(']') => {
825                    self.advance(1);
826                    break;
827                }
828                Some(c) => {
829                    return Err(DslError::UnexpectedChar {
830                        pos: self.pos,
831                        found: c,
832                        expected: "',' or ']'",
833                    });
834                }
835                None => return Err(DslError::UnexpectedEof { expected: "']'" }),
836            }
837        }
838        // If no element is a PrevRef/Array/Object, fold to Value for efficiency.
839        let has_dynamic = elements.iter().any(|e| !matches!(e, ArgValue::Value(_)));
840        if has_dynamic {
841            Ok(ArgValue::Array(elements))
842        } else {
843            let vals: Vec<Value> = elements
844                .into_iter()
845                .map(|e| match e {
846                    ArgValue::Value(v) => v,
847                    _ => unreachable!(),
848                })
849                .collect();
850            Ok(ArgValue::Value(Value::Array(vals)))
851        }
852    }
853
854    /// Parse an object argument: `{"key": value, ...}`.
855    ///
856    /// Keys must be quoted strings (JSON-style). Values may contain `$prev` refs.
857    /// Pure-JSON objects without any `$prev` fold back into `ArgValue::Value`.
858    fn parse_object_arg(&mut self) -> Result<ArgValue, DslError> {
859        self.advance(1); // consume '{'
860        self.skip_ws();
861        let mut pairs: Vec<(String, ArgValue)> = Vec::new();
862        if self.peek() == Some('}') {
863            self.advance(1);
864            return Ok(ArgValue::Value(Value::Object(serde_json::Map::new())));
865        }
866        loop {
867            self.skip_ws();
868            // Key must be a quoted string — parse it directly (not via parse_value,
869            // which uses scan_value_end and would greedily consume `:value`).
870            let key = match self.peek() {
871                Some('"') => {
872                    let start = self.pos;
873                    let end = scan_string_end(self.src, start)?;
874                    let raw = std::str::from_utf8(&self.src[start..end]).expect("utf8 key literal");
875                    let s: String =
876                        serde_json::from_str(raw).map_err(|e| DslError::InvalidValue {
877                            pos: start,
878                            error: e.to_string(),
879                        })?;
880                    self.pos = end;
881                    s
882                }
883                Some(c) => {
884                    return Err(DslError::UnexpectedChar {
885                        pos: self.pos,
886                        found: c,
887                        expected: "quoted string key",
888                    });
889                }
890                None => {
891                    return Err(DslError::UnexpectedEof {
892                        expected: "object key",
893                    })
894                }
895            };
896            self.skip_ws();
897            self.expect_char(':')?;
898            self.skip_ws();
899            let val = self.parse_arg_value()?;
900            pairs.push((key, val));
901            self.skip_ws();
902            match self.peek() {
903                Some(',') => {
904                    self.advance(1);
905                }
906                Some('}') => {
907                    self.advance(1);
908                    break;
909                }
910                Some(c) => {
911                    return Err(DslError::UnexpectedChar {
912                        pos: self.pos,
913                        found: c,
914                        expected: "',' or '}'",
915                    });
916                }
917                None => return Err(DslError::UnexpectedEof { expected: "'}'" }),
918            }
919        }
920        // Fold pure-JSON objects back to Value.
921        let has_dynamic = pairs.iter().any(|(_, v)| !matches!(v, ArgValue::Value(_)));
922        if has_dynamic {
923            Ok(ArgValue::Object(pairs))
924        } else {
925            let mut map = serde_json::Map::with_capacity(pairs.len());
926            for (k, v) in pairs {
927                match v {
928                    ArgValue::Value(val) => {
929                        map.insert(k, val);
930                    }
931                    _ => unreachable!(),
932                }
933            }
934            Ok(ArgValue::Value(Value::Object(map)))
935        }
936    }
937
938    /// Parse a `$prev` or `$prev.field.path` reference.
939    ///
940    /// Grammar: `$prev` optionally followed by a path composed of:
941    /// - dot-separated identifiers: `.field`
942    /// - bracket array indices:     `[N]`
943    ///
944    /// Examples: `$prev`, `$prev.id`, `$prev.items[0].id`, `$prev[0].name`
945    /// (ue-dsl-chain H1: minimal array-index support added).
946    fn parse_prev_ref(&mut self) -> Result<ArgValue, DslError> {
947        let start = self.pos;
948        // Consume `$`
949        self.advance(1);
950        // Must be followed by `prev`
951        let ident = self
952            .parse_identifier()
953            .map_err(|_| DslError::InvalidValue {
954                pos: start,
955                error: "expected '$prev' — '$' must be followed by 'prev'".into(),
956            })?;
957        if ident != "prev" {
958            return Err(DslError::InvalidValue {
959                pos: start,
960                error: format!("expected '$prev', found '${}'", ident),
961            });
962        }
963        // Optional path — dot-segments and/or bracket indices.
964        let mut path = String::new();
965        loop {
966            match self.peek() {
967                Some('.') => {
968                    self.advance(1); // consume '.'
969                    let segment = self.parse_identifier()?;
970                    if !path.is_empty() {
971                        path.push('.');
972                    }
973                    path.push_str(&segment);
974                }
975                Some('[') => {
976                    // Array index: `[N]`
977                    self.advance(1); // consume '['
978                    let idx_start = self.pos;
979                    // Read digits
980                    let mut idx_str = String::new();
981                    while let Some(c) = self.peek() {
982                        if c.is_ascii_digit() {
983                            idx_str.push(c);
984                            self.advance(1);
985                        } else {
986                            break;
987                        }
988                    }
989                    if idx_str.is_empty() {
990                        return Err(DslError::InvalidValue {
991                            pos: idx_start,
992                            error: "expected non-negative integer inside '[...]'".into(),
993                        });
994                    }
995                    match self.peek() {
996                        Some(']') => self.advance(1),
997                        Some(c) => {
998                            return Err(DslError::UnexpectedChar {
999                                pos: self.pos,
1000                                found: c,
1001                                expected: "']'",
1002                            });
1003                        }
1004                        None => {
1005                            return Err(DslError::UnexpectedEof { expected: "']'" });
1006                        }
1007                    }
1008                    if !path.is_empty() {
1009                        path.push('.');
1010                    }
1011                    // Encode index as `[N]` so split_path can parse it back.
1012                    path.push('[');
1013                    path.push_str(&idx_str);
1014                    path.push(']');
1015                }
1016                _ => break,
1017            }
1018        }
1019        Ok(ArgValue::PrevRef { path })
1020    }
1021
1022    fn parse_value(&mut self) -> Result<Value, DslError> {
1023        self.skip_ws();
1024        let start = self.pos;
1025        let end = self.scan_value_end()?;
1026        let slice = std::str::from_utf8(&self.src[start..end])
1027            .expect("ascii-or-utf8 maintained by scanner");
1028        let value: Value =
1029            serde_json::from_str(slice.trim()).map_err(|e| DslError::InvalidValue {
1030                pos: start,
1031                error: e.to_string(),
1032            })?;
1033        self.pos = end;
1034        Ok(value)
1035    }
1036
1037    /// Check whether a parsed string value is a `$prev` reference written
1038    /// inside quotes (CC-3). Returns `Some(PrevRef)` if so, or
1039    /// `Some(Value(...))` if the string is an escaped literal, or `None` if
1040    /// neither (i.e. an ordinary string the caller should store as-is).
1041    ///
1042    /// ## Escape semantics (High-2 fix)
1043    ///
1044    /// A string like `"$prev.id"` deserializes to the Rust string `$prev.id`
1045    /// and is promoted to `ArgValue::PrevRef { path: "id" }`.
1046    ///
1047    /// To pass the **literal** string `$prev.id` as a value, write `"\\$prev.id"`
1048    /// in the DSL source. That deserializes to `\$prev.id` (one leading backslash).
1049    /// This function strips the leading `\` and returns
1050    /// `ArgValue::Value(json!("$prev.id"))` — so the handler receives the clean
1051    /// string without the escape marker.
1052    ///
1053    /// `$prevish.id` does NOT match (prefix boundary is `.` or `[` only).
1054    ///
1055    /// ## Bracket-index validation (Medium-1 fix)
1056    ///
1057    /// Quoted `$prev[...]` strings are routed through the same bracket-body
1058    /// validator as unquoted refs: only non-negative integers are accepted inside
1059    /// `[...]`. Malformed brackets (negative index, non-numeric, unclosed) return
1060    /// `None` (treated as a literal, consistent with the caller treating unknown
1061    /// forms as values).
1062    fn string_as_prev_ref(s: &str) -> Option<ArgValue> {
1063        // Escape: `\$prev...` → strip the leading backslash, return literal.
1064        if let Some(rest) = s.strip_prefix('\\') {
1065            if rest == "$prev" || rest.starts_with("$prev.") || rest.starts_with("$prev[") {
1066                return Some(ArgValue::Value(Value::String(rest.to_owned())));
1067            }
1068        }
1069
1070        if s == "$prev" {
1071            return Some(ArgValue::PrevRef {
1072                path: String::new(),
1073            });
1074        }
1075        // "$prev.field..."
1076        if let Some(rest) = s.strip_prefix("$prev.") {
1077            if !rest.is_empty() {
1078                return Some(ArgValue::PrevRef {
1079                    path: rest.to_owned(),
1080                });
1081            }
1082        }
1083        // "$prev[N]..." — validate bracket body before promoting (Medium-1 fix).
1084        if let Some(after_bracket) = s.strip_prefix("$prev[") {
1085            // after_bracket is everything after "[", e.g. "0].id" or "-1].id"
1086            if let Some(close) = after_bracket.find(']') {
1087                let index_str = &after_bracket[..close];
1088                // Only non-negative integers are valid.
1089                if !index_str.is_empty() && index_str.chars().all(|c| c.is_ascii_digit()) {
1090                    let tail = &after_bracket[close + 1..]; // "].id" → ".id" after close
1091                                                            // path encodes as "[N]..." (used by split_path)
1092                    let path = format!("[{index_str}]{tail}");
1093                    return Some(ArgValue::PrevRef { path });
1094                }
1095            }
1096            // Malformed bracket (missing ']', negative, non-numeric) — treat as invalid.
1097            // Return None so the caller stores it as a literal Value.
1098            return None;
1099        }
1100        None
1101    }
1102
1103    /// Walk forward through the input to find the end of a JSON value, respecting
1104    /// nested brackets / braces and string literals. The returned index is one
1105    /// past the last byte of the value (exclusive).
1106    fn scan_value_end(&self) -> Result<usize, DslError> {
1107        let mut i = self.pos;
1108        let mut depth_paren: i32 = 0; // `(` from the surrounding op
1109        let mut depth_brack: i32 = 0;
1110        let mut depth_brace: i32 = 0;
1111        while i < self.src.len() {
1112            let c = self.src[i] as char;
1113            match c {
1114                '"' => {
1115                    i = scan_string_end(self.src, i)?;
1116                    continue;
1117                }
1118                '[' => depth_brack += 1,
1119                ']' => {
1120                    if depth_brack == 0 {
1121                        if depth_paren == 0 && depth_brace == 0 {
1122                            return Ok(i);
1123                        }
1124                        // we never opened a paren here; this terminates the value.
1125                        return Ok(i);
1126                    }
1127                    depth_brack -= 1;
1128                }
1129                '{' => depth_brace += 1,
1130                '}' => {
1131                    if depth_brace == 0 {
1132                        // Closing brace outside any open brace — terminates the
1133                        // current value (e.g. a string value inside an object literal
1134                        // parsed by parse_object_arg).
1135                        if depth_paren == 0 && depth_brack == 0 {
1136                            return Ok(i);
1137                        }
1138                        return Err(DslError::UnclosedBracket { kind: '{' });
1139                    }
1140                    depth_brace -= 1;
1141                }
1142                '(' => depth_paren += 1,
1143                ')' => {
1144                    if depth_paren == 0 && depth_brack == 0 && depth_brace == 0 {
1145                        return Ok(i);
1146                    }
1147                    if depth_paren == 0 {
1148                        return Err(DslError::UnclosedBracket { kind: '(' });
1149                    }
1150                    depth_paren -= 1;
1151                }
1152                ',' => {
1153                    if depth_paren == 0 && depth_brack == 0 && depth_brace == 0 {
1154                        return Ok(i);
1155                    }
1156                }
1157                _ => {}
1158            }
1159            i += 1;
1160        }
1161        if depth_brack > 0 {
1162            return Err(DslError::UnclosedBracket { kind: '[' });
1163        }
1164        if depth_brace > 0 {
1165            return Err(DslError::UnclosedBracket { kind: '{' });
1166        }
1167        Ok(i)
1168    }
1169}
1170
1171/// Return `true` if the string value is a `$prev` reference written inside JSON
1172/// quotes. Used to detect `"$prev.id"` literals in JSON-form input (ue-dsl-chain C1).
1173///
1174/// Matches exactly `$prev`, strings starting with `$prev.`, or strings starting
1175/// with `$prev[` (bracket-index form). Does NOT match `$prevish.id` — the prefix
1176/// boundary is `.` or `[` only.
1177fn is_prev_ref_string(s: &str) -> bool {
1178    s == "$prev" || s.starts_with("$prev.") || s.starts_with("$prev[")
1179}
1180
1181/// Recursively scan a JSON value for any string that is a `$prev` reference.
1182///
1183/// This covers nested arrays and objects, so `{"ids": ["$prev.id"]}` and
1184/// `{"nested": {"id": "$prev[0].id"}}` are both detected (fix for High-1).
1185fn json_value_contains_prev_ref(v: &Value) -> bool {
1186    match v {
1187        Value::String(s) => is_prev_ref_string(s),
1188        Value::Array(arr) => arr.iter().any(json_value_contains_prev_ref),
1189        Value::Object(map) => map.values().any(json_value_contains_prev_ref),
1190        _ => false,
1191    }
1192}
1193
1194/// A single segment in a `$prev` path — either a field name or an array index.
1195#[derive(Debug, Clone, PartialEq)]
1196enum PathSegment<'a> {
1197    Field(&'a str),
1198    Index(usize),
1199}
1200
1201/// Split a dotted path that may contain bracket array indices into segments.
1202///
1203/// `"items[0].id"` → `[Field("items"), Index(0), Field("id")]`
1204/// `"[2].name"` → `[Index(2), Field("name")]`
1205/// `"plain.path"` → `[Field("plain"), Field("path")]`
1206fn split_path(path: &str) -> Vec<PathSegment<'_>> {
1207    let mut segments = Vec::new();
1208    let mut remaining = path;
1209    while !remaining.is_empty() {
1210        if let Some(rest) = remaining.strip_prefix('[') {
1211            // Array index: `[N]...`
1212            if let Some(close) = rest.find(']') {
1213                let index_str = &rest[..close];
1214                if let Ok(idx) = index_str.parse::<usize>() {
1215                    segments.push(PathSegment::Index(idx));
1216                    remaining = &rest[close + 1..];
1217                    // Strip leading '.' before next segment, if any.
1218                    remaining = remaining.strip_prefix('.').unwrap_or(remaining);
1219                    continue;
1220                }
1221            }
1222            // Malformed index — treat whole remainder as field (will fail lookup).
1223            segments.push(PathSegment::Field(remaining));
1224            break;
1225        }
1226        // Field name — up to next '.' or '['.
1227        let end = remaining.find(['.', '[']).unwrap_or(remaining.len());
1228        let field = &remaining[..end];
1229        if !field.is_empty() {
1230            segments.push(PathSegment::Field(field));
1231        }
1232        remaining = &remaining[end..];
1233        // Strip leading '.' separator.
1234        remaining = remaining.strip_prefix('.').unwrap_or(remaining);
1235    }
1236    segments
1237}
1238
1239/// Apply one path segment to a JSON value — field lookup or array index.
1240fn apply_path_segment<'a>(cur: &'a Value, seg: PathSegment<'_>) -> Option<&'a Value> {
1241    match seg {
1242        PathSegment::Field(key) => cur.get(key),
1243        PathSegment::Index(idx) => cur.as_array()?.get(idx),
1244    }
1245}
1246
1247/// Scan an op's args for any `PrevRef` (or `Array`/`Object` containing one) and
1248/// return a representative position (0 — we don't track source positions per-arg
1249/// at this stage) if any is found. Used to emit `PrevRefOutsideChain` at parse
1250/// time for Single and Parallel modes (adr-dsl-packs H1).
1251fn find_prev_ref_pos(op: &ParsedOp) -> Option<usize> {
1252    for av in op.args.values() {
1253        if arg_value_has_prev_ref(av) {
1254            return Some(0);
1255        }
1256    }
1257    None
1258}
1259
1260fn arg_value_has_prev_ref(av: &ArgValue) -> bool {
1261    match av {
1262        ArgValue::PrevRef { .. } => true,
1263        ArgValue::Array(els) => els.iter().any(arg_value_has_prev_ref),
1264        ArgValue::Object(pairs) => pairs.iter().any(|(_, v)| arg_value_has_prev_ref(v)),
1265        ArgValue::Value(_) => false,
1266    }
1267}
1268
1269fn scan_string_end(src: &[u8], start: usize) -> Result<usize, DslError> {
1270    let mut i = start + 1;
1271    while i < src.len() {
1272        match src[i] as char {
1273            '\\' => {
1274                i += 2; // skip escape pair
1275                continue;
1276            }
1277            '"' => return Ok(i + 1),
1278            _ => i += 1,
1279        }
1280    }
1281    Err(DslError::UnclosedString)
1282}
1283
1284fn char_label(c: char) -> &'static str {
1285    match c {
1286        '(' => "'('",
1287        ')' => "')'",
1288        '[' => "'['",
1289        ']' => "']'",
1290        '=' => "'='",
1291        ',' => "','",
1292        _ => "expected char",
1293    }
1294}
1295
1296#[cfg(test)]
1297mod tests {
1298    use super::*;
1299    use serde_json::json;
1300
1301    fn req(s: &str) -> ParsedRequest {
1302        parse_request(s).unwrap_or_else(|e| panic!("parse({s:?}) failed: {e}"))
1303    }
1304
1305    fn ops(s: &str) -> Vec<ParsedOp> {
1306        req(s).ops
1307    }
1308
1309    /// Extract the concrete `Value` from an `ArgValue::Value`, panicking on dynamic variants.
1310    fn val(arg: &ArgValue) -> &Value {
1311        match arg {
1312            ArgValue::Value(v) => v,
1313            ArgValue::PrevRef { path } => {
1314                panic!("expected Value, got PrevRef {{ path: {path:?} }}")
1315            }
1316            ArgValue::Array(els) => {
1317                panic!("expected Value, got Array with {} elements", els.len())
1318            }
1319            ArgValue::Object(pairs) => {
1320                panic!("expected Value, got Object with {} keys", pairs.len())
1321            }
1322        }
1323    }
1324
1325    #[test]
1326    fn single_op_no_args() {
1327        let r = req("gtd.next()");
1328        assert_eq!(r.mode, ExecutionMode::Single);
1329        assert_eq!(r.ops.len(), 1);
1330        assert_eq!(r.ops[0].tool, "gtd.next");
1331        assert!(r.ops[0].args.is_empty());
1332    }
1333
1334    #[test]
1335    fn single_op_with_string_arg() {
1336        let v = ops(r#"gtd.assign(title="ship release")"#);
1337        assert_eq!(v[0].tool, "gtd.assign");
1338        assert_eq!(val(&v[0].args["title"]), &json!("ship release"));
1339    }
1340
1341    #[test]
1342    fn single_op_with_multiple_typed_args() {
1343        let v = ops(
1344            r#"create(kind="entity", entity_kind="concept", name="LoRA", weight=0.9, active=true)"#,
1345        );
1346        assert_eq!(v[0].tool, "create");
1347        assert_eq!(val(&v[0].args["kind"]), &json!("entity"));
1348        assert_eq!(val(&v[0].args["weight"]), &json!(0.9));
1349        assert_eq!(val(&v[0].args["active"]), &json!(true));
1350    }
1351
1352    #[test]
1353    fn batch_three_ops() {
1354        let r = req(
1355            r#"[create(kind="entity", name="A"), create(kind="entity", name="B"), link(source_id="x", target_id="y", relation="extends")]"#,
1356        );
1357        assert_eq!(r.mode, ExecutionMode::Parallel);
1358        assert_eq!(r.ops.len(), 3);
1359        assert_eq!(r.ops[0].tool, "create");
1360        assert_eq!(r.ops[2].tool, "link");
1361        assert_eq!(val(&r.ops[2].args["relation"]), &json!("extends"));
1362    }
1363
1364    #[test]
1365    fn empty_batch_rejected() {
1366        // UE4-H2: empty batch must be rejected with EmptyBatch error.
1367        let err = parse_request("[]").unwrap_err();
1368        assert!(
1369            matches!(err, DslError::EmptyBatch),
1370            "expected EmptyBatch, got {err:?}"
1371        );
1372        // JSON form empty array is also rejected.
1373        let err2 = parse_request("[]").unwrap_err();
1374        assert!(matches!(err2, DslError::EmptyBatch));
1375    }
1376
1377    #[test]
1378    fn nested_array_and_object_values() {
1379        let v = ops(r#"gtd.assign(title="x", tags=["a","b"], properties={"k":"v","n":1})"#);
1380        assert_eq!(val(&v[0].args["tags"]), &json!(["a", "b"]));
1381        assert_eq!(val(&v[0].args["properties"]), &json!({"k": "v", "n": 1}));
1382    }
1383
1384    #[test]
1385    fn string_with_comma_and_paren_inside() {
1386        let v = ops(r#"gtd.assign(title="hello, world (now)")"#);
1387        assert_eq!(val(&v[0].args["title"]), &json!("hello, world (now)"));
1388    }
1389
1390    #[test]
1391    fn string_with_escaped_quote() {
1392        let v = ops(r#"gtd.assign(title="he said \"hi\"")"#);
1393        assert_eq!(val(&v[0].args["title"]), &json!("he said \"hi\""));
1394    }
1395
1396    #[test]
1397    fn null_and_negative_number() {
1398        let v = ops(r#"update(id="x", description=null, weight=-0.5)"#);
1399        assert_eq!(val(&v[0].args["description"]), &json!(null));
1400        assert_eq!(val(&v[0].args["weight"]), &json!(-0.5));
1401    }
1402
1403    #[test]
1404    fn json_form_batch_parses() {
1405        let r =
1406            req(r#"[{"tool":"gtd.next","args":{}}, {"tool":"gtd.complete","args":{"id":"abc"}}]"#);
1407        assert_eq!(r.mode, ExecutionMode::Parallel);
1408        assert_eq!(r.ops.len(), 2);
1409        assert_eq!(r.ops[1].tool, "gtd.complete");
1410        assert_eq!(val(&r.ops[1].args["id"]), &json!("abc"));
1411    }
1412
1413    #[test]
1414    fn json_form_with_leading_whitespace_inside_array_parses() {
1415        // Pretty-printers commonly emit `[ {...} ]` with spaces or newlines after `[`.
1416        // The whitespace is legal JSON, so the parser must route this to the JSON
1417        // path rather than the function-call batch parser.
1418        let v = ops(r#"[  {"tool":"gtd.next","args":{}} ]"#);
1419        assert_eq!(v.len(), 1);
1420        assert_eq!(v[0].tool, "gtd.next");
1421
1422        let v = ops("[\n  {\"tool\":\"gtd.next\",\"args\":{}},\n  {\"tool\":\"gtd.complete\",\"args\":{\"id\":\"x\"}}\n]");
1423        assert_eq!(v.len(), 2);
1424        assert_eq!(v[1].tool, "gtd.complete");
1425    }
1426
1427    #[test]
1428    fn json_form_single_object_is_treated_as_one_op() {
1429        let r = req(r#"{"tool":"gtd.next","args":{}}"#);
1430        assert_eq!(r.mode, ExecutionMode::Single);
1431        assert_eq!(r.ops.len(), 1);
1432        assert_eq!(r.ops[0].tool, "gtd.next");
1433    }
1434
1435    #[test]
1436    fn duplicate_arg_rejected() {
1437        let err = parse_request(r#"gtd.assign(title="a", title="b")"#).unwrap_err();
1438        assert!(matches!(err, DslError::DuplicateArg { ref name } if name == "title"));
1439    }
1440
1441    #[test]
1442    fn unknown_token_after_op_rejected() {
1443        let err = parse_request(r#"gtd.next() garbage"#).unwrap_err();
1444        assert!(matches!(err, DslError::UnexpectedChar { .. }));
1445    }
1446
1447    #[test]
1448    fn unclosed_paren_rejected() {
1449        let err = parse_request(r#"gtd.assign(title="a""#).unwrap_err();
1450        // The string is closed; the args list isn't.
1451        assert!(matches!(err, DslError::UnexpectedEof { .. }));
1452    }
1453
1454    #[test]
1455    fn unterminated_string_rejected() {
1456        let err = parse_request(r#"gtd.assign(title="oops)"#).unwrap_err();
1457        assert!(matches!(err, DslError::UnclosedString));
1458    }
1459
1460    #[test]
1461    fn too_many_ops_rejected() {
1462        let one = r#"gtd.next(),"#;
1463        let mut s = String::from("[");
1464        for _ in 0..MAX_OPS + 1 {
1465            s.push_str(one);
1466        }
1467        s.push_str("gtd.next()]");
1468        let err = parse_request(&s).unwrap_err();
1469        assert!(matches!(err, DslError::TooManyOps { .. }));
1470    }
1471
1472    #[test]
1473    fn empty_request_rejected() {
1474        let err = parse_request("   ").unwrap_err();
1475        assert!(matches!(err, DslError::Empty));
1476    }
1477
1478    // ── Required prompt examples ───────────────────────────────────────────────
1479
1480    #[test]
1481    fn recall_with_query_arg() {
1482        let v = ops(r#"memory.recall(query="test")"#);
1483        assert_eq!(v.len(), 1);
1484        assert_eq!(v[0].tool, "memory.recall");
1485        assert_eq!(val(&v[0].args["query"]), &json!("test"));
1486    }
1487
1488    #[test]
1489    fn search_with_query_and_limit() {
1490        let v = ops(r#"search(query="test", limit=5)"#);
1491        assert_eq!(v.len(), 1);
1492        assert_eq!(v[0].tool, "search");
1493        assert_eq!(val(&v[0].args["query"]), &json!("test"));
1494        assert_eq!(val(&v[0].args["limit"]), &json!(5));
1495    }
1496
1497    #[test]
1498    fn parallel_recall_and_inbox() {
1499        let r = req(r#"[memory.recall(query="x"), comm.inbox()]"#);
1500        assert_eq!(r.mode, ExecutionMode::Parallel);
1501        assert_eq!(r.ops.len(), 2);
1502        assert_eq!(r.ops[0].tool, "memory.recall");
1503        assert_eq!(val(&r.ops[0].args["query"]), &json!("x"));
1504        assert_eq!(r.ops[1].tool, "comm.inbox");
1505        assert!(r.ops[1].args.is_empty());
1506    }
1507
1508    // ── JSON form edge cases ───────────────────────────────────────────────────
1509
1510    #[test]
1511    fn json_missing_args_defaults_to_empty_map() {
1512        let v = ops(r#"{"tool":"comm.inbox"}"#);
1513        assert_eq!(v.len(), 1);
1514        assert_eq!(v[0].tool, "comm.inbox");
1515        assert!(v[0].args.is_empty());
1516    }
1517
1518    #[test]
1519    fn json_args_as_array_rejected() {
1520        let err = parse_request(r#"{"tool":"x","args":[]}"#).unwrap_err();
1521        assert!(matches!(err, DslError::InvalidJson { .. }));
1522    }
1523
1524    // ── Identifier grammar ────────────────────────────────────────────────────
1525
1526    #[test]
1527    fn dotted_tool_name_parsed() {
1528        let v = ops("brain.state()");
1529        assert_eq!(v[0].tool, "brain.state");
1530        assert!(v[0].args.is_empty());
1531    }
1532
1533    #[test]
1534    fn dotted_tool_with_args() {
1535        let v = ops(r#"memory.recall_candidates(query="test", limit=5)"#);
1536        assert_eq!(v[0].tool, "memory.recall_candidates");
1537        assert_eq!(val(&v[0].args["query"]), &json!("test"));
1538        assert_eq!(val(&v[0].args["limit"]), &json!(5));
1539    }
1540
1541    #[test]
1542    fn dotted_tool_in_batch() {
1543        let v = ops(r#"[brain.state(), memory.recall_fuse(query="x")]"#);
1544        assert_eq!(v.len(), 2);
1545        assert_eq!(v[0].tool, "brain.state");
1546        assert_eq!(v[1].tool, "memory.recall_fuse");
1547    }
1548
1549    #[test]
1550    fn leading_underscore_identifier_is_valid() {
1551        let v = ops("_internal()");
1552        assert_eq!(v[0].tool, "_internal");
1553        assert!(v[0].args.is_empty());
1554    }
1555
1556    #[test]
1557    fn identifier_starting_with_digit_rejected() {
1558        let err = parse_request("1bad()").unwrap_err();
1559        assert!(matches!(err, DslError::InvalidIdentifier { pos: 0 }));
1560    }
1561
1562    // ── Argument value edge cases ─────────────────────────────────────────────
1563
1564    #[test]
1565    fn boolean_false_as_arg_value() {
1566        let v = ops("flag(active=false)");
1567        assert_eq!(val(&v[0].args["active"]), &json!(false));
1568    }
1569
1570    #[test]
1571    fn unicode_string_arg_preserved() {
1572        let v = ops(r#"gtd.assign(title="café")"#);
1573        assert_eq!(val(&v[0].args["title"]), &json!("café"));
1574    }
1575
1576    // ── Chain mode (ADR-016) ──────────────────────────────────────────────────
1577
1578    #[test]
1579    fn chain_two_ops_with_prev_ref() {
1580        let r = req(
1581            r#"create(kind="entity", entity_kind="concept", name="A") | link(source_id=$prev.id, target_id="abc", relation="extends")"#,
1582        );
1583        assert_eq!(r.mode, ExecutionMode::Chain);
1584        assert_eq!(r.ops.len(), 2);
1585        assert_eq!(r.ops[0].tool, "create");
1586        assert_eq!(r.ops[1].tool, "link");
1587        // The second op's source_id should be a PrevRef
1588        assert_eq!(
1589            r.ops[1].args["source_id"],
1590            ArgValue::PrevRef { path: "id".into() }
1591        );
1592        // target_id is a concrete value
1593        assert_eq!(val(&r.ops[1].args["target_id"]), &json!("abc"));
1594    }
1595
1596    #[test]
1597    fn chain_three_ops_mode() {
1598        let r = req(
1599            r#"create(kind="entity", name="A") | link(source_id=$prev.id, target_id="b", relation="extends") | update(id=$prev.id, description="desc")"#,
1600        );
1601        assert_eq!(r.mode, ExecutionMode::Chain);
1602        assert_eq!(r.ops.len(), 3);
1603        assert_eq!(r.ops[2].args["id"], ArgValue::PrevRef { path: "id".into() });
1604    }
1605
1606    #[test]
1607    fn chain_prev_no_field_selector() {
1608        // $prev alone (no dot path) refers to the whole prior result.
1609        let r = req(r#"gtd.next() | update(id=$prev)"#);
1610        assert_eq!(r.mode, ExecutionMode::Chain);
1611        assert_eq!(r.ops[1].args["id"], ArgValue::PrevRef { path: "".into() });
1612    }
1613
1614    #[test]
1615    fn chain_prev_deep_path() {
1616        let r = req(
1617            r#"create(kind="entity", name="A") | link(source_id=$prev.result.id, target_id="b", relation="extends")"#,
1618        );
1619        assert_eq!(r.mode, ExecutionMode::Chain);
1620        assert_eq!(
1621            r.ops[1].args["source_id"],
1622            ArgValue::PrevRef {
1623                path: "result.id".into()
1624            }
1625        );
1626    }
1627
1628    #[test]
1629    fn single_op_mode() {
1630        let r = req("gtd.next()");
1631        assert_eq!(r.mode, ExecutionMode::Single);
1632    }
1633
1634    #[test]
1635    fn chain_too_many_ops_rejected() {
1636        let mut s = String::from("gtd.next()");
1637        for _ in 0..MAX_OPS {
1638            s.push_str(" | gtd.next()");
1639        }
1640        let err = parse_request(&s).unwrap_err();
1641        assert!(matches!(err, DslError::TooManyOps { .. }));
1642    }
1643
1644    // ── ArgValue helpers ──────────────────────────────────────────────────────
1645
1646    #[test]
1647    fn arg_value_resolve_prev_simple() {
1648        let prev = json!({"id": "abc-123", "name": "A"});
1649        let r = ArgValue::PrevRef { path: "id".into() };
1650        assert_eq!(r.resolve_prev(&prev), Some(&json!("abc-123")));
1651    }
1652
1653    #[test]
1654    fn arg_value_resolve_prev_empty_path() {
1655        let prev = json!({"id": "x"});
1656        let r = ArgValue::PrevRef { path: "".into() };
1657        assert_eq!(r.resolve_prev(&prev), Some(&prev));
1658    }
1659
1660    #[test]
1661    fn arg_value_resolve_prev_nested_path() {
1662        let prev = json!({"result": {"id": "nested-id"}});
1663        let r = ArgValue::PrevRef {
1664            path: "result.id".into(),
1665        };
1666        assert_eq!(r.resolve_prev(&prev), Some(&json!("nested-id")));
1667    }
1668
1669    #[test]
1670    fn arg_value_resolve_prev_missing_field_returns_none() {
1671        let prev = json!({"id": "x"});
1672        let r = ArgValue::PrevRef {
1673            path: "nonexistent".into(),
1674        };
1675        assert_eq!(r.resolve_prev(&prev), None);
1676    }
1677
1678    #[test]
1679    fn arg_value_value_returns_none_for_resolve_prev() {
1680        let r = ArgValue::Value(json!("hello"));
1681        assert_eq!(r.resolve_prev(&json!({})), None);
1682    }
1683
1684    // ── G-C1: $prev inside array / object literals (regression) ──────────────
1685
1686    #[test]
1687    fn chain_prev_in_single_element_array() {
1688        // `gtd.assign(title="root") | gtd.assign(title="dep", depends_on=[$prev.full_id])`
1689        let r = req(
1690            r#"gtd.assign(title="root") | gtd.assign(title="dep", depends_on=[$prev.full_id])"#,
1691        );
1692        assert_eq!(r.mode, ExecutionMode::Chain);
1693        assert_eq!(r.ops.len(), 2);
1694        match &r.ops[1].args["depends_on"] {
1695            ArgValue::Array(els) => {
1696                assert_eq!(els.len(), 1);
1697                assert_eq!(
1698                    els[0],
1699                    ArgValue::PrevRef {
1700                        path: "full_id".into()
1701                    }
1702                );
1703            }
1704            other => panic!("expected Array, got {other:?}"),
1705        }
1706    }
1707
1708    #[test]
1709    fn chain_prev_in_mixed_array() {
1710        // `[$prev.id, "literal-uuid"]` — first element is PrevRef, second is literal.
1711        let r = req(
1712            r#"gtd.assign(title="root") | gtd.assign(title="dep", depends_on=[$prev.id, "literal-uuid"])"#,
1713        );
1714        assert_eq!(r.mode, ExecutionMode::Chain);
1715        match &r.ops[1].args["depends_on"] {
1716            ArgValue::Array(els) => {
1717                assert_eq!(els.len(), 2);
1718                assert_eq!(els[0], ArgValue::PrevRef { path: "id".into() });
1719                assert_eq!(els[1], ArgValue::Value(json!("literal-uuid")));
1720            }
1721            other => panic!("expected Array, got {other:?}"),
1722        }
1723    }
1724
1725    #[test]
1726    fn chain_prev_multiple_in_array() {
1727        // `depends_on=[$prev.field.deep, $prev.other]`
1728        let r = req(
1729            r#"gtd.assign(title="root") | gtd.assign(title="dep", depends_on=[$prev.field.deep, $prev.other])"#,
1730        );
1731        assert_eq!(r.mode, ExecutionMode::Chain);
1732        match &r.ops[1].args["depends_on"] {
1733            ArgValue::Array(els) => {
1734                assert_eq!(els.len(), 2);
1735                assert_eq!(
1736                    els[0],
1737                    ArgValue::PrevRef {
1738                        path: "field.deep".into()
1739                    }
1740                );
1741                assert_eq!(
1742                    els[1],
1743                    ArgValue::PrevRef {
1744                        path: "other".into()
1745                    }
1746                );
1747            }
1748            other => panic!("expected Array, got {other:?}"),
1749        }
1750    }
1751
1752    #[test]
1753    fn chain_prev_inside_object_inside_array() {
1754        // `properties={"refs":[$prev.id]}` — nested: object containing array containing PrevRef
1755        let r = req(
1756            r#"gtd.assign(title="root") | gtd.assign(title="dep", properties={"refs": [$prev.id]})"#,
1757        );
1758        assert_eq!(r.mode, ExecutionMode::Chain);
1759        match &r.ops[1].args["properties"] {
1760            ArgValue::Object(pairs) => {
1761                assert_eq!(pairs.len(), 1);
1762                assert_eq!(pairs[0].0, "refs");
1763                match &pairs[0].1 {
1764                    ArgValue::Array(els) => {
1765                        assert_eq!(els.len(), 1);
1766                        assert_eq!(els[0], ArgValue::PrevRef { path: "id".into() });
1767                    }
1768                    other => panic!("expected inner Array, got {other:?}"),
1769                }
1770            }
1771            other => panic!("expected Object, got {other:?}"),
1772        }
1773    }
1774
1775    #[test]
1776    fn pure_json_array_folds_to_value() {
1777        // An array with no $prev refs should still produce ArgValue::Value(Array(...))
1778        let v = ops(r#"gtd.assign(title="x", depends_on=["a", "b"])"#);
1779        assert_eq!(val(&v[0].args["depends_on"]), &json!(["a", "b"]));
1780    }
1781
1782    #[test]
1783    fn pure_json_object_folds_to_value() {
1784        // An object with no $prev refs should still produce ArgValue::Value(Object(...))
1785        let v = ops(r#"gtd.assign(title="x", properties={"k": "v"})"#);
1786        assert_eq!(val(&v[0].args["properties"]), &json!({"k": "v"}));
1787    }
1788
1789    #[test]
1790    fn resolve_all_on_array_with_prev_ref() {
1791        let prev = json!({"full_id": "abc-def-123"});
1792        let arr = ArgValue::Array(vec![ArgValue::PrevRef {
1793            path: "full_id".into(),
1794        }]);
1795        assert_eq!(arr.resolve_all(&prev), Some(json!(["abc-def-123"])));
1796    }
1797
1798    #[test]
1799    fn resolve_all_on_mixed_array() {
1800        let prev = json!({"id": "x"});
1801        let arr = ArgValue::Array(vec![
1802            ArgValue::PrevRef { path: "id".into() },
1803            ArgValue::Value(json!("literal")),
1804        ]);
1805        assert_eq!(arr.resolve_all(&prev), Some(json!(["x", "literal"])));
1806    }
1807
1808    #[test]
1809    fn resolve_all_on_nested_object() {
1810        let prev = json!({"id": "obj-id"});
1811        let obj = ArgValue::Object(vec![(
1812            "refs".into(),
1813            ArgValue::Array(vec![ArgValue::PrevRef { path: "id".into() }]),
1814        )]);
1815        assert_eq!(obj.resolve_all(&prev), Some(json!({"refs": ["obj-id"]})));
1816    }
1817
1818    #[test]
1819    fn resolve_all_missing_path_returns_none() {
1820        let prev = json!({"id": "x"});
1821        let arr = ArgValue::Array(vec![ArgValue::PrevRef {
1822            path: "missing".into(),
1823        }]);
1824        assert_eq!(arr.resolve_all(&prev), None);
1825    }
1826
1827    // ── CC-3: Quoted "$prev.id" substitutes the same as unquoted $prev.id ─────
1828
1829    #[test]
1830    fn quoted_prev_ref_chain_parses_as_prev_ref() {
1831        // CC-3: `get(id="$prev.id")` must produce PrevRef, not Value("$prev.id").
1832        let r = req(r#"create(kind="concept", name="A") | get(id="$prev.id")"#);
1833        assert_eq!(r.mode, ExecutionMode::Chain);
1834        assert_eq!(r.ops[1].args["id"], ArgValue::PrevRef { path: "id".into() });
1835    }
1836
1837    #[test]
1838    fn quoted_bare_prev_ref_parses_as_prev_ref() {
1839        // CC-3: `"$prev"` (no path) must also promote.
1840        let r = req(r#"next() | update(id="$prev")"#);
1841        assert_eq!(r.mode, ExecutionMode::Chain);
1842        assert_eq!(r.ops[1].args["id"], ArgValue::PrevRef { path: "".into() });
1843    }
1844
1845    #[test]
1846    fn quoted_prev_ref_deep_path_parses_as_prev_ref() {
1847        // CC-3: `"$prev.result.id"` — multi-segment dotted quoted ref.
1848        let r = req(r#"create(kind="concept", name="A") | get(id="$prev.result.id")"#);
1849        assert_eq!(r.mode, ExecutionMode::Chain);
1850        assert_eq!(
1851            r.ops[1].args["id"],
1852            ArgValue::PrevRef {
1853                path: "result.id".into()
1854            }
1855        );
1856    }
1857
1858    #[test]
1859    fn escaped_dollar_prev_stays_literal() {
1860        // CC-3 escape (High-2 fix): `"\\$prev.id"` → the literal string `$prev.id`.
1861        // The DSL source `"\\$prev.id"` deserializes to `\$prev.id` (one backslash).
1862        // string_as_prev_ref strips the leading `\` and returns Value("$prev.id").
1863        let r = req(r#"create(kind="concept", name="A") | get(id="\\$prev.id")"#);
1864        assert_eq!(r.mode, ExecutionMode::Chain);
1865        // After stripping the escape marker the handler sees the clean literal.
1866        assert_eq!(r.ops[1].args["id"], ArgValue::Value(json!("$prev.id")));
1867    }
1868
1869    // ── ue-dsl-chain C1: JSON-form with $prev string is rejected clearly ──────
1870
1871    #[test]
1872    fn json_form_with_prev_ref_string_is_rejected() {
1873        // ue-dsl-chain C1: JSON form `[{...}, {"args":{"id":"$prev.id"}}]` must
1874        // be rejected with PrevRefInJsonForm, not silently passed through.
1875        let err = parse_request(
1876            r#"[{"tool":"create","args":{"kind":"concept","name":"A"}},{"tool":"get","args":{"id":"$prev.id"}}]"#,
1877        )
1878        .unwrap_err();
1879        assert!(
1880            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "id"),
1881            "expected PrevRefInJsonForm, got {err:?}"
1882        );
1883    }
1884
1885    #[test]
1886    fn json_form_with_bare_prev_string_is_rejected() {
1887        // ue-dsl-chain C1: bare `"$prev"` in JSON form is also rejected.
1888        let err = parse_request(r#"[{"tool":"get","args":{"id":"$prev"}}]"#).unwrap_err();
1889        assert!(
1890            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "id"),
1891            "expected PrevRefInJsonForm, got {err:?}"
1892        );
1893    }
1894
1895    #[test]
1896    fn json_form_without_prev_ref_still_works() {
1897        // ue-dsl-chain C1 guard: make sure normal JSON form is not broken.
1898        let r = req(r#"[{"tool":"next","args":{}}, {"tool":"complete","args":{"id":"abc"}}]"#);
1899        assert_eq!(r.mode, ExecutionMode::Parallel);
1900        assert_eq!(r.ops.len(), 2);
1901    }
1902
1903    // ── adr-dsl-packs H1: PrevRefOutsideChain emitted at parse time ───────────
1904
1905    #[test]
1906    fn prev_ref_in_single_op_is_rejected() {
1907        // adr-dsl-packs H1: `get(id=$prev.id)` without chain must be rejected.
1908        let err = parse_request(r#"get(id=$prev.id)"#).unwrap_err();
1909        assert!(
1910            matches!(err, DslError::PrevRefOutsideChain { .. }),
1911            "expected PrevRefOutsideChain, got {err:?}"
1912        );
1913    }
1914
1915    #[test]
1916    fn prev_ref_in_fn_batch_is_rejected() {
1917        // adr-dsl-packs H1: PrevRef inside `[create(...), get(id=$prev.id)]` is
1918        // parallel (no `|`) — must be rejected at parse time.
1919        let err =
1920            parse_request(r#"[create(kind="concept", name="A"), get(id=$prev.id)]"#).unwrap_err();
1921        assert!(
1922            matches!(err, DslError::PrevRefOutsideChain { .. }),
1923            "expected PrevRefOutsideChain, got {err:?}"
1924        );
1925    }
1926
1927    // ── adr-dsl-packs H3: MixedSeparators emitted at parse time ──────────────
1928
1929    #[test]
1930    fn mixed_separators_in_fn_batch_rejected() {
1931        // adr-dsl-packs H3: `[a() | b(), c()]` mixes `|` and `,` at top level.
1932        let err = parse_request("[a() | b(), c()]").unwrap_err();
1933        assert!(
1934            matches!(err, DslError::MixedSeparators),
1935            "expected MixedSeparators, got {err:?}"
1936        );
1937    }
1938
1939    #[test]
1940    fn mixed_separator_after_chain_rejected() {
1941        // adr-dsl-packs H3: `a() | b(), c()` mixes `|` chain with trailing `,`.
1942        let err = parse_request("a() | b(), c()").unwrap_err();
1943        assert!(
1944            matches!(err, DslError::MixedSeparators),
1945            "expected MixedSeparators, got {err:?}"
1946        );
1947    }
1948
1949    #[test]
1950    fn comma_only_parallel_accepted() {
1951        // adr-dsl-packs H3: `[a(), b(), c()]` is valid comma-only parallel batch.
1952        let req = parse_request("[a(), b(), c()]").unwrap();
1953        assert_eq!(req.mode, ExecutionMode::Parallel);
1954        assert_eq!(req.ops.len(), 3);
1955    }
1956
1957    #[test]
1958    fn pipe_only_chain_accepted() {
1959        // adr-dsl-packs H3: `a() | b() | c()` is valid pipe-only chain.
1960        let req = parse_request("a() | b() | c()").unwrap();
1961        assert_eq!(req.mode, ExecutionMode::Chain);
1962        assert_eq!(req.ops.len(), 3);
1963    }
1964
1965    // ── adr-dsl-packs H2: multi-segment dotted verb → clear error ─────────────
1966
1967    #[test]
1968    fn three_segment_verb_name_rejected() {
1969        // adr-dsl-packs H2: `brain.state.debug()` must produce UnsupportedVerbNesting,
1970        // not the misleading "expected '|' or end of input, found '.'".
1971        let err = parse_request("brain.state.debug()").unwrap_err();
1972        assert!(
1973            matches!(err, DslError::UnsupportedVerbNesting { .. }),
1974            "expected UnsupportedVerbNesting, got {err:?}"
1975        );
1976    }
1977
1978    // ── ue-dsl-chain H1: array indexing in $prev paths ────────────────────────
1979
1980    #[test]
1981    fn chain_prev_array_index_at_root() {
1982        // `$prev[0].id` — index at the root of a prev result.
1983        let r = req(r#"list(kind="concept") | get(id=$prev[0].id)"#);
1984        assert_eq!(r.mode, ExecutionMode::Chain);
1985        assert_eq!(
1986            r.ops[1].args["id"],
1987            ArgValue::PrevRef {
1988                path: "[0].id".into()
1989            }
1990        );
1991    }
1992
1993    #[test]
1994    fn chain_prev_array_index_nested() {
1995        // `$prev.items[2].name` — index inside a named field.
1996        let r = req(r#"list(kind="concept") | get(id=$prev.items[2].name)"#);
1997        assert_eq!(r.mode, ExecutionMode::Chain);
1998        assert_eq!(
1999            r.ops[1].args["id"],
2000            ArgValue::PrevRef {
2001                path: "items.[2].name".into()
2002            }
2003        );
2004    }
2005
2006    #[test]
2007    fn resolve_prev_array_index_at_root() {
2008        let prev = json!([{"id": "first"}, {"id": "second"}]);
2009        let r = ArgValue::PrevRef {
2010            path: "[0].id".into(),
2011        };
2012        assert_eq!(r.resolve_prev(&prev), Some(&json!("first")));
2013    }
2014
2015    #[test]
2016    fn resolve_prev_array_index_nested() {
2017        let prev = json!({"items": [{"name": "alpha"}, {"name": "beta"}]});
2018        let r = ArgValue::PrevRef {
2019            path: "items.[1].name".into(),
2020        };
2021        assert_eq!(r.resolve_prev(&prev), Some(&json!("beta")));
2022    }
2023
2024    #[test]
2025    fn resolve_prev_array_index_out_of_bounds_returns_none() {
2026        let prev = json!([{"id": "only"}]);
2027        let r = ArgValue::PrevRef {
2028            path: "[5].id".into(),
2029        };
2030        assert_eq!(r.resolve_prev(&prev), None);
2031    }
2032
2033    // ── CC-3 + H1: quoted prev ref with array index ───────────────────────────
2034
2035    #[test]
2036    fn quoted_prev_ref_with_array_index_parses() {
2037        // `"$prev[0].id"` quoted with bracket index should also promote.
2038        let r = req(r#"list(kind="concept") | get(id="$prev[0].id")"#);
2039        assert_eq!(r.mode, ExecutionMode::Chain);
2040        assert_eq!(
2041            r.ops[1].args["id"],
2042            ArgValue::PrevRef {
2043                path: "[0].id".into()
2044            }
2045        );
2046    }
2047
2048    // ── High-1 regression: JSON-form recursive $prev detection ───────────────
2049
2050    #[test]
2051    fn json_form_nested_array_with_prev_ref_is_rejected() {
2052        // High-1: `{"ids": ["$prev.id"]}` — $prev inside an array arg must be detected.
2053        let err = parse_request(
2054            r#"[{"tool":"create","args":{"kind":"concept","name":"A"}},{"tool":"search","args":{"ids":["$prev.id"]}}]"#,
2055        )
2056        .unwrap_err();
2057        assert!(
2058            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "ids"),
2059            "expected PrevRefInJsonForm for nested array, got {err:?}"
2060        );
2061    }
2062
2063    #[test]
2064    fn json_form_nested_object_with_prev_ref_is_rejected() {
2065        // High-1: `{"filter": {"id": "$prev.id"}}` — $prev inside an object arg must be detected.
2066        let err = parse_request(
2067            r#"[{"tool":"create","args":{"kind":"concept","name":"A"}},{"tool":"search","args":{"filter":{"id":"$prev.id"}}}]"#,
2068        )
2069        .unwrap_err();
2070        assert!(
2071            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "filter"),
2072            "expected PrevRefInJsonForm for nested object, got {err:?}"
2073        );
2074    }
2075
2076    #[test]
2077    fn json_form_bracket_prev_ref_is_rejected() {
2078        // High-1: `{"id": "$prev[0].id"}` — bracket-index form must also be detected.
2079        let err = parse_request(
2080            r#"[{"tool":"create","args":{"kind":"concept","name":"A"}},{"tool":"get","args":{"id":"$prev[0].id"}}]"#,
2081        )
2082        .unwrap_err();
2083        assert!(
2084            matches!(err, DslError::PrevRefInJsonForm { ref arg_name } if arg_name == "id"),
2085            "expected PrevRefInJsonForm for $prev[0].id, got {err:?}"
2086        );
2087    }
2088
2089    #[test]
2090    fn json_form_prevish_id_stays_literal() {
2091        // High-1 boundary: `$prevish.id` is NOT a $prev ref and must pass through.
2092        let r = req(r#"[{"tool":"get","args":{"id":"$prevish.id"}}]"#);
2093        assert_eq!(r.mode, ExecutionMode::Parallel);
2094        assert_eq!(r.ops[0].args["id"], ArgValue::Value(json!("$prevish.id")));
2095    }
2096
2097    // ── High-2 regression: escape semantics produce clean literal ────────────
2098
2099    #[test]
2100    fn escaped_dollar_prev_without_path_stays_literal() {
2101        // High-2: `"\\$prev"` → literal `$prev` (no path), not a PrevRef.
2102        let r = req(r#"create(kind="concept", name="A") | get(id="\\$prev")"#);
2103        assert_eq!(r.mode, ExecutionMode::Chain);
2104        assert_eq!(r.ops[1].args["id"], ArgValue::Value(json!("$prev")));
2105    }
2106
2107    #[test]
2108    fn escaped_dollar_prev_bracket_stays_literal() {
2109        // High-2: `"\\$prev[0].id"` → literal `$prev[0].id`, not a PrevRef.
2110        let r = req(r#"create(kind="concept", name="A") | get(id="\\$prev[0].id")"#);
2111        assert_eq!(r.mode, ExecutionMode::Chain);
2112        assert_eq!(r.ops[1].args["id"], ArgValue::Value(json!("$prev[0].id")));
2113    }
2114
2115    // ── Medium-1 regression: quoted bracket index validation ─────────────────
2116
2117    #[test]
2118    fn quoted_prev_ref_negative_index_treated_as_literal() {
2119        // Medium-1: `"$prev[-1].id"` — negative index is invalid in bracket grammar.
2120        // string_as_prev_ref returns None → stored as literal Value, not PrevRef.
2121        // In a chain, the value is a concrete string (no $prev substitution needed).
2122        let r = req(r#"list(kind="concept") | get(id="$prev[-1].id")"#);
2123        assert_eq!(r.mode, ExecutionMode::Chain);
2124        // Should be a Value (literal), NOT a PrevRef.
2125        assert!(
2126            matches!(r.ops[1].args["id"], ArgValue::Value(_)),
2127            "negative index quoted ref must be literal Value, not PrevRef; got {:?}",
2128            r.ops[1].args["id"]
2129        );
2130    }
2131
2132    #[test]
2133    fn quoted_prev_ref_missing_close_bracket_treated_as_literal() {
2134        // Medium-1: `"$prev[0.id"` — missing ']' is a malformed bracket.
2135        let r = req(r#"list(kind="concept") | get(id="$prev[0.id")"#);
2136        assert_eq!(r.mode, ExecutionMode::Chain);
2137        assert!(
2138            matches!(r.ops[1].args["id"], ArgValue::Value(_)),
2139            "unclosed bracket quoted ref must be literal Value, not PrevRef; got {:?}",
2140            r.ops[1].args["id"]
2141        );
2142    }
2143
2144    #[test]
2145    fn quoted_prev_ref_non_numeric_index_treated_as_literal() {
2146        // Medium-1: `"$prev[abc].id"` — non-numeric index is invalid.
2147        let r = req(r#"list(kind="concept") | get(id="$prev[abc].id")"#);
2148        assert_eq!(r.mode, ExecutionMode::Chain);
2149        assert!(
2150            matches!(r.ops[1].args["id"], ArgValue::Value(_)),
2151            "non-numeric bracket index quoted ref must be literal Value; got {:?}",
2152            r.ops[1].args["id"]
2153        );
2154    }
2155
2156    #[test]
2157    fn unquoted_negative_index_rejected_at_parse_time() {
2158        // Regression: unquoted `$prev[-1].id` — the `-` is not a digit, so the
2159        // digit-reader finds an empty index string and returns InvalidValue.
2160        let err = parse_request(r#"list(kind="concept") | get(id=$prev[-1].id)"#).unwrap_err();
2161        assert!(
2162            matches!(err, DslError::InvalidValue { .. }),
2163            "expected InvalidValue for negative index in unquoted ref, got {err:?}"
2164        );
2165    }
2166
2167    // ── ADR-038: write-key conflict detection ─────────────────────────────────
2168
2169    #[test]
2170    fn no_conflict_on_non_write_ops() {
2171        // search + list ops share no write keys; must pass.
2172        let r =
2173            parse_request(r#"[list(kind="entity"), search(kind="entity", query="x")]"#).unwrap();
2174        check_write_key_conflicts(&r).unwrap();
2175    }
2176
2177    #[test]
2178    fn update_and_delete_same_id_conflict() {
2179        // Two ops targeting the same UUID should be rejected.
2180        // Keys are substrate-prefixed: entity:<uuid>.
2181        let r =
2182            parse_request(r#"[update(id="abc-123", name="new"), delete(id="abc-123")]"#).unwrap();
2183        let err = check_write_key_conflicts(&r).unwrap_err();
2184        assert!(
2185            matches!(&err, DslError::WriteKeyConflict { id, first_op, second_op }
2186                if id == "entity:abc-123" && first_op == "update" && second_op == "delete"),
2187            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
2188        );
2189    }
2190
2191    #[test]
2192    fn two_updates_same_id_conflict() {
2193        let r = parse_request(
2194            r#"[update(id="uuid-1", name="a"), update(id="uuid-1", description="b")]"#,
2195        )
2196        .unwrap();
2197        let err = check_write_key_conflicts(&r).unwrap_err();
2198        assert!(
2199            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:uuid-1"),
2200            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
2201        );
2202    }
2203
2204    #[test]
2205    fn merge_from_id_conflicts_with_delete() {
2206        // merge's from_id overlaps a delete's id — both are entity writes.
2207        let r =
2208            parse_request(r#"[merge(into_id="new-id", from_id="old-id"), delete(id="old-id")]"#)
2209                .unwrap();
2210        let err = check_write_key_conflicts(&r).unwrap_err();
2211        assert!(
2212            matches!(&err, DslError::WriteKeyConflict { id, .. } if id == "entity:old-id"),
2213            "expected WriteKeyConflict with entity-prefixed key, got {err:?}"
2214        );
2215    }
2216
2217    #[test]
2218    fn different_ids_no_conflict() {
2219        // Each op has a distinct UUID; no conflict.
2220        let r = parse_request(
2221            r#"[update(id="id-1", name="a"), delete(id="id-2"), update(id="id-3", name="c")]"#,
2222        )
2223        .unwrap();
2224        check_write_key_conflicts(&r).unwrap();
2225    }
2226
2227    #[test]
2228    fn chain_mode_skips_conflict_detection() {
2229        // Chain ops run sequentially; write-key preflight is skipped.
2230        let r = parse_request(r#"update(id="same-id", name="a") | delete(id="same-id")"#).unwrap();
2231        assert_eq!(r.mode, ExecutionMode::Chain);
2232        // Must not return an error even though the same id appears in both ops.
2233        check_write_key_conflicts(&r).unwrap();
2234    }
2235
2236    #[test]
2237    fn link_source_id_does_not_conflict_with_entity_update() {
2238        // update(id="X") + link(source_id="X", ...) must NOT conflict — `link` writes an
2239        // edge record, not the entity at "X".  Substrate-prefixed keys distinguish them:
2240        // entity:X vs edge-natural:X:Y:rel.
2241        let r = parse_request(
2242            r#"[update(id="node-1", name="x"), link(source_id="node-1", target_id="node-2", relation="extends")]"#,
2243        )
2244        .unwrap();
2245        check_write_key_conflicts(&r).unwrap();
2246    }
2247
2248    #[test]
2249    fn two_links_same_natural_key_conflict() {
2250        // Two link ops targeting the same (source, target, relation) triple conflict
2251        // because they would produce duplicate edges.
2252        let r = parse_request(
2253            r#"[link(source_id="a", target_id="b", relation="extends"), link(source_id="a", target_id="b", relation="extends")]"#,
2254        )
2255        .unwrap();
2256        let err = check_write_key_conflicts(&r).unwrap_err();
2257        assert!(
2258            matches!(&err, DslError::WriteKeyConflict { id, .. }
2259                if id == "edge-natural:a:b:extends"),
2260            "expected WriteKeyConflict on edge-natural key, got {err:?}"
2261        );
2262    }
2263
2264    #[test]
2265    fn single_write_op_no_conflict() {
2266        let r = parse_request(r#"delete(id="solo-id")"#).unwrap();
2267        assert_eq!(r.mode, ExecutionMode::Single);
2268        check_write_key_conflicts(&r).unwrap();
2269    }
2270}