Skip to main content

oxdock_process/
expand.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use anyhow::{Result, anyhow, bail};
5
6use crate::contract::CommandContext;
7
8/// Maximum bytes to buffer while scanning for closing delimiter.
9/// If exceeded without finding closing delimiter, buffered bytes are flushed as literals.
10const MAX_PLACEHOLDER_SCAN: usize = 1024;
11
12/// Configurable delimiter syntax for template expansion.
13pub struct TemplateDelimiters {
14    pub open: &'static [u8],
15    pub close: &'static [u8],
16}
17
18impl Default for TemplateDelimiters {
19    fn default() -> Self {
20        Self {
21            open: b"{{",
22            close: b"}}",
23        }
24    }
25}
26
27/// Resolver for `{{ MODULE::FUNC(args) }}` placeholder calls.
28///
29/// Receives the module name, function name, and already resolved argument
30/// values, and returns the call result. Only pure value returning host
31/// functions may back this: no handles, no pipes, no I/O. The resolver
32/// carries no formatting logic; formatting lives with the function.
33pub type PlaceholderCall = Arc<
34    dyn Fn(&str, &str, Vec<oxdock_parser::Value>) -> Result<oxdock_parser::Value> + Send + Sync,
35>;
36
37/// Streaming template expansion state machine.
38///
39/// Processes input bytes incrementally, expanding `{{ env:KEY }}` placeholders.
40/// At most `MAX_PLACEHOLDER_SCAN` bytes are held in buffer. Plain text streams
41/// flush immediately with zero buffering.
42pub struct StreamingExpand {
43    /// Bytes accumulated as key payload inside `{{ ... }}` (no open delimiter prefix).
44    buffer: Vec<u8>,
45    /// Explicit key=value overrides (take precedence over env).
46    overrides: HashMap<String, String>,
47    /// Environment variable lookup.
48    env: HashMap<String, String>,
49    /// Structured variable lookup (for key-path evaluation).
50    vars: HashMap<String, oxdock_parser::Value>,
51    /// Optional dispatcher for `{{ MODULE::FUNC(args) }}` calls. When set,
52    /// placeholders holding a call expression are evaluated through it.
53    /// Carries dispatch only; formatting stays with the callee.
54    call_resolver: Option<PlaceholderCall>,
55    /// State: are we currently inside a placeholder?
56    in_placeholder: bool,
57    /// Trailing opening byte from previous chunk : deferred across chunks.
58    pending_brace: bool,
59    /// Trailing closing byte from previous chunk : deferred across chunks.
60    pending_close_brace: bool,
61    /// Trailing backslash from previous chunk : deferred across chunks so
62    /// `\{{` split across a boundary still emits a literal opener.
63    pending_escape: bool,
64    /// Trailing `\` + `{` from previous chunk : deferred across chunks so
65    /// a `\{` split across a boundary still resolves as an escape pair.
66    pending_escape_brace: bool,
67    /// Configurable delimiter syntax.
68    delimiters: TemplateDelimiters,
69}
70
71impl StreamingExpand {
72    /// Create with env vars and optional explicit overrides.
73    /// Overrides take precedence over env vars.
74    pub fn new(overrides: &[(String, String)], env: &HashMap<String, String>) -> Self {
75        Self {
76            buffer: Vec::with_capacity(256),
77            overrides: overrides.iter().cloned().collect(),
78            env: env.clone(),
79            vars: HashMap::new(),
80            call_resolver: None,
81            in_placeholder: false,
82            pending_brace: false,
83            pending_close_brace: false,
84            pending_escape: false,
85            pending_escape_brace: false,
86            delimiters: TemplateDelimiters::default(),
87        }
88    }
89
90    /// Create with env vars, structured variables, and optional explicit overrides.
91    /// Enables key-path evaluation in template tags (e.g., `{{ pkg.package.name }}`).
92    pub fn with_vars(mut self, vars: &HashMap<String, oxdock_parser::Value>) -> Self {
93        self.vars = vars.clone();
94        self
95    }
96
97    /// Enable `{{ MODULE::FUNC(args) }}` calls, dispatched through `resolver`.
98    /// Args are `$var.path` references, string, int, float, and bool
99    /// literals, or `{key: value}` and `[item]` literals nesting those
100    /// same shapes. Unknown functions and bad arity fail strict at expansion.
101    pub fn with_call_resolver(mut self, resolver: PlaceholderCall) -> Self {
102        self.call_resolver = Some(resolver);
103        self
104    }
105
106    /// Process a chunk of input bytes, writing expanded output to `out`.
107    /// Returns early on empty input to preserve pending boundary state.
108    pub fn process_bytes(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<usize> {
109        if input.is_empty() {
110            return Ok(0);
111        }
112
113        let start_len = out.len();
114        let mut i = 0;
115
116        // Handle pending close brace from previous chunk
117        if self.pending_close_brace {
118            self.pending_close_brace = false;
119            if input[0] == self.delimiters.close[1] {
120                // Confirmed close delimiter across boundary : extract key, lookup, emit
121                let key = extract_key(&self.buffer);
122                let value = lookup(
123                    &key,
124                    &self.overrides,
125                    &self.env,
126                    &self.vars,
127                    self.call_resolver.as_ref(),
128                )?;
129                out.extend_from_slice(value.as_bytes());
130                self.buffer.clear();
131                self.in_placeholder = false;
132                i = self.delimiters.close.len() - 1; // Skip input[0] (the second byte)
133            } else {
134                // Lone closing byte : treat as literal part of key
135                // Push it to buffer, then let scan_placeholder process input[0]
136                self.buffer.push(self.delimiters.close[0]);
137                i = 0; // Do NOT skip input[0]: let scan_placeholder handle it
138            }
139        }
140
141        // Handle pending open brace from previous chunk
142        if self.pending_brace {
143            self.pending_brace = false;
144            if input[0] == self.delimiters.open[1] {
145                // Confirmed `{{` across boundary : enter PlaceholderScan
146                self.in_placeholder = true;
147                self.buffer.clear();
148                i = 1; // Skip the second open byte
149            } else {
150                // Single open byte was just a literal : flush it
151                out.push(self.delimiters.open[0]);
152            }
153        }
154
155        // Handle pending escape pair from previous chunk: a trailing `\{`
156        // combines with a leading `{` into a literal opener. Anything
157        // else means both bytes were literal; re-emit them, then let the
158        // scan below handle this chunk from the start.
159        if self.pending_escape_brace {
160            self.pending_escape_brace = false;
161            if !input.is_empty() && input[0] == self.delimiters.open[1] {
162                out.extend_from_slice(b"{{");
163                i = 1;
164            } else {
165                out.push(b'\\');
166                out.push(self.delimiters.open[0]);
167            }
168        }
169
170        // Handle pending escape from previous chunk: a lone trailing `\`
171        // combines with a leading `{{` into a literal opener, or with a
172        // leading `\` into a literal backslash (the pair is complete, so
173        // whatever follows processes normally). A lone trailing `{`
174        // cannot decide yet, so it joins the deferred pair above.
175        if self.pending_escape {
176            self.pending_escape = false;
177            if input.len() >= 2 && input[0] == b'{' && input[1] == b'{' {
178                out.extend_from_slice(b"{{");
179                i = 2;
180            } else if input.len() == 1 && input[0] == self.delimiters.open[0] {
181                self.pending_escape_brace = true;
182                i = 1;
183            } else if !input.is_empty() && input[0] == b'\\' {
184                out.push(b'\\');
185                i = 1;
186            } else {
187                // Not an escape : the backslash was literal; reprocess
188                // this chunk from the start (a lone `{` still defers via
189                // the pending_brace path below).
190                out.push(b'\\');
191            }
192        }
193
194        if self.in_placeholder {
195            // We're inside a placeholder : scan for closing delimiter
196            i = self.scan_placeholder(input, i, out)?;
197        }
198
199        // Normal state : scan for opening byte or flush literals
200        while i < input.len() {
201            if input[i] == b'\\' {
202                if i + 2 < input.len() && input[i + 1] == b'{' && input[i + 2] == b'{' {
203                    // Escaped opener : emit a literal `{{`, consume all three
204                    out.extend_from_slice(b"{{");
205                    i += 3;
206                } else if i + 2 == input.len() && input[i + 1] == self.delimiters.open[0] {
207                    // `\{` ends the chunk : defer the pair; the next
208                    // chunk decides literal `{{` vs literal `\` + `{`.
209                    self.pending_escape_brace = true;
210                    i += 2;
211                } else if i + 1 < input.len() && input[i + 1] == b'\\' {
212                    // Escaped backslash : emit one `\`, consume both (this
213                    // keeps `\\{{ ... }}` expanding, matching the lenient
214                    // interpolator used for command arguments)
215                    out.push(b'\\');
216                    i += 2;
217                } else if i + 1 == input.len() {
218                    // Trailing backslash : defer across the chunk boundary
219                    self.pending_escape = true;
220                    i += 1;
221                } else {
222                    // Ordinary backslash : literal, reprocess what follows
223                    out.push(b'\\');
224                    i += 1;
225                }
226            } else if input[i] == self.delimiters.open[0] {
227                if i + 1 < input.len() && input[i + 1] == self.delimiters.open[1] {
228                    // Found open delimiter : enter PlaceholderScan
229                    self.in_placeholder = true;
230                    self.buffer.clear();
231                    i += 2;
232                    i = self.scan_placeholder(input, i, out)?;
233                } else if i + 1 == input.len() {
234                    // Opening byte is the LAST byte of chunk : defer
235                    self.pending_brace = true;
236                    i += 1;
237                } else {
238                    // Single opening byte in the middle : flush as literal
239                    out.push(self.delimiters.open[0]);
240                    i += 1;
241                }
242            } else {
243                // Flush literal bytes until we find an opening byte, a
244                // backslash (potential `\{{` escape), or end of chunk
245                let start = i;
246                while i < input.len() && input[i] != self.delimiters.open[0] && input[i] != b'\\' {
247                    i += 1;
248                }
249                out.extend_from_slice(&input[start..i]);
250            }
251        }
252
253        Ok(out.len() - start_len)
254    }
255
256    /// Flush remaining buffer. Incomplete placeholders are treated as literals.
257    pub fn flush(mut self, out: &mut Vec<u8>) -> Result<()> {
258        // Emit deferred closing byte if present
259        if self.pending_close_brace {
260            self.buffer.push(self.delimiters.close[0]);
261            self.pending_close_brace = false;
262        }
263        // Emit deferred opening byte if present
264        if self.pending_brace {
265            out.push(self.delimiters.open[0]);
266            self.pending_brace = false;
267        }
268        // Emit deferred backslash if present
269        if self.pending_escape {
270            out.push(b'\\');
271            self.pending_escape = false;
272        }
273        // Emit deferred escape pair if present
274        if self.pending_escape_brace {
275            out.push(b'\\');
276            out.push(self.delimiters.open[0]);
277            self.pending_escape_brace = false;
278        }
279        // If inside placeholder, emit open delimiter prefix ONCE before buffer
280        if self.in_placeholder {
281            out.extend_from_slice(self.delimiters.open);
282            self.in_placeholder = false;
283        }
284        // Flush remaining buffer as literal text
285        out.extend_from_slice(&self.buffer);
286        self.buffer.clear();
287        Ok(())
288    }
289
290    /// Process a complete string (convenience for short command arguments).
291    pub fn expand_string(self, input: &str) -> Result<String> {
292        let mut out = Vec::with_capacity(input.len());
293        let mut expander = self;
294        expander.process_bytes(input.as_bytes(), &mut out)?;
295        expander.flush(&mut out)?;
296        Ok(String::from_utf8(out).unwrap_or_default())
297    }
298
299    /// Scan for closing delimiter starting at position `i`.
300    /// Returns the next position to process after the placeholder.
301    fn scan_placeholder(&mut self, input: &[u8], mut i: usize, out: &mut Vec<u8>) -> Result<usize> {
302        while i < input.len() {
303            if input[i] == self.delimiters.close[0] {
304                if i + 1 < input.len() && input[i + 1] == self.delimiters.close[1] {
305                    // Found closing delimiter : extract key, lookup, emit expansion
306                    let key = extract_key(&self.buffer);
307                    let value = lookup(
308                        &key,
309                        &self.overrides,
310                        &self.env,
311                        &self.vars,
312                        self.call_resolver.as_ref(),
313                    )?;
314                    out.extend_from_slice(value.as_bytes());
315                    self.buffer.clear();
316                    self.in_placeholder = false;
317                    return Ok(i + 2);
318                }
319                if i + 1 == input.len() {
320                    // Closing byte is the LAST byte : defer to next chunk
321                    self.pending_close_brace = true;
322                    return Ok(i + 1);
323                }
324            }
325            self.buffer.push(input[i]);
326            i += 1;
327
328            // Buffer limit exceeded : flush as literal
329            if self.buffer.len() > MAX_PLACEHOLDER_SCAN {
330                out.extend_from_slice(self.delimiters.open);
331                out.extend_from_slice(&self.buffer);
332                self.buffer.clear();
333                self.in_placeholder = false;
334                return Ok(i);
335            }
336        }
337        Ok(i)
338    }
339}
340
341/// Extract and trim key from buffer content (the bytes between delimiters).
342fn extract_key(buffer: &[u8]) -> String {
343    String::from_utf8_lossy(buffer).trim().to_string()
344}
345
346/// Lookup a key in overrides and env, stripping namespace prefixes.
347///
348/// Strict resolution contract:
349/// - `{{ KEY }}` (bare) → overrides only
350/// - `{{ env:KEY }}` → overrides then env
351/// - `{{ $var }}` → script vars
352/// - `{{ $var.field }}` → script var key-path
353/// - `{{ MODULE::FUNC(args) }}` → placeholder call via `calls`
354///
355/// All missing or invalid references return an error.
356fn lookup(
357    raw_key: &str,
358    overrides: &HashMap<String, String>,
359    env: &HashMap<String, String>,
360    vars: &HashMap<String, oxdock_parser::Value>,
361    calls: Option<&PlaceholderCall>,
362) -> Result<String> {
363    use oxdock_parser::template::{PlaceholderKey, classify_placeholder_key, split_var_path};
364    let key = raw_key.trim();
365
366    // 1. Explicit overrides (command-level CLI flags: KEY=val)
367    if let Some(val) = overrides.get(key) {
368        return Ok(val.clone());
369    }
370
371    // Shapes below come from the single template owner: this keeps
372    // its own order (overrides first), sources, and errors.
373    match classify_placeholder_key(key) {
374        // 2. Environment variables: must be prefixed with "env:"
375        PlaceholderKey::Env(env_key) => {
376            // Trim once up front like the static gate and the
377            // script-engine expansion, so `{{ env: FOO }}` looks up
378            // `FOO` (never the padded spelling) on every layer.
379            let env_key = env_key.trim();
380            // Empty names bail explicitly (same message as the miss
381            // below) instead of relying on the lookup miss alone.
382            if env_key.is_empty() {
383                bail!("undefined environment variable: ''");
384            }
385            if let Some(val) = overrides.get(env_key).or_else(|| env.get(env_key)) {
386                return Ok(val.clone());
387            }
388            let hint = if vars.contains_key(env_key) {
389                format!("; did you mean '${env_key}' (script variable)?")
390            } else {
391                String::new()
392            };
393            bail!("undefined environment variable: '{env_key}'{hint}");
394        }
395
396        // 3. Script variables: must be prefixed with "$". Path split
397        // through the single template owner; dotted paths traverse
398        // strictly, plain names read directly.
399        PlaceholderKey::Dollar(rest) => {
400            let parts = split_var_path(rest);
401            if parts.len() == 1 {
402                if let Some(val) = vars.get(&parts[0]) {
403                    return format_value_for_string(val);
404                }
405                let hint = if env.contains_key(rest) {
406                    format!("; did you mean 'env:{rest}' (environment variable)?")
407                } else if overrides.contains_key(rest) {
408                    format!("; did you mean '{rest}' (step override)?")
409                } else {
410                    String::new()
411                };
412                bail!("undefined script variable: '${rest}'{hint}");
413            }
414            return resolve_key_path_strict(&parts, vars);
415        }
416
417        // 4. Placeholder calls: `MODULE::FUNC(args)` dispatches through
418        // the registered resolver. Without one, the shape falls through
419        // to the invalid placeholder error below. Bare heads are not
420        // resolvable here: they fail as invalid placeholders, never as
421        // missing keys.
422        PlaceholderKey::Call(call) => {
423            let Some(module) = call.module else {
424                // Bare `FUNC(...)` has no registry entry in override
425                // expansion: explicit invalid-format error, never silent
426                // fallthrough.
427                bail!(
428                    "invalid placeholder format '{key}': script variables must start with '$' and environment variables with 'env:'"
429                );
430            };
431            let (name, args_raw) = (call.name, call.args_raw);
432            let Some(resolver) = calls else {
433                bail!(
434                    "placeholder call '{module}::{name}' has no function registry; register one with with_call_resolver"
435                );
436            };
437            let args_src = oxdock_parser::template::split_placeholder_args(args_raw);
438            let mut args = Vec::with_capacity(args_src.len());
439            for src in args_src {
440                args.push(resolve_call_arg(&src, vars)?);
441            }
442            let result = resolver(module, name, args)?;
443            return format_value_for_string(&result);
444        }
445
446        // 5. Unprefixed key: could be a missing step override or invalid
447        // syntax. `script_env:` has no meaning in this context: it reads
448        // as invalid exactly like any other non-shape.
449        PlaceholderKey::Bare(name) => {
450            if !name.is_empty()
451                && name
452                    .chars()
453                    .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
454            {
455                let hint = if vars.contains_key(name) {
456                    format!("; did you mean '${name}' (script variable)?")
457                } else if env.contains_key(name) {
458                    format!("; did you mean 'env:{name}' (environment variable)?")
459                } else {
460                    String::new()
461                };
462                bail!("missing required step override argument: '{name}'{hint}");
463            }
464        }
465        PlaceholderKey::ScriptEnv(name) => {
466            // Empty names bail explicitly; non-empty `script_env:`
467            // has no meaning here and falls through to the invalid
468            // placeholder error below, as before.
469            if name.trim().is_empty() {
470                bail!("undefined environment variable: ''");
471            }
472        }
473        PlaceholderKey::Empty => {}
474    }
475    bail!(
476        "invalid placeholder format '{key}': script variables must start with '$' and environment variables with 'env:'"
477    );
478}
479
480/// Split a `MODULE::FUNC(args)` placeholder body for call resolution
481/// outside the streaming expander. Returns `None` when the body is not
482/// call shaped, so plain keys keep their own handling. Single grammar
483/// behind every phase: classifies through the shared
484/// `oxdock_parser::template::classify_placeholder_key`, so runtime
485/// dispatch and parse-time qualification can never disagree on what
486/// counts as one call.
487pub fn parse_placeholder_call(key: &str) -> Option<(String, String, Vec<String>)> {
488    use oxdock_parser::template::{PlaceholderKey, classify_placeholder_key};
489    let PlaceholderKey::Call(call) = classify_placeholder_key(key.trim()) else {
490        return None;
491    };
492    let module = call.module?.to_string();
493    let args = oxdock_parser::template::split_placeholder_args(call.args_raw);
494    Some((module, call.name.to_string(), args))
495}
496
497/// Maximum nesting for map and list literals in placeholder call
498/// args: the parser's shared argument depth budget.
499const MAX_LITERAL_DEPTH: usize = oxdock_parser::template::MAX_TEMPLATE_ARG_DEPTH;
500
501/// Resolve one placeholder call argument against script variables for
502/// call resolution outside the streaming expander. Same grammar there:
503/// `$var.path`, string, int, float, and bool literals, plus `{...}`
504/// and `[...]` literals holding those shapes nested.
505pub fn resolve_placeholder_arg(
506    src: &str,
507    vars: &HashMap<String, oxdock_parser::Value>,
508) -> Result<oxdock_parser::Value> {
509    resolve_call_arg(src, vars)
510}
511
512/// Resolve one call argument to a value: `$var.path` from vars, a
513/// string, int, float, or bool literal, or a `{key: value}` map or
514/// `[item]` list literal holding those same shapes nested.
515fn resolve_call_arg(
516    src: &str,
517    vars: &HashMap<String, oxdock_parser::Value>,
518) -> Result<oxdock_parser::Value> {
519    resolve_call_value(src, vars, 0)
520}
521
522fn resolve_call_value(
523    src: &str,
524    vars: &HashMap<String, oxdock_parser::Value>,
525    depth: usize,
526) -> Result<oxdock_parser::Value> {
527    use oxdock_parser::template::{
528        ScalarLit, TemplateArg, classify_template_arg, parse_scalar_literal, parse_string_literal,
529        parse_var_path,
530    };
531    if depth > MAX_LITERAL_DEPTH {
532        bail!("placeholder call argument nests too deep (limit {MAX_LITERAL_DEPTH})");
533    }
534    match classify_template_arg(src) {
535        TemplateArg::Dollar(rest) => {
536            let Some(parts) = parse_var_path(rest) else {
537                // `$` refs split through the single template owner; the
538                // empty check below keeps the historical
539                // malformed-argument error.
540                bail!("invalid placeholder call argument: empty variable reference");
541            };
542            return resolve_value_path(&parts, vars);
543        }
544        TemplateArg::Str(literal_src) => {
545            if let Some(literal) = parse_string_literal(literal_src) {
546                return literal.map(oxdock_parser::Value::string);
547            }
548        }
549        TemplateArg::Map(inner) => {
550            return resolve_call_map(inner, vars, depth);
551        }
552        TemplateArg::List(inner) => {
553            return resolve_call_list(inner, vars, depth);
554        }
555        TemplateArg::Scalar(scalar_src) => match parse_scalar_literal(scalar_src) {
556            Some(ScalarLit::Bool(value)) => return Ok(oxdock_parser::Value::bool(value)),
557            Some(ScalarLit::Int(value)) => return Ok(oxdock_parser::Value::int(value)),
558            Some(ScalarLit::Float(value)) => return Ok(oxdock_parser::Value::float(value)),
559            None => {}
560        },
561        TemplateArg::Invalid(_) => {}
562    }
563    bail!(
564        "invalid placeholder call argument '{src}': use $var.path, a string, int, float, or bool literal, or a {{key: value}} or [item] literal"
565    )
566}
567
568/// Resolve a `{key: value}` map literal. Keys validate through the
569/// shared key parser; values recurse through [`resolve_call_value`].
570fn resolve_call_map(
571    inner: &str,
572    vars: &HashMap<String, oxdock_parser::Value>,
573    depth: usize,
574) -> Result<oxdock_parser::Value> {
575    use oxdock_parser::template::{parse_map_key, split_map_entry, split_top_level};
576    let mut entries = std::collections::BTreeMap::new();
577    if inner.trim().is_empty() {
578        return Ok(oxdock_parser::Value::map(entries));
579    }
580    for entry in split_top_level(inner, ',') {
581        let Some((key_src, value_src)) = split_map_entry(&entry) else {
582            bail!("invalid map literal entry '{entry}': use key: value");
583        };
584        let key = parse_map_key(&key_src)?;
585        if entries.contains_key(&key) {
586            bail!("duplicate key '{key}' in map literal");
587        }
588        let value = resolve_call_value(&value_src, vars, depth + 1)?;
589        entries.insert(key, value);
590    }
591    Ok(oxdock_parser::Value::map(entries))
592}
593
594/// Resolve a `[item]` list literal, elements recursing through
595/// [`resolve_call_value`].
596fn resolve_call_list(
597    inner: &str,
598    vars: &HashMap<String, oxdock_parser::Value>,
599    depth: usize,
600) -> Result<oxdock_parser::Value> {
601    let mut items = Vec::new();
602    if inner.trim().is_empty() {
603        return Ok(oxdock_parser::Value::list(items));
604    }
605    for item in oxdock_parser::template::split_top_level(inner, ',') {
606        items.push(resolve_call_value(&item, vars, depth + 1)?);
607    }
608    Ok(oxdock_parser::Value::list(items))
609}
610
611/// Resolve a dotted path against vars, cloning the value for the caller.
612/// Mirrors `resolve_key_path_strict` but returns the value instead of
613/// its string form so calls receive typed arguments.
614fn resolve_value_path(
615    parts: &[String],
616    vars: &HashMap<String, oxdock_parser::Value>,
617) -> Result<oxdock_parser::Value> {
618    if parts.is_empty() || parts[0].is_empty() {
619        bail!("invalid placeholder call argument: empty variable reference");
620    }
621    let root_key = parts[0].as_str();
622    let mut current = vars
623        .get(root_key)
624        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?
625        .clone();
626    for segment in &parts[1..] {
627        if segment.contains('(') || segment.contains(')') {
628            bail!("nested calls are not supported in placeholder arguments");
629        }
630        if let Some(map) = current.as_map() {
631            current = map
632                .get(segment)
633                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?
634                .clone();
635        } else if let Some(list) = current.as_list() {
636            let idx: usize = segment
637                .parse()
638                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
639            current = list
640                .get(idx)
641                .ok_or_else(|| {
642                    anyhow!(
643                        "index {idx} out of bounds for list '${root_key}' (len: {})",
644                        list.len()
645                    )
646                })?
647                .clone();
648        } else {
649            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
650        }
651    }
652    Ok(current)
653}
654
655/// Resolve nested key-paths against the vars map.
656///
657/// Fails explicitly on missing object keys, out-of-bounds array indices,
658/// or type mismatches (e.g. trying to access a property on a primitive).
659fn resolve_key_path_strict(
660    parts: &[String],
661    vars: &HashMap<String, oxdock_parser::Value>,
662) -> Result<String> {
663    let root_key = parts[0].as_str();
664    let mut current = vars
665        .get(root_key)
666        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?;
667
668    for segment in &parts[1..] {
669        if let Some(map) = current.as_map() {
670            current = map
671                .get(segment)
672                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?;
673        } else if let Some(list) = current.as_list() {
674            let idx: usize = segment
675                .parse()
676                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
677            current = list.get(idx).ok_or_else(|| {
678                anyhow!(
679                    "index {idx} out of bounds for list '${root_key}' (len: {})",
680                    list.len()
681                )
682            })?;
683        } else {
684            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
685        }
686    }
687
688    format_value_for_string(current)
689}
690
691/// Format a Value as a string for inline interpolation.
692/// Render a script value as inline text: the single renderer behind
693/// placeholder expansion everywhere (streaming file templates and
694/// engine string expansion alike), so one value renders one way in
695/// every context. Pipes are refused: they carry streams between
696/// steps, not text, and silently rendering a handle hides a bug.
697///
698/// Float rendering is defined as `f.to_string()`: Rust's `Display` for
699/// `f64` already produces the shortest round-trip decimal (Ryū since
700/// 1.36), so `ECHO` / `{{ }}` output stays clean (`3.14`, not
701/// `3.140000`) with no extra dependency.
702pub fn format_value_for_string(val: &oxdock_parser::Value) -> anyhow::Result<String> {
703    if let Some(s) = val.as_str() {
704        return Ok(s.to_string());
705    }
706    if let Some(i) = val.as_i64() {
707        return Ok(i.to_string());
708    }
709    if let Some(f) = val.as_f64() {
710        return Ok(f.to_string());
711    }
712    if let Some(b) = val.as_bool() {
713        return Ok(b.to_string());
714    }
715    if val.as_pipe_handle().is_some() {
716        anyhow::bail!(
717            "cannot render PIPE as STRING: pipes carry streams between steps, not text. Capture the producing step's output with LET $var: STRING = ... instead."
718        );
719    }
720    if val.as_semaphore().is_some() {
721        anyhow::bail!(
722            "cannot render SEMAPHORE as STRING: semaphores coordinate task access between steps, not text."
723        );
724    }
725    if val.as_permit().is_some() {
726        anyhow::bail!(
727            "cannot render PERMIT as STRING: permits grant scoped task access, not text."
728        );
729    }
730    if let Some(d) = val.as_duration() {
731        return Ok(oxdock_parser::command::format_duration(&d));
732    }
733    if let Some(p) = val.as_path() {
734        return Ok(p.to_string_lossy().to_string());
735    }
736    if let Some(items) = val.as_list() {
737        let parts: Vec<String> = items
738            .iter()
739            .map(format_value_for_string)
740            .collect::<anyhow::Result<_>>()?;
741        return Ok(parts.join(" "));
742    }
743    if let Some(map) = val.as_map() {
744        let mut parts = Vec::with_capacity(map.len());
745        for (k, v) in map.iter() {
746            parts.push(format!("\"{}\": {}", k, format_value_for_string(v)?));
747        }
748        return Ok(parts.join(", "));
749    }
750    if let Some(id) = val.as_handle() {
751        return Ok(format!("task#{}", id));
752    }
753    Ok(format!("{}", val))
754}
755
756// Legacy functions for backward compatibility
757
758pub(crate) fn expand_with_lookup<F>(input: &str, mut lookup_fn: F) -> String
759where
760    F: FnMut(&str) -> Option<String>,
761{
762    let mut out = String::with_capacity(input.len());
763    let mut chars = input.chars().peekable();
764    while let Some(c) = chars.next() {
765        if c == '{' {
766            if let Some(&'{') = chars.peek() {
767                chars.next(); // consume second '{'
768                let mut content = String::new();
769                let mut closed = false;
770                // Look ahead for closing }}
771                let mut inner_chars = chars.clone();
772                while let Some(ch) = inner_chars.next() {
773                    if ch == '}'
774                        && let Some(&'}') = inner_chars.peek()
775                    {
776                        closed = true;
777                        break;
778                    }
779                    content.push(ch);
780                }
781
782                if closed {
783                    // Advance main iterator past content and closing braces.
784                    // Count chars, not bytes: content may contain multi-byte
785                    // UTF-8 (e.g. non-ASCII placeholder names).
786                    for _ in 0..content.chars().count() {
787                        chars.next();
788                    }
789                    chars.next(); // first }
790                    chars.next(); // second }
791
792                    let key = content.trim();
793                    if !key.is_empty() {
794                        out.push_str(&lookup_fn(key).unwrap_or_default());
795                    }
796                } else {
797                    out.push('{');
798                    out.push('{');
799                }
800            } else {
801                out.push('{');
802            }
803        } else {
804            out.push(c);
805        }
806    }
807    out
808}
809
810pub fn expand_script_env(input: &str, script_envs: &HashMap<String, String>) -> String {
811    expand_with_lookup(input, |name| {
812        if let Some(key) = name.strip_prefix("env:") {
813            script_envs
814                .get(key)
815                .cloned()
816                .or_else(|| std::env::var(key).ok())
817        } else {
818            None
819        }
820    })
821}
822
823pub fn expand_command_env(input: &str, ctx: &CommandContext) -> String {
824    expand_with_lookup(input, |name| {
825        if let Some(key) = name.strip_prefix("env:") {
826            ctx.envs().get(key).cloned()
827        } else {
828            None
829        }
830    })
831}
832
833#[cfg(test)]
834mod tests {
835    use super::*;
836    use std::collections::HashMap;
837
838    #[test]
839    fn basic_expansion() {
840        let mut env = HashMap::new();
841        env.insert("NAME".into(), "World".into());
842        let expander = StreamingExpand::new(&[], &env);
843        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
844        assert_eq!(result, "Hello World");
845    }
846
847    #[test]
848    fn multiple_vars() {
849        let mut env = HashMap::new();
850        env.insert("A".into(), "X".into());
851        env.insert("B".into(), "Y".into());
852        let expander = StreamingExpand::new(&[], &env);
853        let result = expander
854            .expand_string("{{ env:A }} and {{ env:B }}")
855            .unwrap();
856        assert_eq!(result, "X and Y");
857    }
858
859    #[test]
860    fn missing_var() {
861        let env = HashMap::new();
862        let expander = StreamingExpand::new(&[], &env);
863        let result = expander.expand_string("{{ env:MISSING }}");
864        assert!(result.is_err());
865        assert!(
866            result
867                .unwrap_err()
868                .to_string()
869                .contains("undefined environment variable"),
870            "error should mention undefined environment variable"
871        );
872    }
873
874    #[test]
875    fn spaced_env_name_resolves_trimmed() {
876        // `{{ env: FOO }}` looks up `FOO` on every layer: the lookup
877        // trims up front like the static gate and the script engine,
878        // instead of missing on the padded spelling.
879        let mut env = HashMap::new();
880        env.insert("FOO".into(), "bar".into());
881        let expander = StreamingExpand::new(&[], &env);
882        assert_eq!(expander.expand_string("{{ env: FOO }}").unwrap(), "bar");
883    }
884
885    #[test]
886    fn empty_env_names_bail() {
887        // Empty `env:` / `script_env:` names never interpolate empty:
888        // every layer rejects them, matching the static gate and the
889        // script-engine expansion.
890        let env = HashMap::new();
891        for text in ["{{ env: }}", "{{ script_env: }}", "{{ script_env:   }}"] {
892            let expander = StreamingExpand::new(&[], &env);
893            let result = expander.expand_string(text);
894            assert!(result.is_err(), "{text:?} must fail");
895        }
896    }
897
898    #[test]
899    fn no_placeholders() {
900        let env = HashMap::new();
901        let expander = StreamingExpand::new(&[], &env);
902        let result = expander.expand_string("plain text").unwrap();
903        assert_eq!(result, "plain text");
904    }
905
906    #[test]
907    fn empty_input() {
908        let env = HashMap::new();
909        let expander = StreamingExpand::new(&[], &env);
910        let result = expander.expand_string("").unwrap();
911        assert_eq!(result, "");
912    }
913
914    #[test]
915    fn override_precedence() {
916        let mut env = HashMap::new();
917        env.insert("KEY".into(), "envval".into());
918        let overrides = vec![("KEY".into(), "override".into())];
919        let expander = StreamingExpand::new(&overrides, &env);
920        let result = expander.expand_string("{{ env:KEY }}").unwrap();
921        assert_eq!(result, "override");
922    }
923
924    #[test]
925    fn override_with_namespace() {
926        let mut env = HashMap::new();
927        env.insert("CRATE".into(), "envval".into());
928        let overrides = vec![("CRATE".into(), "override".into())];
929        let expander = StreamingExpand::new(&overrides, &env);
930        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
931        assert_eq!(result, "override");
932    }
933
934    #[test]
935    fn override_raw_key_match() {
936        let mut env = HashMap::new();
937        env.insert("CRATE".into(), "envval".into());
938        let overrides = vec![("env:CRATE".into(), "override".into())];
939        let expander = StreamingExpand::new(&overrides, &env);
940        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
941        assert_eq!(result, "override");
942    }
943
944    #[test]
945    fn unclosed_placeholder() {
946        let env = HashMap::new();
947        let expander = StreamingExpand::new(&[], &env);
948        let result = expander.expand_string("{{ env:KEY").unwrap();
949        assert_eq!(result, "{{ env:KEY");
950    }
951
952    #[test]
953    fn unclosed_with_prefix() {
954        let env = HashMap::new();
955        let expander = StreamingExpand::new(&[], &env);
956        let result = expander.expand_string("Hello {{ env:KEY").unwrap();
957        assert_eq!(result, "Hello {{ env:KEY");
958    }
959
960    #[test]
961    fn buffer_limit_exceeded() {
962        let env = HashMap::new();
963        let expander = StreamingExpand::new(&[], &env);
964        // Create input with `{{` followed by >1024 bytes without `}}`
965        let mut input = b"{{ ".to_vec();
966        input.extend(std::iter::repeat_n(b'x', 2000));
967        let result = expander
968            .expand_string(&String::from_utf8_lossy(&input))
969            .unwrap();
970        // Should flush as literal with `{{` prefix
971        assert!(result.starts_with("{{ "));
972        assert!(result.len() > 1024);
973    }
974
975    #[test]
976    fn escaped_opener_emits_literal() {
977        let mut env = HashMap::new();
978        env.insert("PROJECT".into(), "OxDock".into());
979        let expander = StreamingExpand::new(&[], &env);
980        let result = expander
981            .expand_string("Built with \\{{ env:PROJECT }}")
982            .unwrap();
983        assert_eq!(result, "Built with {{ env:PROJECT }}");
984    }
985
986    /// Stub resolver echoing `upper` over one string arg, for call tests.
987    fn shout_resolver() -> PlaceholderCall {
988        Arc::new(|module, func, args| {
989            if module == "T" && func == "SHOUT" && args.len() == 1 {
990                let s = args[0]
991                    .as_str()
992                    .ok_or_else(|| anyhow!("SHOUT expects a string"))?;
993                return Ok(oxdock_parser::Value::string(s.to_uppercase()));
994            }
995            bail!("unknown placeholder function '{module}::{func}'")
996        })
997    }
998
999    #[test]
1000    fn placeholder_call_with_var_arg() {
1001        let env = HashMap::new();
1002        let mut vars = HashMap::new();
1003        vars.insert(
1004            "who".to_string(),
1005            oxdock_parser::Value::string("bob".to_string()),
1006        );
1007        let expander = StreamingExpand::new(&[], &env)
1008            .with_vars(&vars)
1009            .with_call_resolver(shout_resolver());
1010        let result = expander.expand_string("hi {{ T::SHOUT($who) }}!").unwrap();
1011        assert_eq!(result, "hi BOB!");
1012    }
1013
1014    #[test]
1015    fn placeholder_call_with_literal_args() {
1016        let env = HashMap::new();
1017        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1018        let result = expander
1019            .expand_string("{{ T::SHOUT(\"bob\") }} {{ T::SHOUT( \"ann\" ) }}")
1020            .unwrap();
1021        assert_eq!(result, "BOB ANN");
1022    }
1023
1024    #[test]
1025    fn placeholder_call_output_stays_literal() {
1026        // Call output containing `{{ }}` is terminal text, never re-expanded.
1027        let env = HashMap::new();
1028        let mut vars = HashMap::new();
1029        vars.insert(
1030            "any".to_string(),
1031            oxdock_parser::Value::string("v".to_string()),
1032        );
1033        let resolver: PlaceholderCall = Arc::new(|_, _, _| {
1034            Ok(oxdock_parser::Value::string(
1035                "x {{ env:NOPE }} y".to_string(),
1036            ))
1037        });
1038        let expander = StreamingExpand::new(&[], &env)
1039            .with_vars(&vars)
1040            .with_call_resolver(resolver);
1041        let result = expander.expand_string("{{ T::SHOUT($any) }}").unwrap();
1042        assert_eq!(result, "x {{ env:NOPE }} y");
1043    }
1044
1045    #[test]
1046    fn placeholder_call_unknown_function_fails() {
1047        let env = HashMap::new();
1048        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1049        let result = expander.expand_string("{{ T::NOPE($x) }}");
1050        assert!(result.is_err());
1051    }
1052
1053    #[test]
1054    fn placeholder_call_without_resolver_fails() {
1055        let env = HashMap::new();
1056        let expander = StreamingExpand::new(&[], &env);
1057        let result = expander.expand_string("{{ T::SHOUT($x) }}");
1058        assert!(result.is_err());
1059    }
1060
1061    #[test]
1062    fn escaped_opener_across_chunks() {
1063        let mut env = HashMap::new();
1064        env.insert("PROJECT".into(), "OxDock".into());
1065        let mut expander = StreamingExpand::new(&[], &env);
1066        let mut out = Vec::new();
1067
1068        // Split `\` / `{{ env:PROJECT }}` across chunks
1069        expander.process_bytes(b"Built with \\", &mut out).unwrap();
1070        expander
1071            .process_bytes(b"{{ env:PROJECT }}", &mut out)
1072            .unwrap();
1073        expander.flush(&mut out).unwrap();
1074
1075        assert_eq!(
1076            String::from_utf8_lossy(&out),
1077            "Built with {{ env:PROJECT }}"
1078        );
1079    }
1080
1081    #[test]
1082    fn double_backslash_then_placeholder_expands() {
1083        let mut env = HashMap::new();
1084        env.insert("PROJECT".into(), "OxDock".into());
1085        let expander = StreamingExpand::new(&[], &env);
1086        let result = expander.expand_string("\\\\{{ env:PROJECT }}").unwrap();
1087        assert_eq!(result, "\\OxDock");
1088    }
1089
1090    #[test]
1091    fn trailing_backslash_flushes_literal() {
1092        let env = HashMap::new();
1093        let expander = StreamingExpand::new(&[], &env);
1094        let result = expander.expand_string("end\\").unwrap();
1095        assert_eq!(result, "end\\");
1096    }
1097
1098    #[test]
1099    fn backslash_before_other_text_is_literal() {
1100        let env = HashMap::new();
1101        let expander = StreamingExpand::new(&[], &env);
1102        let result = expander.expand_string("a\\b \\{ once }").unwrap();
1103        assert_eq!(result, "a\\b \\{ once }");
1104    }
1105
1106    #[test]
1107    fn escaped_pair_split_across_chunks() {
1108        let mut env = HashMap::new();
1109        env.insert("PROJECT".into(), "OxDock".into());
1110        let mut expander = StreamingExpand::new(&[], &env);
1111        let mut out = Vec::new();
1112
1113        // Split `\\` / `{{ env:PROJECT }}` across chunks: the pair
1114        // completes to one backslash, then the placeholder expands
1115        expander.process_bytes(b"\\", &mut out).unwrap();
1116        expander
1117            .process_bytes(b"\\{{ env:PROJECT }}", &mut out)
1118            .unwrap();
1119        expander.flush(&mut out).unwrap();
1120
1121        assert_eq!(String::from_utf8_lossy(&out), "\\OxDock");
1122    }
1123
1124    #[test]
1125    fn partial_across_chunks() {
1126        let mut env = HashMap::new();
1127        env.insert("NAME".into(), "World".into());
1128        let mut expander = StreamingExpand::new(&[], &env);
1129        let mut out = Vec::new();
1130
1131        // Split `{{ env:NA` / `ME }}` across chunks
1132        expander.process_bytes(b"{{ env:NA", &mut out).unwrap();
1133        expander.process_bytes(b"ME }}", &mut out).unwrap();
1134        expander.flush(&mut out).unwrap();
1135
1136        assert_eq!(String::from_utf8_lossy(&out), "World");
1137    }
1138
1139    #[test]
1140    fn trailing_brace_across_chunks() {
1141        let mut env = HashMap::new();
1142        env.insert("NAME".into(), "World".into());
1143        let mut expander = StreamingExpand::new(&[], &env);
1144        let mut out = Vec::new();
1145
1146        // Split `...{` / `{env:NAME}}` across chunks
1147        expander.process_bytes(b"...", &mut out).unwrap();
1148        expander.process_bytes(b"{", &mut out).unwrap();
1149        expander.process_bytes(b"{env:NAME}}", &mut out).unwrap();
1150        expander.flush(&mut out).unwrap();
1151
1152        assert_eq!(String::from_utf8_lossy(&out), "...World");
1153    }
1154
1155    #[test]
1156    fn trailing_brace_at_eof() {
1157        let env = HashMap::new();
1158        let mut expander = StreamingExpand::new(&[], &env);
1159        let mut out = Vec::new();
1160
1161        expander.process_bytes(b"hello{", &mut out).unwrap();
1162        expander.flush(&mut out).unwrap();
1163
1164        assert_eq!(String::from_utf8_lossy(&out), "hello{");
1165    }
1166
1167    #[test]
1168    fn immediate_flush_guarantee() {
1169        let env = HashMap::new();
1170        let mut expander = StreamingExpand::new(&[], &env);
1171        let mut out = Vec::new();
1172
1173        // 1MB of plain text with no placeholders
1174        let input = std::iter::repeat_n(b'x', 1024 * 1024).collect::<Vec<_>>();
1175        expander.process_bytes(&input, &mut out).unwrap();
1176        expander.flush(&mut out).unwrap();
1177
1178        assert_eq!(out.len(), 1024 * 1024);
1179    }
1180
1181    #[test]
1182    fn nested_braces() {
1183        let mut env = HashMap::new();
1184        env.insert("KEY{1}".into(), "val".into());
1185        let expander = StreamingExpand::new(&[], &env);
1186        let result = expander.expand_string("{{ env:KEY{1} }}").unwrap();
1187        assert_eq!(result, "val");
1188    }
1189
1190    #[test]
1191    fn split_close_delimiter_across_chunks() {
1192        let mut env = HashMap::new();
1193        env.insert("NAME".into(), "World".into());
1194        let mut expander = StreamingExpand::new(&[], &env);
1195        let mut out = Vec::new();
1196
1197        // Split `}}` across chunks: `{{ env:NAME` / `}}`
1198        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1199        expander.process_bytes(b"}}", &mut out).unwrap();
1200        expander.flush(&mut out).unwrap();
1201
1202        assert_eq!(String::from_utf8_lossy(&out), "World");
1203    }
1204
1205    #[test]
1206    fn split_close_delimiter_with_trailing_content() {
1207        let mut env = HashMap::new();
1208        env.insert("NAME".into(), "World".into());
1209        let mut expander = StreamingExpand::new(&[], &env);
1210        let mut out = Vec::new();
1211
1212        // Split `}}` across chunks with content after
1213        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1214        expander.process_bytes(b"}} rest", &mut out).unwrap();
1215        expander.flush(&mut out).unwrap();
1216
1217        assert_eq!(String::from_utf8_lossy(&out), "World rest");
1218    }
1219
1220    #[test]
1221    fn empty_input_preserves_pending_state() {
1222        let mut env = HashMap::new();
1223        env.insert("NAME".into(), "World".into());
1224        let mut expander = StreamingExpand::new(&[], &env);
1225        let mut out = Vec::new();
1226
1227        // End chunk with closing byte, then empty input, then confirm
1228        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1229        expander.process_bytes(b"", &mut out).unwrap(); // empty: should preserve state
1230        expander.process_bytes(b"}}", &mut out).unwrap();
1231        expander.flush(&mut out).unwrap();
1232
1233        assert_eq!(String::from_utf8_lossy(&out), "World");
1234    }
1235
1236    #[test]
1237    fn missing_env_var_errors() {
1238        let env = HashMap::new();
1239        let expander = StreamingExpand::new(&[], &env);
1240        let result = expander.expand_string("{{ env:UNDEFINED_VAR }}");
1241        assert!(result.is_err());
1242        let msg = result.unwrap_err().to_string();
1243        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1244        assert!(msg.contains("UNDEFINED_VAR"), "got: {msg}");
1245    }
1246
1247    #[test]
1248    fn missing_script_var_errors() {
1249        let env = HashMap::new();
1250        let expander = StreamingExpand::new(&[], &env);
1251        let result = expander.expand_string("{{ $undefined_var }}");
1252        assert!(result.is_err());
1253        let msg = result.unwrap_err().to_string();
1254        assert!(msg.contains("undefined script variable"), "got: {msg}");
1255        assert!(msg.contains("$undefined_var"), "got: {msg}");
1256    }
1257
1258    #[test]
1259    fn missing_key_in_map_errors() {
1260        let mut vars = HashMap::new();
1261        vars.insert(
1262            "cfg".into(),
1263            oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1264                "server".into(),
1265                oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1266                    "port".into(),
1267                    oxdock_parser::Value::int(8080),
1268                )])),
1269            )])),
1270        );
1271        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1272        let result = expander.expand_string("{{ $cfg.missing_key }}");
1273        assert!(result.is_err());
1274        let msg = result.unwrap_err().to_string();
1275        assert!(
1276            msg.contains("property 'missing_key' not found"),
1277            "got: {msg}"
1278        );
1279    }
1280
1281    #[test]
1282    fn out_of_bounds_array_index_errors() {
1283        let mut vars = HashMap::new();
1284        vars.insert(
1285            "arr".into(),
1286            oxdock_parser::Value::list(vec![oxdock_parser::Value::string("a".into())]),
1287        );
1288        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1289        let result = expander.expand_string("{{ $arr.5 }}");
1290        assert!(result.is_err());
1291        let msg = result.unwrap_err().to_string();
1292        assert!(msg.contains("index 5 out of bounds"), "got: {msg}");
1293    }
1294
1295    #[test]
1296    fn type_mismatch_navigation_errors() {
1297        let mut vars = HashMap::new();
1298        vars.insert("name".into(), oxdock_parser::Value::string("alice".into()));
1299        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1300        let result = expander.expand_string("{{ $name.sub_field }}");
1301        assert!(result.is_err());
1302        let msg = result.unwrap_err().to_string();
1303        assert!(
1304            msg.contains("cannot access property 'sub_field' on primitive"),
1305            "got: {msg}"
1306        );
1307    }
1308
1309    #[test]
1310    fn unprefixed_identifier_errors() {
1311        let env = HashMap::new();
1312        let expander = StreamingExpand::new(&[], &env);
1313        let result = expander.expand_string("{{ bare_word }}");
1314        assert!(result.is_err());
1315        let msg = result.unwrap_err().to_string();
1316        assert!(msg.contains("missing required step override"), "got: {msg}");
1317    }
1318
1319    // ── Strict namespace isolation tests ─────────────────────────────────────
1320
1321    #[test]
1322    fn script_var_does_not_fall_back_to_env() {
1323        let mut env = HashMap::new();
1324        env.insert("WHO".into(), "from-env".into());
1325        let expander = StreamingExpand::new(&[], &env);
1326        // $WHO queries vars, NOT env : should error even though env has WHO
1327        let result = expander.expand_string("{{ $WHO }}");
1328        assert!(result.is_err());
1329        let msg = result.unwrap_err().to_string();
1330        assert!(msg.contains("undefined script variable"), "got: {msg}");
1331        assert!(
1332            msg.contains("did you mean 'env:WHO'"),
1333            "hint should suggest env: prefix, got: {msg}"
1334        );
1335    }
1336
1337    #[test]
1338    fn env_var_does_not_fall_back_to_vars() {
1339        let mut vars = HashMap::new();
1340        vars.insert(
1341            "HOST".into(),
1342            oxdock_parser::Value::string("from-var".into()),
1343        );
1344        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1345        // env:HOST queries env, NOT vars : should error even though vars has HOST
1346        let result = expander.expand_string("{{ env:HOST }}");
1347        assert!(result.is_err());
1348        let msg = result.unwrap_err().to_string();
1349        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1350        assert!(
1351            msg.contains("did you mean '$HOST'"),
1352            "hint should suggest $ prefix, got: {msg}"
1353        );
1354    }
1355
1356    #[test]
1357    fn step_override_does_not_fall_back_to_vars() {
1358        let mut vars = HashMap::new();
1359        vars.insert("PORT".into(), oxdock_parser::Value::int(8080));
1360        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1361        // PORT (bare) queries overrides, NOT vars : should error
1362        let result = expander.expand_string("{{ PORT }}");
1363        assert!(result.is_err());
1364        let msg = result.unwrap_err().to_string();
1365        assert!(msg.contains("missing required step override"), "got: {msg}");
1366        assert!(
1367            msg.contains("did you mean '$PORT'"),
1368            "hint should suggest $ prefix, got: {msg}"
1369        );
1370    }
1371
1372    #[test]
1373    fn env_prefix_isolated_from_script_vars() {
1374        let mut vars = HashMap::new();
1375        vars.insert("MODE".into(), oxdock_parser::Value::string("dev".into()));
1376        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1377        // env:MODE looks in env, not vars : should error
1378        let result = expander.expand_string("{{ env:MODE }}");
1379        assert!(result.is_err());
1380        let msg = result.unwrap_err().to_string();
1381        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1382        assert!(
1383            msg.contains("did you mean '$MODE'"),
1384            "hint should suggest $ prefix, got: {msg}"
1385        );
1386    }
1387
1388    #[test]
1389    fn dollar_prefix_isolated_from_env() {
1390        let mut env = HashMap::new();
1391        env.insert("PORT".into(), "3000".into());
1392        let expander = StreamingExpand::new(&[], &env);
1393        // $PORT looks in vars, not env : should error
1394        let result = expander.expand_string("{{ $PORT }}");
1395        assert!(result.is_err());
1396        let msg = result.unwrap_err().to_string();
1397        assert!(msg.contains("undefined script variable"), "got: {msg}");
1398        assert!(
1399            msg.contains("did you mean 'env:PORT'"),
1400            "hint should suggest env: prefix, got: {msg}"
1401        );
1402    }
1403
1404    #[test]
1405    fn empty_placeholder_errors() {
1406        let expander = StreamingExpand::new(&[], &HashMap::new());
1407        let result = expander.expand_string("{{ }}");
1408        assert!(result.is_err());
1409        let msg = result.unwrap_err().to_string();
1410        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1411    }
1412
1413    #[test]
1414    fn malformed_symbol_placeholder_errors() {
1415        let expander = StreamingExpand::new(&[], &HashMap::new());
1416        let result = expander.expand_string("{{ @invalid! }}");
1417        assert!(result.is_err());
1418        let msg = result.unwrap_err().to_string();
1419        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1420    }
1421
1422    #[test]
1423    fn bare_call_head_fails_as_invalid_placeholder() {
1424        // Directive 3: bare `FUNC(...)` has no registry entry in
1425        // override expansion. The `Call` arm handles `module == None`
1426        // explicitly instead of silently falling through.
1427        let expander = StreamingExpand::new(&[], &HashMap::new());
1428        let result = expander.expand_string("{{ FOO() }}");
1429        assert!(result.is_err());
1430        let msg = result.unwrap_err().to_string();
1431        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1432    }
1433
1434    /// Feed input in fixed-size chunks, then flush: exercises every
1435    /// chunk-boundary alignment for the given split size.
1436    fn render_split(
1437        input: &[u8],
1438        size: usize,
1439        env: &HashMap<String, String>,
1440    ) -> Result<String, anyhow::Error> {
1441        let mut expander = StreamingExpand::new(&[], env);
1442        let mut out = Vec::new();
1443        for chunk in input.chunks(size) {
1444            expander.process_bytes(chunk, &mut out)?;
1445        }
1446        expander.flush(&mut out)?;
1447        Ok(String::from_utf8_lossy(&out).into_owned())
1448    }
1449
1450    #[test]
1451    fn escaped_opener_one_byte_chunks_stays_literal() {
1452        let mut env = HashMap::new();
1453        env.insert("NAME".into(), "World".into());
1454        // Every byte arrives alone: `\` | `{` | `{` | ... must still
1455        // resolve to a literal opener, never an expansion.
1456        let out = render_split(b"\\{{ env:NAME }}", 1, &env).unwrap();
1457        assert_eq!(out, "{{ env:NAME }}");
1458    }
1459
1460    #[test]
1461    fn escaped_opener_two_byte_chunks_stays_literal() {
1462        let mut env = HashMap::new();
1463        env.insert("NAME".into(), "World".into());
1464        // Two-byte splits land `\{` and lone `{` at chunk ends.
1465        let out = render_split(b"a\\{{ env:NAME }}b", 2, &env).unwrap();
1466        assert_eq!(out, "a{{ env:NAME }}b");
1467    }
1468
1469    #[test]
1470    fn escaped_opener_split_variants_stay_literal() {
1471        let mut env = HashMap::new();
1472        env.insert("NAME".into(), "World".into());
1473        for chunks in [
1474            vec![b"\\".as_slice(), b"{", b"{ env:NAME }}"],
1475            vec![b"\\{".as_slice(), b"{ env:NAME }}"],
1476            vec![b"\\{{ env:NAME ".as_slice(), b"}}"],
1477        ] {
1478            let mut expander = StreamingExpand::new(&[], &env);
1479            let mut out = Vec::new();
1480            for chunk in chunks {
1481                expander.process_bytes(chunk, &mut out).unwrap();
1482            }
1483            expander.flush(&mut out).unwrap();
1484            assert_eq!(
1485                String::from_utf8_lossy(&out),
1486                "{{ env:NAME }}",
1487                "chunks must not corrupt the escape"
1488            );
1489        }
1490    }
1491
1492    #[test]
1493    fn plain_opener_split_chunks_still_expands() {
1494        let mut env = HashMap::new();
1495        env.insert("NAME".into(), "World".into());
1496        // The fix must not swallow genuine openers fragmented the
1497        // same way: `{` | `{` opens, then the key resolves.
1498        let out = render_split(b"{{ env:NAME }}", 1, &env).unwrap();
1499        assert_eq!(out, "World");
1500    }
1501
1502    #[test]
1503    fn double_backslash_split_chunks_still_expands() {
1504        let mut env = HashMap::new();
1505        env.insert("NAME".into(), "World".into());
1506        // `\\` completes to one backslash; the opener after it expands.
1507        let out = render_split(b"\\\\{{ env:NAME }}", 1, &env).unwrap();
1508        assert_eq!(out, "\\World");
1509    }
1510
1511    #[test]
1512    fn trailing_escape_brace_flushes_literal() {
1513        let env = HashMap::new();
1514        let expander = StreamingExpand::new(&[], &env);
1515        let result = expander.expand_string("end\\{").unwrap();
1516        assert_eq!(result, "end\\{");
1517    }
1518
1519    // ── Single-pass substitution tests ────────────────────────────────────
1520    // Substituted values are emitted verbatim and never re-scanned for
1521    // `{{ ... }}`. These pin the top-level-only behavior: a value that
1522    // itself contains a placeholder stays literal instead of expanding.
1523
1524    #[test]
1525    fn substituted_override_value_is_not_rescanned() {
1526        let mut env = HashMap::new();
1527        env.insert("OTHER".into(), "world".into());
1528        let overrides = vec![("NAME".into(), "{{ env:OTHER }}".into())];
1529        let expander = StreamingExpand::new(&overrides, &env);
1530        let result = expander.expand_string("Hello {{ NAME }}").unwrap();
1531        assert_eq!(result, "Hello {{ env:OTHER }}");
1532    }
1533
1534    #[test]
1535    fn substituted_env_value_is_not_rescanned() {
1536        let mut env = HashMap::new();
1537        env.insert("NAME".into(), "{{ env:OTHER }}".into());
1538        env.insert("OTHER".into(), "world".into());
1539        let expander = StreamingExpand::new(&[], &env);
1540        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
1541        assert_eq!(result, "Hello {{ env:OTHER }}");
1542    }
1543
1544    #[test]
1545    fn substituted_script_var_value_is_not_rescanned() {
1546        let mut vars = HashMap::new();
1547        vars.insert(
1548            "inner".into(),
1549            oxdock_parser::Value::string("{{ env:OTHER }}".into()),
1550        );
1551        let mut env = HashMap::new();
1552        env.insert("OTHER".into(), "world".into());
1553        let expander = StreamingExpand::new(&[], &env).with_vars(&vars);
1554        let result = expander.expand_string("Hello {{ $inner }}").unwrap();
1555        assert_eq!(result, "Hello {{ env:OTHER }}");
1556    }
1557
1558    /// Echo resolver returning the debug shape of each argument, so
1559    /// literal parsing asserts on values instead of formatting.
1560    fn shape_resolver() -> PlaceholderCall {
1561        Arc::new(|module, func, args| {
1562            if module == "T" && func == "SHAPE" {
1563                let shape = args
1564                    .iter()
1565                    .map(|arg| arg.type_name().to_string())
1566                    .collect::<Vec<_>>()
1567                    .join(",");
1568                return Ok(oxdock_parser::Value::string(shape));
1569            }
1570            bail!("unknown placeholder function '{module}::{func}'")
1571        })
1572    }
1573
1574    #[test]
1575    fn placeholder_call_with_empty_map_literal() {
1576        let expander =
1577            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1578        let result = expander.expand_string("{{ T::SHAPE({}) }}").unwrap();
1579        assert_eq!(result, "MAP");
1580    }
1581
1582    #[test]
1583    fn placeholder_call_with_map_and_list_literals() {
1584        let expander =
1585            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1586        let result = expander
1587            .expand_string("{{ T::SHAPE({a: 1, b: \"x\"}, [1, true]) }}")
1588            .unwrap();
1589        assert_eq!(result, "MAP,LIST");
1590    }
1591
1592    #[test]
1593    fn placeholder_call_map_commas_nest_inside_literals() {
1594        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1595            let map = args[0].as_map().expect("map");
1596            let format = map
1597                .get("format")
1598                .and_then(|v| v.as_str())
1599                .expect("format string");
1600            Ok(oxdock_parser::Value::string(format.to_string()))
1601        });
1602        let expander = StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(resolver);
1603        let result = expander
1604            .expand_string("{{ T::SHAPE({min_level: 2, format: \"a,b\"}) }}")
1605            .unwrap();
1606        assert_eq!(result, "a,b");
1607    }
1608
1609    #[test]
1610    fn placeholder_call_map_values_accept_var_refs_and_nesting() {
1611        let mut vars = HashMap::new();
1612        vars.insert("depth".into(), oxdock_parser::Value::int(2));
1613        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1614            let map = args[0].as_map().expect("map");
1615            let depth = map.get("n").and_then(|v| v.as_i64()).expect("int");
1616            let tags = map.get("tags").and_then(|v| v.as_list()).expect("list");
1617            Ok(oxdock_parser::Value::string(format!(
1618                "{depth}:{}",
1619                tags.len()
1620            )))
1621        });
1622        let expander = StreamingExpand::new(&[], &HashMap::new())
1623            .with_vars(&vars)
1624            .with_call_resolver(resolver);
1625        let result = expander
1626            .expand_string("{{ T::SHAPE({n: $depth, tags: [\"a\", \"b\"]}) }}")
1627            .unwrap();
1628        assert_eq!(result, "2:2");
1629    }
1630
1631    #[test]
1632    fn placeholder_call_rejects_malformed_literals() {
1633        for bad in [
1634            "{{ T::SHAPE({a}) }}",
1635            "{{ T::SHAPE({a: 1, a: 2}) }}",
1636            "{{ T::SHAPE({\"a\": 1: 2}) }}",
1637            "{{ T::SHAPE([1) }}",
1638            "{{ T::SHAPE({a: 1) }}",
1639        ] {
1640            let expander =
1641                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1642            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1643        }
1644    }
1645
1646    #[test]
1647    fn placeholder_call_rejects_adjacent_string_literals() {
1648        // Missing commas and infix expressions must fail, never merge
1649        // into one string.
1650        for bad in [
1651            "{{ T::SHAPE(\"a\" \"b\") }}",
1652            "{{ T::SHAPE(\"a\" + \"b\") }}",
1653            "{{ T::SHAPE(\"foo\\\") }}",
1654        ] {
1655            let expander =
1656                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1657            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1658        }
1659    }
1660
1661    #[test]
1662    fn placeholder_call_brackets_inside_block_strings_resolve() {
1663        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1664            let first = &args[0];
1665            if let Some(items) = first.as_list() {
1666                return Ok(oxdock_parser::Value::string(
1667                    items[0].as_str().unwrap_or("?").to_string(),
1668                ));
1669            }
1670            if let Some(entries) = first.as_map() {
1671                return Ok(oxdock_parser::Value::string(
1672                    entries
1673                        .get("k")
1674                        .and_then(|v| v.as_str())
1675                        .unwrap_or("?")
1676                        .to_string(),
1677                ));
1678            }
1679            bail!("expected list or map")
1680        });
1681        let list = StreamingExpand::new(&[], &HashMap::new())
1682            .with_call_resolver(resolver.clone())
1683            .expand_string("{{ T::ECHO([\"\"\"a]b\"\"\"]) }}")
1684            .unwrap();
1685        assert_eq!(list, "a]b");
1686        let map = StreamingExpand::new(&[], &HashMap::new())
1687            .with_call_resolver(resolver.clone())
1688            .expand_string("{{ T::ECHO({k: \"\"\"a}b\"\"\"}) }}")
1689            .unwrap();
1690        assert_eq!(map, "a}b");
1691    }
1692
1693    #[test]
1694    fn placeholder_call_single_quotes_match_double_quotes() {
1695        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1696            Ok(oxdock_parser::Value::string(
1697                args.iter()
1698                    .map(|a| a.as_str().unwrap_or("?").to_string())
1699                    .collect::<Vec<_>>()
1700                    .join("|"),
1701            ))
1702        });
1703        for (double, single) in [
1704            ("{{ T::ECHO(\"hi\") }}", "{{ T::ECHO('hi') }}"),
1705            ("{{ T::ECHO(\"a,b\") }}", "{{ T::ECHO('a,b') }}"),
1706            ("{{ T::ECHO({k: \"v\"}) }}", "{{ T::ECHO({k: 'v'}) }}"),
1707            ("{{ T::ECHO({\"k\": \"v\"}) }}", "{{ T::ECHO({'k': 'v'}) }}"),
1708            ("{{ T::ECHO([\"a\"]) }}", "{{ T::ECHO(['a']) }}"),
1709        ] {
1710            let left = StreamingExpand::new(&[], &HashMap::new())
1711                .with_call_resolver(resolver.clone())
1712                .expand_string(double)
1713                .unwrap();
1714            let right = StreamingExpand::new(&[], &HashMap::new())
1715                .with_call_resolver(resolver.clone())
1716                .expand_string(single)
1717                .unwrap();
1718            assert_eq!(
1719                left, right,
1720                "quote style must not matter: {double} vs {single}"
1721            );
1722        }
1723    }
1724
1725    #[test]
1726    fn placeholder_call_triple_quoted_matches_single_line() {
1727        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1728            Ok(oxdock_parser::Value::string(
1729                args[0].as_str().unwrap_or("?").to_string(),
1730            ))
1731        });
1732        let plain = StreamingExpand::new(&[], &HashMap::new())
1733            .with_call_resolver(resolver.clone())
1734            .expand_string("{{ T::ECHO(\"Release installs\") }}")
1735            .unwrap();
1736        let block = StreamingExpand::new(&[], &HashMap::new())
1737            .with_call_resolver(resolver.clone())
1738            .expand_string("{{ T::ECHO(\"\"\"Release installs\"\"\") }}")
1739            .unwrap();
1740        assert_eq!(plain, block);
1741    }
1742}