Skip to main content

oxdock_core/exec/
native.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_func_macro::oxdock_func;
6use oxdock_parser::value::HandleValue;
7use oxdock_parser::{
8    Field, GuardExpr, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step,
9    TypeTag, Value, base_name, guards_overlap, qualify, render_structural, split_qualified,
10};
11use oxdock_pipe::PipeHandle;
12use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
13
14use super::io::StreamHandle;
15use super::state::ExecState;
16use super::steps::StepCtx;
17use super::typing::TypeDescriptor;
18
19/// Origin of a callable in the unified function registry. `Script` is an
20/// interpreted `FUNC` body; `HostCtx` and `HostPure` are compiled Rust
21/// functions (the `#[oxdock_func]` host export macro). Builtins and
22/// runtime-registered hosts share the host kinds; only `DESCRIBE` output
23/// shows the label, and both host kinds keep rendering as `host`.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum FuncKind {
26    Script,
27    HostCtx,
28    HostPure,
29}
30
31/// Canonical registry key for a file-imported script function:
32/// defining file plus base name, through the shared [`qualify`]
33/// owner. Importer aliases never appear here.
34pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
35    qualify(defining_file, name)
36}
37
38/// Loud ambiguity error for one unit importing the same alias from
39/// several files. `files` sorts for deterministic rendering.
40pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
41    let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
42    files.sort();
43    format!(
44        "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
45        files.join(", ")
46    )
47}
48
49/// One `ALIAS::FUNC` spelling's fate under a unit's alias targets.
50/// Single owner for alias-target matching: every resolution path
51/// (static calls, template gates, runtime dispatch, placeholder
52/// misses, snapshots, re-exports) classifies here and acts on the
53/// result, never restating the singleton/ambiguity branches.
54pub(super) enum AliasResolution {
55    /// Resolve as spelled (bare, `SCRIPT::`, hosts, unknown-to-unit).
56    Global,
57    /// Canonical defining-file key.
58    Canonical(String),
59    /// Known alias with no usable target: the caller reports unknown.
60    Unknown,
61    /// One alias, several files with the name in overlapping guards:
62    /// fail loud, naming the colliding spelling.
63    Ambiguous {
64        alias: String,
65        base: String,
66        files: HashSet<String>,
67    },
68    /// Several files hold the name under disjoint guards: the caller
69    /// validates every target instead of failing outright
70    /// (platform-conditional imports). `has_host` marks a disjoint
71    /// host-harvest branch (a `(None, guard)` target) alongside the
72    /// files: that branch holds no file functions, so any file-backed
73    /// call misses there.
74    Any {
75        base: String,
76        files: HashSet<String>,
77        has_host: bool,
78    },
79}
80
81/// One unit's alias targets: defining file plus the import's guard.
82/// Single owner for the target-set shape; static and runtime tables
83/// share it. Guards decide ambiguity (overlapping guards importing
84/// different files under one alias are ambiguous); unguarded imports
85/// overlap everything. Runtime records `None` (its imports execute
86/// once taken).
87pub(super) type AliasTargets = HashMap<String, Vec<(Option<String>, Option<GuardExpr>)>>;
88
89/// Classify one call spelling under a unit's alias targets. Single
90/// entry point for alias-target matching: splits the spelling,
91/// resolves `SCRIPT::` and bare names globally, and maps file aliases
92/// through the unit's recorded targets. `exists` probes the caller's
93/// function map for a canonical key.
94pub(super) fn classify_alias_call(
95    unit_targets: &AliasTargets,
96    name: &str,
97    exists: &dyn Fn(&str) -> bool,
98) -> AliasResolution {
99    let Some((alias, base)) = name.split_once("::") else {
100        return AliasResolution::Global;
101    };
102    if alias == SCRIPT_MODULE_NAME {
103        return AliasResolution::Global;
104    }
105    let Some(entries) = unit_targets.get(alias) else {
106        return AliasResolution::Global;
107    };
108    if entries.is_empty() {
109        return AliasResolution::Unknown;
110    }
111    // Distinct defining files in first-seen order; `(None, guard)`
112    // entries are host-harvest branches holding no file functions.
113    let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
114    let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
115    for (file, guard) in entries {
116        match file {
117            Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
118                Some((_, guards)) => guards.push(guard.as_ref()),
119                None => files.push((path, vec![guard.as_ref()])),
120            },
121            None => host_guards.push(guard.as_ref()),
122        }
123    }
124    if files.is_empty() {
125        return AliasResolution::Unknown;
126    }
127    let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
128        left.iter()
129            .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
130    };
131    if files.len() == 1 {
132        // A lone file target stays canonical unless a host-harvest
133        // branch is disjoint from it: on that platform the alias
134        // holds no file function, so the call misses there.
135        let disjoint_host = host_guards
136            .iter()
137            .any(|host| !overlaps(&files[0].1, &[*host]));
138        if !disjoint_host {
139            return AliasResolution::Canonical(file_func_key(files[0].0, base));
140        }
141        let mut all = HashSet::new();
142        all.insert(files[0].0.to_string());
143        return AliasResolution::Any {
144            base: base.to_string(),
145            files: all,
146            has_host: true,
147        };
148    }
149    let mut ambiguous = HashSet::new();
150    for (i, (file, guards)) in files.iter().enumerate() {
151        for (other, other_guards) in files.iter().skip(i + 1) {
152            if overlaps(guards, other_guards)
153                && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
154            {
155                ambiguous.insert((*file).to_string());
156                ambiguous.insert((*other).to_string());
157            }
158        }
159    }
160    if !ambiguous.is_empty() {
161        return AliasResolution::Ambiguous {
162            alias: alias.to_string(),
163            base: base.to_string(),
164            files: ambiguous,
165        };
166    }
167    let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
168    if all.iter().any(|file| exists(&file_func_key(file, base))) {
169        return AliasResolution::Any {
170            base: base.to_string(),
171            files: all,
172            has_host: !host_guards.is_empty(),
173        };
174    }
175    AliasResolution::Unknown
176}
177
178/// Whether a disjoint-alias template call names a script function,
179/// owned here so every placeholder path agrees with `resolve_call`:
180/// visible only when no host-harvest branch competes (`!has_host`)
181/// and **every** candidate file defines `base` (universal, not
182/// existential: a missing branch fails the `LET` path, so the
183/// template must not suggest it). `exists` probes canonical
184/// file-function keys for script definitions.
185pub(super) fn disjoint_template_script_visible(
186    base: &str,
187    files: &HashSet<String>,
188    has_host: bool,
189    exists: &dyn Fn(&str) -> bool,
190) -> bool {
191    !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
192}
193
194/// Miss wording for a disjoint-alias placeholder call, shared by the
195/// static gate, the lazy runtime path, and (via the script set) the
196/// EXPAND snapshot. Script-visible branches read as script misses
197/// (the `LET` path); otherwise the alias is known but holds no
198/// callable function here. Always renders: `Any` only arises for a
199/// known alias, so the generic unknown wording never applies.
200pub(super) fn disjoint_alias_placeholder_miss(
201    module: &str,
202    name: &str,
203    base: &str,
204    files: &HashSet<String>,
205    has_host: bool,
206    is_script: &dyn Fn(&str) -> bool,
207) -> String {
208    let script = disjoint_template_script_visible(base, files, has_host, is_script);
209    describe_placeholder_miss(module, name, script, false, !script)
210        .expect("disjoint miss always renders")
211}
212
213/// Every local spelling of one defining file's function in a unit.
214/// Inverted direction of [`classify_alias_call`]; shares its matcher.
215/// `is_script` probes the caller's registry for script bodies, so
216/// disjoint platform aliases covering every branch with a script
217/// definition read as direct spellings (matching the static gate and
218/// the lazy path through [`disjoint_alias_placeholder_miss`]).
219pub(super) fn spellings_for_defining_file(
220    unit_targets: &AliasTargets,
221    defining: &str,
222    base: &str,
223    is_script: &dyn Fn(&str) -> bool,
224) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
225    let mut direct = Vec::new();
226    let mut ambiguous = Vec::new();
227    for (alias, files) in unit_targets {
228        if !files
229            .iter()
230            .any(|(file, _)| file.as_deref() == Some(defining))
231        {
232            continue;
233        }
234        let spelling = qualify(alias, base);
235        match classify_alias_call(unit_targets, &spelling, &|key| {
236            key == file_func_key(defining, base)
237        }) {
238            AliasResolution::Canonical(_) => direct.push(spelling),
239            AliasResolution::Ambiguous { files, .. } => {
240                ambiguous.push((spelling, files));
241            }
242            AliasResolution::Any {
243                base,
244                files,
245                has_host,
246            } => {
247                if disjoint_template_script_visible(&base, &files, has_host, is_script) {
248                    direct.push(spelling);
249                }
250            }
251            AliasResolution::Global | AliasResolution::Unknown => {}
252        }
253    }
254    (direct, ambiguous)
255}
256
257impl FuncKind {
258    pub fn label(&self) -> &'static str {
259        match self {
260            FuncKind::Script => "script",
261            FuncKind::HostCtx | FuncKind::HostPure => "host",
262        }
263    }
264}
265
266/// One declared parameter of a registered function. `param_type` is `None`
267/// for unconstrained `Value` parameters (the macro accepts any value).
268/// `allowed` names the closed value set for constrained `STRING`
269/// parameters, declared once via `#[values(...)]`: the generated
270/// extractor enforces membership and the reference renders the set,
271/// so the list cannot rot apart from the check. `docs` carries the
272/// parameter's description (parsed from the `# Arguments` doc section
273/// for macro functions, written inline for hand-built entries) and
274/// renders into every reference surface. `options` declares the known
275/// keys of a `MAP` options parameter: same single-source rule as
276/// `allowed`, with per-key types, required flags, defaults, and docs.
277/// `optional` marks a trailing `MAP` parameter callers may omit: the
278/// runtime fills an empty MAP, and signatures render `= {}`. Only
279/// trailing `MAP` params may be optional (run-start validation
280/// rejects anything else), so omission always means "no options".
281/// The macro never emits optional params: only hand-built entries
282/// use them, and only for options MAPs.
283#[derive(Debug, Clone)]
284pub struct FuncParam {
285    pub name: String,
286    pub param_type: Option<TypeTag>,
287    pub allowed: Option<&'static [&'static str]>,
288    pub docs: &'static str,
289    pub options: Option<&'static [ParamOption]>,
290    pub optional: bool,
291}
292
293/// Required argument count: total params minus trailing optionals.
294/// Callers may pass any count in `required..=total`; omitted trailing
295/// MAPs fill with an empty MAP. Shared by the static arity gate and
296/// the runtime gate so the two can never disagree.
297pub fn required_arity(params: &[FuncParam]) -> usize {
298    params
299        .iter()
300        .rev()
301        .take_while(|param| param.optional)
302        .fold(params.len(), |count, _| count - 1)
303}
304
305/// Fill omitted trailing optional MAP params with empty MAPs. The
306/// caller guarantees `values.len()` is within
307/// `required_arity(params)..=params.len()`; anything else is a bug,
308/// not a user error, so over- and under-counts panic loudly.
309pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
310    assert!(
311        values.len() <= params.len(),
312        "arity gate must run before fill_optional_args"
313    );
314    assert!(
315        values.len() >= required_arity(params),
316        "arity gate must run before fill_optional_args"
317    );
318    while values.len() < params.len() {
319        values.push(Value::map(BTreeMap::new()));
320    }
321    values
322}
323
324/// One known key of a `MAP` options parameter: name, value type,
325/// whether callers must pass it, the rendered default for optional
326/// keys, and what it controls. Declared once per options parameter
327/// (macro `#[options(...)]` plus the `# Options` doc section, or
328/// inline for hand-built entries) and rendered into signatures,
329/// `DESCRIBE` output, and generated references alike.
330#[derive(Debug, Clone)]
331pub struct ParamOption {
332    pub name: &'static str,
333    pub value: TypeTag,
334    pub required: bool,
335    pub default: Option<&'static str>,
336}
337
338/// Introspectable metadata for one function. Single source for
339/// `DESCRIBE(name)` output and the static function reference. `rpn` names
340/// whether the function also runs on the compiled math path (`true` for
341/// pure functions and opted-in stateful ones); everything runs on the AST
342/// path.
343#[derive(Debug, Clone)]
344pub struct FuncMeta {
345    pub name: String,
346    /// Owning module (`STD` for builtins, `SCRIPT` for DSL definitions,
347    /// the host module name otherwise). `name` is always the qualified
348    /// `MODULE::BASE` form, so listings and `DESCRIBE` never lose origin.
349    pub module: String,
350    pub kind: FuncKind,
351    pub params: Option<Vec<FuncParam>>,
352    pub returns: Option<TypeTag>,
353    pub rpn: bool,
354    pub summary: &'static str,
355    pub docs: &'static str,
356    /// Executable examples, rendered as ```oxdock fences into the
357    /// generated reference and executed by docs_conformance like
358    /// command examples. The single precondition mechanism: the
359    /// returns gate executes these blocks to cover functions blind
360    /// sampling cannot reach.
361    pub examples: &'static [crate::Example],
362}
363
364/// Pure scalar function: no filesystem, no scope, no process access.
365/// Usable from both AST evaluation and compiled RPN math.
366pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
367
368/// Stateful/IO function with full step context (fs, cwd, envs, vars, pipes).
369pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
370
371/// Export hook for a DSL function, implemented by `#[oxdock_func]` on a
372/// registration marker. The engine calls `registration()` and never names
373/// a generated symbol.
374pub trait OxDockFn<P: ProcessManager> {
375    /// The registry entry deriving from the Rust signature plus doc
376    /// comments: name, metadata, and entry point, rendered.
377    fn registration() -> HostRegistration<P>;
378}
379
380/// One host-registered function, grouped into a [`HostModule`] and passed
381/// to `Engine::register_module`. Build the entry with the `#[oxdock_func]`-
382/// generated registration marker, or by hand. `Pure` entries run
383/// on both the AST and the compiled RPN math paths; `Stateful` entries run
384/// on the AST path with full step context. `Both` entries carry a stateful
385/// body plus a pure string projection: every context with step IO runs
386/// the body, while `{{ }}` placeholder expansion (which has no step
387/// context) runs the projection.
388pub enum HostRegistration<P: ProcessManager> {
389    Stateful {
390        name: String,
391        meta: FuncMeta,
392        func: NativeFn<P>,
393    },
394    Pure {
395        name: String,
396        meta: FuncMeta,
397        func: PureFn,
398    },
399    Both {
400        name: String,
401        meta: FuncMeta,
402        func: NativeFn<P>,
403        template: PureFn,
404    },
405}
406
407// Manual `Clone` (a derive would demand `P: Clone`): entries share their
408// function pointers through the `Arc`s and deep-copy the metadata.
409impl<P: ProcessManager> Clone for HostRegistration<P> {
410    fn clone(&self) -> Self {
411        match self {
412            HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
413                name: name.clone(),
414                meta: meta.clone(),
415                func: Arc::clone(func),
416            },
417            HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
418                name: name.clone(),
419                meta: meta.clone(),
420                func: Arc::clone(func),
421            },
422            HostRegistration::Both {
423                name,
424                meta,
425                func,
426                template,
427            } => HostRegistration::Both {
428                name: name.clone(),
429                meta: meta.clone(),
430                func: Arc::clone(func),
431                template: Arc::clone(template),
432            },
433        }
434    }
435}
436
437impl<P: ProcessManager> HostRegistration<P> {
438    /// Introspectable metadata for this entry, for documentation tooling
439    /// that reads modules without registering them.
440    pub fn meta(&self) -> &FuncMeta {
441        match self {
442            HostRegistration::Stateful { meta, .. } => meta,
443            HostRegistration::Pure { meta, .. } => meta,
444            HostRegistration::Both { meta, .. } => meta,
445        }
446    }
447}
448
449/// One user-defined function body (`FUNC NAME($p: TYPE, ...): RET { ... }`).
450/// Param and return types resolve to tags at definition time, where the type
451/// directory is in scope; the registry never holds raw type strings.
452/// The flag marks trailing `?` params the caller may omit (filled with
453/// [`optional_zero_value`] at call time).
454#[derive(Debug, Clone)]
455pub(super) struct FuncDefData {
456    pub(super) params: Vec<(String, TypeTag, bool)>,
457    pub(super) return_type: TypeTag,
458    pub(super) return_spelling: String,
459    pub(super) is_async: bool,
460    pub(super) body: Vec<Step>,
461    /// Owning file module (#115, resolved display path): module-owned
462    /// `FUNC`s resolve names against the module's shared store after
463    /// lexical frames miss. `None` for entry/REPL definitions, which
464    /// stay params-only.
465    pub(super) module: Option<String>,
466}
467
468/// Zero value for an omitted trailing optional script param, by
469/// resolved tag. Scalars take falsy empties and collections empty
470/// shapes (mirroring the host optional-`MAP` fill); records qualify
471/// when every field is optional or defaulted (binding fills the
472/// defaults). Handles, pipes, custom types, unions, and the
473/// remaining words have no zero: omitting those fails at definition,
474/// so the caller passes explicitly.
475pub fn optional_zero_value(tag: &TypeTag) -> Result<Value> {
476    match tag {
477        TypeTag::Bool => Ok(Value::bool(false)),
478        TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
479        TypeTag::Int => Ok(Value::int(0)),
480        TypeTag::Float => Ok(Value::float(0.0)),
481        TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
482        TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
483        TypeTag::Record(fields)
484            if fields
485                .iter()
486                .all(|field| field.optional || field.default.is_some()) =>
487        {
488            Ok(Value::map(BTreeMap::new()))
489        }
490        other => anyhow::bail!(
491            "no zero value for {}; omit the `?` or pass the argument explicitly",
492            oxdock_parser::render_structural(other)
493        ),
494    }
495}
496
497/// Resolve script `FUNC` param spellings to tags in one place: tag
498/// resolution, declaration checks, and optional zero-value validation.
499/// All definition paths (direct, static check, file import) funnel
500/// here, so a required-after-optional or zero-less optional fails
501/// identically everywhere instead of drifting by call site.
502pub fn resolve_script_params<P: ProcessManager>(
503    state: &ExecState<P>,
504    func_name: &str,
505    params: &[(String, String, bool)],
506) -> Result<Vec<(String, TypeTag, bool)>> {
507    let mut resolved = Vec::with_capacity(params.len());
508    for (pname, ptype, optional) in params {
509        let clean = pname.trim_start_matches('$').to_string();
510        let tag = state
511            .resolve_tag(ptype)
512            .map_err(|err| anyhow::anyhow!("function `{func_name}`: {err:#}"))?;
513        state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
514        if *optional {
515            optional_zero_value(&tag).map(|_| ()).map_err(|err| {
516                anyhow::anyhow!("function `{func_name}` optional param `${clean}`: {err:#}")
517            })?;
518        }
519        resolved.push((clean, tag, *optional));
520    }
521    Ok(resolved)
522}
523
524/// Validate already-resolved script param tags: the zero-value gate
525/// for registry insertion paths that never see spellings.
526pub fn check_script_param_tags(func_name: &str, params: &[(String, TypeTag, bool)]) -> Result<()> {
527    for (pname, tag, optional) in params {
528        if *optional {
529            optional_zero_value(tag).map(|_| ()).map_err(|err| {
530                anyhow::anyhow!("function `{func_name}` optional param `${pname}`: {err:#}")
531            })?;
532        }
533    }
534    Ok(())
535}
536
537/// Executable body behind one registry entry: an interpreted script, a
538/// pure scalar function, a stateful function with step context, or a
539/// dual entry whose pure arm serves `{{ }}` placeholders while the ctx
540/// arm serves every context that carries step IO.
541pub(super) enum FuncBody<P: ProcessManager> {
542    Script(FuncDefData),
543    Pure(PureFn),
544    Ctx(NativeFn<P>),
545    Both { pure: PureFn, ctx: NativeFn<P> },
546}
547
548// Manual `Clone` (a derive would demand `P: Clone`).
549impl<P: ProcessManager> Clone for FuncBody<P> {
550    fn clone(&self) -> Self {
551        match self {
552            FuncBody::Script(def) => FuncBody::Script(def.clone()),
553            FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
554            FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
555            FuncBody::Both { pure, ctx } => FuncBody::Both {
556                pure: Arc::clone(pure),
557                ctx: Arc::clone(ctx),
558            },
559        }
560    }
561}
562
563/// One entry in the unified function registry: introspectable metadata
564/// (mandatory for every entry, backing the pre-evaluation arity gate)
565/// plus the executable body.
566pub(super) struct FuncEntry<P: ProcessManager> {
567    pub(super) meta: FuncMeta,
568    pub(super) body: FuncBody<P>,
569}
570
571// Manual `Clone` (a derive would demand `P: Clone`).
572impl<P: ProcessManager> Clone for FuncEntry<P> {
573    fn clone(&self) -> Self {
574        Self {
575            meta: self.meta.clone(),
576            body: self.body.clone(),
577        }
578    }
579}
580
581/// Names defined in one lexical scope frame: `defined` rejects duplicates
582/// in the same scope, `shadowed` restores outer definitions on exit.
583struct ScopeFrame<P: ProcessManager> {
584    defined: HashSet<String>,
585    shadowed: Vec<(String, FuncEntry<P>)>,
586}
587
588// Manual `Clone` (a derive would demand `P: Clone`).
589impl<P: ProcessManager> Clone for ScopeFrame<P> {
590    fn clone(&self) -> Self {
591        Self {
592            defined: self.defined.clone(),
593            shadowed: self.shadowed.clone(),
594        }
595    }
596}
597
598/// The single function registry: DSL `FUNC` definitions, builtins, and
599/// host extensions share one lookup table, one metadata path, and one
600/// dispatch order. Script entries scope lexically (defined names revert on
601/// scope exit, shadowing an outer definition restores it); native entries
602/// persist for the run. Shared across `fork()` via clone; the entry maps
603/// clone while scope frames stay per state.
604/// Module to function-name table of pure entries, shared by reference.
605/// Nested so placeholder dispatch looks up `table[module][func]` with
606/// zero allocation; rebuilt only when native entries register.
607pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
608
609/// Shared `{{ MODULE::FUNC(args) }}` dispatch over a pure-function table.
610///
611/// Single implementation for every expansion path (script `EXPAND`,
612/// string interpolation, host-driven fragment expansion): nested
613/// module then function lookup with zero allocation, unknown names
614/// failing with the sorted known-functions listing. Callers keep
615/// their own arg resolution and output handling; only dispatch and
616/// its error shape live here.
617pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
618    Arc::new(move |module, func, args| {
619        let callee = table
620            .get(module)
621            .and_then(|entries| entries.get(func))
622            .ok_or_else(|| {
623                let mut known: Vec<String> = table
624                    .iter()
625                    .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
626                    .collect();
627                known.sort();
628                anyhow::anyhow!(
629                    "unknown placeholder function '{module}::{func}'; known functions: {}",
630                    known.join(", ")
631                )
632            })?;
633        callee(args)
634    })
635}
636
637/// Descriptive `{{ MODULE::FUNC }}` miss wording, shared by the static
638/// gate and the runtime fallbacks: known callees are never called
639/// "unknown". Returns `None` when the callee is genuinely unknown
640/// everywhere (callers keep the unknown-function diagnostic with its
641/// known-functions listing). `{{ }}` runs without step context, so
642/// the fix always routes through a prior `LET` binding.
643pub(super) fn describe_placeholder_miss(
644    module: &str,
645    name: &str,
646    is_script: bool,
647    is_stateful: bool,
648    alias_known: bool,
649) -> Option<String> {
650    let qualified = qualify(module, name);
651    if is_script {
652        let call = if module == SCRIPT_MODULE_NAME {
653            format!("{name}(...)")
654        } else {
655            format!("{qualified}(...)")
656        };
657        return Some(format!(
658            "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with LET $v = {call} then interpolate {{{{ $v }}}}"
659        ));
660    }
661    if is_stateful {
662        return Some(format!(
663            "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with LET then interpolate {{{{ $v }}}}"
664        ));
665    }
666    if alias_known {
667        return Some(format!(
668            "placeholder function '{qualified}': no function '{name}' under file alias '{module}'; check the file's EXPORT list and the IMPORT harvest, or bind a known function first with LET then interpolate {{{{ $v }}}}"
669        ));
670    }
671    None
672}
673
674/// Owned placeholder classes for `'static` closures (notably
675/// `EXPAND` streaming), which cannot borrow the registry.
676pub(super) struct PlaceholderClasses {
677    pub script: HashSet<String>,
678    pub stateful: HashSet<String>,
679    pub aliases: HashSet<String>,
680    /// Ambiguous spellings: alias resolves to several files.
681    pub ambiguous: HashMap<String, HashSet<String>>,
682}
683
684impl PlaceholderClasses {
685    pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
686        let qualified = qualify(module, name);
687        if let Some(files) = self.ambiguous.get(&qualified) {
688            return Some(ambiguous_alias_message(module, name, files));
689        }
690        describe_placeholder_miss(
691            module,
692            name,
693            self.script.contains(&qualified),
694            self.stateful.contains(&qualified),
695            self.aliases.contains(module),
696        )
697    }
698}
699
700pub struct FunctionRegistry<P: ProcessManager> {
701    entries: HashMap<String, FuncEntry<P>>,
702    scopes: Vec<ScopeFrame<P>>,
703    pure_shared: Arc<PureTable>,
704    /// Script `#` doc comments keyed by qualified `SCRIPT::NAME`.
705    /// Populated by the MCP host after linear execution; the tool
706    /// table reads these with fallback to `FuncMeta` summary.
707    script_docs: HashMap<String, (String, String)>,
708}
709
710impl<P: ProcessManager> FunctionRegistry<P> {
711    pub(super) fn with_builtins() -> Self {
712        let mut reg = Self {
713            entries: HashMap::new(),
714            pure_shared: Arc::new(HashMap::new()),
715            script_docs: HashMap::new(),
716            scopes: vec![ScopeFrame {
717                defined: HashSet::new(),
718                shadowed: Vec::new(),
719            }],
720        };
721        // Every builtin registers through the same `HostRegistration`
722        // entries hosts use: no separate authoring path for engine natives.
723        // Builtins land in the `STD` module, exactly like a host module.
724        for host in Self::builtin_registrations() {
725            match host {
726                HostRegistration::Stateful { name, meta, func } => {
727                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
728                }
729                HostRegistration::Pure { name, meta, func } => {
730                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
731                }
732                HostRegistration::Both {
733                    name,
734                    meta,
735                    func,
736                    template,
737                } => {
738                    reg.insert_qualified(
739                        STD_MODULE_NAME,
740                        name,
741                        meta,
742                        FuncBody::Both {
743                            pure: template,
744                            ctx: func,
745                        },
746                    );
747                }
748            }
749        }
750        reg
751    }
752
753    /// All builtins as host-style registrations, built from the same
754    /// `#[oxdock_func]`-generated markers hosts use. `with_builtins`
755    /// consumes this list, so builtins and hosts share one registration
756    /// pathway instead of two authoring models.
757    pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
758        vec![
759            Int::registration(),
760            Float::registration(),
761            BoolConvert::registration(),
762            BoolOr::registration(),
763            FormatByteCount::registration(),
764            ParseByteCount::registration(),
765            FormatDuration::registration(),
766            ParseDuration::registration(),
767            Types::registration(),
768            TypeDescribe::registration(),
769            Glob::registration(),
770            LoadToml::registration(),
771            LoadJson::registration(),
772            HashSha256::registration(),
773            Cwd::registration(),
774            ParseToml::registration(),
775            ParseJson::registration(),
776            PathType::registration(),
777            PathWritable::registration(),
778            IsExec::registration(),
779            HasKey::registration(),
780            Get::registration(),
781            MapSet::registration(),
782            MergeMaps::registration(),
783            Base64Encode::registration(),
784            Base64Decode::registration(),
785            Rand::registration(),
786            ToJson::registration(),
787            TypeOf::registration(),
788            Functions::registration(),
789            Describe::registration(),
790            IsMain::registration(),
791            IsTerminal::registration(),
792            Eof::registration(),
793            TaskPoll::registration(),
794            Version::registration(),
795            Interpreter::registration(),
796            Argv::registration(),
797            ParseArgs::registration(),
798            ParseFlags::registration(),
799            ParsePositionals::registration(),
800            TextTrim::registration(),
801            TextTrimPrefix::registration(),
802            TextTrimSuffix::registration(),
803            PathJoin::registration(),
804            TextToUpper::registration(),
805            TextToLower::registration(),
806            TextReplace::registration(),
807            TextReplaceRegex::registration(),
808            TextSplit::registration(),
809            TextJoin::registration(),
810            TextLines::registration(),
811            TextFields::registration(),
812            TextMatch::registration(),
813            TextExtract::registration(),
814            TextStartsWith::registration(),
815            TextEndsWith::registration(),
816            TextContains::registration(),
817            Len::registration(),
818            TextCount::registration(),
819            TextCountMatches::registration(),
820            TextGrep::registration(),
821            TextLinesRange::registration(),
822            SemaphoreNew::registration(),
823            SemaphoreTryAcquire::registration(),
824            SemaphoreAvailable::registration(),
825            ShellSplitArgs::registration(),
826            ShellJoinArgs::registration(),
827        ]
828    }
829
830    /// Every name the registry answers to. Backs parse-time shadow
831    /// validation through `builtin_function_names`.
832    pub(super) fn keys(&self) -> HashSet<String> {
833        self.entries.keys().cloned().collect()
834    }
835
836    /// Single lookup for every callable: script, pure, or stateful.
837    pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
838        self.entries.get(name).cloned()
839    }
840
841    /// Single lazy miss classifier for runtime placeholder paths with
842    /// registry access: one borrow, no `FuncEntry` clones, invoked only
843    /// on resolver failure. Classification runs first (matching
844    /// `exported_metas`); the shared body helper below owns the
845    /// `Script`/`Ctx` wording, so the match appears once.
846    pub(super) fn describe_unit_placeholder_miss(
847        &self,
848        unit_targets: &AliasTargets,
849        module: &str,
850        name: &str,
851    ) -> Option<String> {
852        let qualified = qualify(module, name);
853        // File-aliased spellings classify through the shared matcher.
854        // A canonical miss means the alias is known but holds no such
855        // function; disjoint aliases share the static owner's verdict
856        // (script-visible branches read as script misses).
857        match classify_alias_call(unit_targets, &qualified, &|key| {
858            self.entries.contains_key(key)
859        }) {
860            AliasResolution::Canonical(canonical) => {
861                if let Some(entry) = self.entries.get(&canonical) {
862                    if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
863                        return Some(miss);
864                    }
865                    None
866                } else {
867                    describe_placeholder_miss(module, name, false, false, true)
868                }
869            }
870            AliasResolution::Global => {
871                if let Some(entry) = self.entries.get(&qualified) {
872                    // `SCRIPT` and host spellings resolve globally;
873                    // canonical file keys never match a call-site
874                    // spelling.
875                    if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
876                        return Some(miss);
877                    }
878                }
879                None
880            }
881            AliasResolution::Ambiguous { files, .. } => {
882                Some(ambiguous_alias_message(module, name, &files))
883            }
884            AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
885            // Disjoint aliases share the static owner's verdict through
886            // the single miss helper, so lazy inline expansion agrees
887            // with the static gate word for word (script-visible
888            // branches read as script misses, the rest as known-alias
889            // misses, never the generic unknown wording).
890            AliasResolution::Any {
891                base,
892                files,
893                has_host,
894            } => Some(disjoint_alias_placeholder_miss(
895                module,
896                name,
897                &base,
898                &files,
899                has_host,
900                &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
901            )),
902        }
903    }
904
905    /// Single owner for the `FuncBody` miss wording: script and
906    /// stateful bodies report their kind, template-capable bodies
907    /// (`Pure`/`Both`) report no miss.
908    fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
909        match body {
910            FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
911            FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
912            FuncBody::Pure(_) | FuncBody::Both { .. } => None,
913        }
914    }
915
916    /// Owned snapshot for `'static` placeholder closures (notably
917    /// `EXPAND` streaming): the resolver closure cannot borrow the
918    /// registry, so these name sets are the minimal owned form.
919    pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
920        let mut script = HashSet::new();
921        let mut stateful = HashSet::new();
922        let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
923        for (key, entry) in self.entries.iter() {
924            let Some((module, base)) = split_qualified(key) else {
925                continue;
926            };
927            match &entry.body {
928                FuncBody::Script(def) => {
929                    if module == SCRIPT_MODULE_NAME {
930                        // `SCRIPT` and bare-harvest spellings stay global.
931                        script.insert(key.clone());
932                        continue;
933                    }
934                    // Canonical file key: every local spelling in this
935                    // unit, singletons (plus disjoint platform branches
936                    // covered everywhere by script definitions) into
937                    // the script set and several files into the
938                    // ambiguity map, through the shared matcher so
939                    // `describe` matches call sites exactly like the
940                    // static gate and lazy path.
941                    let defining = def.module.as_deref().unwrap_or(module);
942                    let (direct, ambiguous_here) = spellings_for_defining_file(
943                        unit_targets,
944                        defining,
945                        base,
946                        &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
947                    );
948                    script.extend(direct);
949                    for (spelling, files) in ambiguous_here {
950                        ambiguous.entry(spelling).or_default().extend(files);
951                    }
952                }
953                FuncBody::Ctx(_) => {
954                    stateful.insert(key.clone());
955                }
956                FuncBody::Pure(_) | FuncBody::Both { .. } => {}
957            }
958        }
959        let aliases = unit_targets.keys().cloned().collect();
960        PlaceholderClasses {
961            script,
962            stateful,
963            aliases,
964            ambiguous,
965        }
966    }
967
968    fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
969        self.entries.insert(name, FuncEntry { meta, body });
970        self.rebuild_pure_shared();
971    }
972
973    /// Rebuild the shared pure table. Runs only on native insertion:
974    /// script definitions insert `Script` bodies directly and never
975    /// affect the pure set, so this stays correct between rebuilds.
976    /// Dual entries contribute their template arm, which is what
977    /// `{{ }}` placeholder expansion resolves.
978    fn rebuild_pure_shared(&mut self) {
979        let mut table: PureTable = HashMap::new();
980        for (name, entry) in &self.entries {
981            let func = match &entry.body {
982                FuncBody::Pure(func) => func,
983                FuncBody::Both { pure, .. } => pure,
984                FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
985            };
986            if let Some((module, base)) = split_qualified(name) {
987                table
988                    .entry(module.to_string())
989                    .or_default()
990                    .insert(base.to_string(), Arc::clone(func));
991            }
992        }
993        self.pure_shared = Arc::new(table);
994    }
995
996    /// Insert under `MODULE::BASE`, stamping provenance on the metadata.
997    /// The single choke point for every registry entry: builtins pass
998    /// `STD`, hosts pass their module, scripts pass `SCRIPT`.
999    fn insert_qualified(
1000        &mut self,
1001        module: &str,
1002        base: String,
1003        mut meta: FuncMeta,
1004        body: FuncBody<P>,
1005    ) {
1006        meta.name = qualify(module, &base);
1007        meta.module = module.to_string();
1008        // Last-write-wins would silently reroute calls, so a repeated
1009        // qualified name is a programmer error, never a shadow: panic like
1010        // conflicting type registrations do. `SCRIPT` definitions bypass
1011        // this path (`define_script` owns their scoped shadowing).
1012        if self.entries.contains_key(&meta.name) {
1013            panic!("duplicate function registration `{}`", meta.name);
1014        }
1015        self.insert_native(meta.name.clone(), meta, body);
1016    }
1017
1018    pub(super) fn register_host(
1019        &mut self,
1020        module: &str,
1021        name: String,
1022        mut meta: FuncMeta,
1023        func: NativeFn<P>,
1024    ) {
1025        meta.kind = FuncKind::HostCtx;
1026        self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1027    }
1028
1029    pub(super) fn register_pure_host(
1030        &mut self,
1031        module: &str,
1032        name: String,
1033        mut meta: FuncMeta,
1034        func: PureFn,
1035    ) {
1036        meta.kind = FuncKind::HostPure;
1037        self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1038    }
1039
1040    pub(super) fn register_both_host(
1041        &mut self,
1042        module: &str,
1043        name: String,
1044        mut meta: FuncMeta,
1045        func: NativeFn<P>,
1046        template: PureFn,
1047    ) {
1048        meta.kind = FuncKind::HostCtx;
1049        self.insert_qualified(
1050            module,
1051            name,
1052            meta,
1053            FuncBody::Both {
1054                pure: template,
1055                ctx: func,
1056            },
1057        );
1058    }
1059
1060    /// Define a DSL `FUNC`: names colliding with any known base name cannot
1061    /// shadow, same-scope duplicates cannot redefine, and nested shadowing
1062    /// of an outer script definition restores on scope exit. Stored as
1063    /// `SCRIPT::NAME`, exactly like every other qualified entry.
1064    #[allow(clippy::too_many_arguments)]
1065    pub(super) fn define_script(
1066        &mut self,
1067        name: &str,
1068        params: &[(String, TypeTag, bool)],
1069        return_type: TypeTag,
1070        return_spelling: &str,
1071        is_async: bool,
1072        body: &[Step],
1073        module: Option<&str>,
1074    ) -> Result<()> {
1075        let qualified = qualify(SCRIPT_MODULE_NAME, name);
1076        let shadowable = matches!(
1077            self.entries.get(&qualified).map(|entry| &entry.body),
1078            Some(FuncBody::Script(_))
1079        );
1080        // Reserved spans every module: compare base names so the message
1081        // keeps naming the bare script identifier. Script-defined entries
1082        // (including `ALIAS::NAME` file imports, #115) never reserve: only
1083        // native/host bodies are unshadowable.
1084        let reserved = self.entries.iter().any(|(key, entry)| {
1085            split_qualified(key).is_some_and(|(_, base)| base == name)
1086                && !matches!(entry.body, FuncBody::Script(_))
1087        });
1088        if reserved && !shadowable {
1089            anyhow::bail!("cannot shadow reserved function `{name}`");
1090        }
1091        if self
1092            .scopes
1093            .last()
1094            .is_some_and(|frame| frame.defined.contains(&qualified))
1095        {
1096            anyhow::bail!("duplicate function `{name}` in same scope");
1097        }
1098        check_script_param_tags(name, params)?;
1099        let old = self.entries.insert(
1100            qualified.clone(),
1101            FuncEntry {
1102                meta: FuncMeta {
1103                    name: qualified.clone(),
1104                    module: SCRIPT_MODULE_NAME.to_string(),
1105                    kind: FuncKind::Script,
1106                    params: Some(
1107                        params
1108                            .iter()
1109                            .map(|(pname, param_type, optional)| {
1110                                Ok(FuncParam {
1111                                    name: pname.clone(),
1112                                    param_type: Some(param_type.clone()),
1113                                    allowed: None,
1114                                    // Script `FUNC` params carry no prose:
1115                                    // declarations have no doc syntax.
1116                                    docs: "",
1117                                    options: None,
1118                                    optional: *optional,
1119                                })
1120                            })
1121                            .collect::<Result<_>>()?,
1122                    ),
1123                    returns: Some(return_type.clone()),
1124                    rpn: false,
1125                    summary: "DSL-defined function.",
1126                    docs: "Defined via FUNC in script.",
1127                    examples: &[],
1128                },
1129                body: FuncBody::Script(FuncDefData {
1130                    params: params.to_vec(),
1131                    return_type,
1132                    return_spelling: return_spelling.to_string(),
1133                    is_async,
1134                    body: body.to_vec(),
1135                    module: module.map(|m| m.to_string()),
1136                }),
1137            },
1138        );
1139        if let Some(frame) = self.scopes.last_mut() {
1140            frame.defined.insert(qualified.clone());
1141            if let Some(old) = old {
1142                frame.shadowed.push((qualified, old));
1143            }
1144        }
1145        Ok(())
1146    }
1147
1148    /// Define a file-imported DSL `FUNC` under its canonical key
1149    /// ([`file_func_key`]: defining file plus base name, never the
1150    /// importer alias) in the global registry frame (index 0, never
1151    /// popped): eviction on scope exit would strand the module cache
1152    /// and alias targets that still reference it.
1153    #[allow(clippy::too_many_arguments)]
1154    pub(super) fn define_file_func(
1155        &mut self,
1156        name: &str,
1157        params: &[(String, TypeTag, bool)],
1158        return_type: TypeTag,
1159        return_spelling: &str,
1160        is_async: bool,
1161        body: &[Step],
1162        defining: &str,
1163    ) -> Result<()> {
1164        // The importer alias selects the defining file at dispatch;
1165        // the key itself names the defining file so units never share
1166        // entries.
1167        let qualified = file_func_key(defining, name);
1168        let shadowable = matches!(
1169            self.entries.get(&qualified).map(|entry| &entry.body),
1170            Some(FuncBody::Script(_))
1171        );
1172        // Reserved spans every module: compare base names so the message
1173        // keeps naming the bare script identifier. Script-defined entries
1174        // never reserve: only native/host bodies are unshadowable.
1175        let reserved = self.entries.iter().any(|(key, entry)| {
1176            split_qualified(key).is_some_and(|(_, base)| base == name)
1177                && !matches!(entry.body, FuncBody::Script(_))
1178        });
1179        if reserved && !shadowable {
1180            anyhow::bail!("cannot shadow reserved function `{name}`");
1181        }
1182        // File entries live in the global frame (index 0, never
1183        // popped): eviction on scope exit would strand the module
1184        // cache and alias targets that still reference them.
1185        let frame_idx = 0;
1186        if self
1187            .scopes
1188            .get(frame_idx)
1189            .is_some_and(|frame| frame.defined.contains(&qualified))
1190        {
1191            anyhow::bail!("duplicate function `{name}` in same scope");
1192        }
1193        check_script_param_tags(name, params)?;
1194        let old = self.entries.insert(
1195            qualified.clone(),
1196            FuncEntry {
1197                meta: FuncMeta {
1198                    name: qualified.clone(),
1199                    module: defining.to_string(),
1200                    kind: FuncKind::Script,
1201                    params: Some(
1202                        params
1203                            .iter()
1204                            .map(|(pname, param_type, optional)| {
1205                                Ok(FuncParam {
1206                                    name: pname.clone(),
1207                                    param_type: Some(param_type.clone()),
1208                                    allowed: None,
1209                                    docs: "",
1210                                    options: None,
1211                                    optional: *optional,
1212                                })
1213                            })
1214                            .collect::<Result<_>>()?,
1215                    ),
1216                    returns: Some(return_type.clone()),
1217                    rpn: false,
1218                    summary: "DSL-defined function.",
1219                    docs: "Defined via FUNC in an imported script.",
1220                    examples: &[],
1221                },
1222                body: FuncBody::Script(FuncDefData {
1223                    params: params.to_vec(),
1224                    return_type,
1225                    return_spelling: return_spelling.to_string(),
1226                    is_async,
1227                    body: body.to_vec(),
1228                    module: Some(defining.to_string()),
1229                }),
1230            },
1231        );
1232        if let Some(frame) = self.scopes.get_mut(frame_idx) {
1233            frame.defined.insert(qualified.clone());
1234            if let Some(old) = old {
1235                frame.shadowed.push((qualified, old));
1236            }
1237        }
1238        Ok(())
1239    }
1240
1241    /// Open a lexical scope frame for script definitions. Native entries
1242    /// persist; only script names track here.
1243    pub(super) fn push_scope(&mut self) {
1244        self.scopes.push(ScopeFrame {
1245            defined: HashSet::new(),
1246            shadowed: Vec::new(),
1247        });
1248    }
1249
1250    /// Close a lexical scope frame: names defined inside revert, and any
1251    /// outer definition they shadowed is restored.
1252    pub(super) fn pop_scope(&mut self) {
1253        let Some(frame) = self.scopes.pop() else {
1254            return;
1255        };
1256        for name in frame.defined {
1257            self.entries.remove(&name);
1258        }
1259        for (name, old) in frame.shadowed {
1260            self.entries.insert(name, old);
1261        }
1262    }
1263
1264    /// True when `name` is an interpreted script definition (needing call
1265    /// scoping and depth budgeting through `call_func_value` rather than
1266    /// inline evaluation). Callers resolve file-aliased spellings to
1267    /// the canonical key first (see `resolve_file_call_key`).
1268    pub(super) fn contains_script(&self, name: &str) -> bool {
1269        matches!(
1270            self.entries.get(name).map(|entry| &entry.body),
1271            Some(FuncBody::Script(_))
1272        )
1273    }
1274
1275    /// Registry lookup key for a runtime call-site spelling, through
1276    /// the shared alias-target matcher.
1277    pub(super) fn resolve_file_call_key(
1278        &self,
1279        unit_targets: &AliasTargets,
1280        name: &str,
1281    ) -> Result<Option<String>> {
1282        match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1283            AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1284                Ok(None)
1285            }
1286            AliasResolution::Canonical(key) => Ok(Some(key)),
1287            AliasResolution::Ambiguous { alias, base, files } => Err(anyhow::anyhow!(
1288                "{}",
1289                ambiguous_alias_message(&alias, &base, &files)
1290            )),
1291        }
1292    }
1293
1294    /// Clone the pure fn for `name` (ending the registry borrow) so callers
1295    /// can invoke it without holding `&self` across a `&mut StepCtx` use.
1296    /// Dual entries answer with their template arm.
1297    fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
1298        match self.entries.get(name)?.body {
1299            FuncBody::Pure(ref func) => Some(Arc::clone(func)),
1300            FuncBody::Both { ref pure, .. } => Some(Arc::clone(pure)),
1301            _ => None,
1302        }
1303    }
1304
1305    /// Shared snapshot of every pure entry, nested by module and base
1306    /// name. Cloning the `Arc` is refcount-only: placeholder dispatch
1307    /// borrows this per expansion with no map copies.
1308    pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1309        Arc::clone(&self.pure_shared)
1310    }
1311
1312    /// Every entry's metadata, scripts included, sorted by name. Backs
1313    /// run-start type tag validation.
1314    pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1315        self.entries_metas()
1316    }
1317
1318    /// Clone the ctx fn for `name` (ending the registry borrow) so callers
1319    /// can invoke it with `&mut StepCtx` without double-borrowing state.
1320    /// Dual entries answer with their stateful arm, which is the full
1321    /// behavior wherever step IO exists.
1322    fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
1323        match self.entries.get(name)?.body {
1324            FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
1325            FuncBody::Both { ref ctx, .. } => Some(Arc::clone(ctx)),
1326            _ => None,
1327        }
1328    }
1329
1330    fn meta(&self, name: &str) -> Option<FuncMeta> {
1331        self.entries.get(name).map(|entry| entry.meta.clone())
1332    }
1333
1334    fn native_metas(&self) -> Vec<FuncMeta> {
1335        let mut out: Vec<FuncMeta> = Vec::new();
1336        for entry in self.entries.values() {
1337            if !matches!(entry.body, FuncBody::Script(_)) {
1338                out.push(entry.meta.clone());
1339            }
1340        }
1341        out.sort_by(|a, b| a.name.cmp(&b.name));
1342        out
1343    }
1344
1345    /// Metadata for template-capable entries only: `Pure` plus `Both`
1346    /// (dual entries contribute their template arm to `{{ }}`).
1347    /// `Ctx` and `Script` never resolve in placeholder expansion, so
1348    /// the static template gate reads this instead of `all_metas`.
1349    pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1350        let mut out: Vec<FuncMeta> = Vec::new();
1351        for entry in self.entries.values() {
1352            if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1353                out.push(entry.meta.clone());
1354            }
1355        }
1356        out.sort_by(|a, b| a.name.cmp(&b.name));
1357        out
1358    }
1359
1360    /// Every entry's metadata, scripts included, sorted by name. Backs
1361    /// runtime `FUNCTIONS()` listings.
1362    fn entries_metas(&self) -> Vec<FuncMeta> {
1363        let mut out: Vec<FuncMeta> = self
1364            .entries
1365            .values()
1366            .map(|entry| entry.meta.clone())
1367            .collect();
1368        out.sort_by(|a, b| a.name.cmp(&b.name));
1369        out
1370    }
1371
1372    /// Install script `#` docs keyed by bare base name. Stored under
1373    /// qualified `SCRIPT::NAME` keys.
1374    pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1375        for (base, pair) in docs {
1376            self.script_docs
1377                .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1378        }
1379    }
1380
1381    /// Script doc pair for a qualified name, if the parser collected one.
1382    pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1383        self.script_docs.get(qualified).cloned()
1384    }
1385
1386    /// Metadata for single-file `EXPORT` names in source order. Errors
1387    /// name the first missing export; callers fail fast before serving.
1388    /// Qualified names resolve through `resolve_file_call_key`, so
1389    /// re-exported file functions serve under the export spelling.
1390    pub fn exported_metas(
1391        &self,
1392        func_exports: &[String],
1393        unit_targets: &AliasTargets,
1394    ) -> anyhow::Result<Vec<FuncMeta>> {
1395        let mut out = Vec::with_capacity(func_exports.len());
1396        for name in func_exports {
1397            // Bare names are script FUNCs; qualified names resolve
1398            // through the unit's alias targets first, falling back to
1399            // the global spelling for hosts and entry-owned scripts.
1400            let qualified = match split_qualified(name) {
1401                None => qualify(SCRIPT_MODULE_NAME, name),
1402                Some(_) => name.clone(),
1403            };
1404            let lookup = self
1405                .resolve_file_call_key(unit_targets, &qualified)?
1406                .unwrap_or_else(|| qualified.clone());
1407            if let Some(entry) = self.entries.get(&lookup) {
1408                let mut meta = entry.meta.clone();
1409                if lookup != qualified {
1410                    meta.name = name.clone();
1411                }
1412                out.push(meta);
1413                continue;
1414            }
1415            anyhow::bail!(
1416                "EXPORT `{name}` matches no defined script function or known host function"
1417            );
1418        }
1419        Ok(out)
1420    }
1421}
1422
1423impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1424    fn clone(&self) -> Self {
1425        Self {
1426            entries: self.entries.clone(),
1427            scopes: self.scopes.clone(),
1428            pure_shared: Arc::clone(&self.pure_shared),
1429            script_docs: self.script_docs.clone(),
1430        }
1431    }
1432}
1433
1434/// Names of all compiled-in builtins plus `INSPECT` (a dedicated AST/RPN
1435/// node, not a registry entry). Read straight off a stock registry, so the
1436/// `#[oxdock_func]` annotations stay the single source of truth: adding a
1437/// builtin extends this set with no parallel list to update. Seeds
1438/// parse-time shadow validation, so the parser crate keeps zero
1439/// compile-time knowledge of builtin names.
1440pub fn builtin_function_names() -> HashSet<String> {
1441    let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1442    names.insert(KEYWORD_INSPECT.to_string());
1443    names
1444}
1445
1446/// Metadata of every builtin function, sorted by name, for static
1447/// rendering (oxdock-render). Same single source as `builtin_function_names`:
1448/// the `#[oxdock_func]` annotations, never a parallel list.
1449pub fn builtin_function_metas() -> Vec<FuncMeta> {
1450    FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
1451}
1452
1453/// Stock `STD` module table derived from the `#[oxdock_func]` builtins:
1454/// the single source of truth for builtin membership and RPN eligibility.
1455/// Seeds parse-time module resolution, so the parser crate keeps zero
1456/// compile-time knowledge of builtin names.
1457pub fn std_module_table() -> oxdock_parser::ModuleTable {
1458    // Registry names are qualified (`STD::GLOB`); the table holds bases.
1459    let func_names: HashSet<String> = builtin_function_metas()
1460        .into_iter()
1461        .map(|meta| base_name(&meta.name).to_string())
1462        .collect();
1463    oxdock_parser::ModuleTable {
1464        modules: HashMap::from([(
1465            STD_MODULE_NAME.to_string(),
1466            Some(oxdock_parser::ModuleFuncs { func_names }),
1467        )]),
1468    }
1469}
1470
1471// Builtins below use the `#[oxdock_func]` host export macro, the exact same authoring
1472// model as host-registered functions: metadata, arity checks, and argument
1473// unpacking derive from the signature plus doc comments, so adding a native
1474// means writing one small typed function plus one line each in
1475// `builtin_registrations` (consumed by `with_builtins`) and the
1476// `FUNCTIONS`/`DESCRIBE`/`TYPES` surface, which all read the same symbols.
1477
1478/// Convert a value to INT.
1479///
1480/// Trims ASCII whitespace and parses i64. Passes Int through; Float only
1481/// when integral and finite; Bool as 1/0.
1482///
1483#[oxdock_func(pure, returns = TypeTag::Int)]
1484#[example(
1485    name = "convert",
1486    code = r###"
1487    IMPORT [STD]
1488    LET $n: INT = INT("42")
1489    ASSERT_EQ $n 42
1490    LET $flag: INT = INT(true)
1491    ASSERT_EQ $flag 1
1492    "###
1493)]
1494fn int(
1495    /// Value to convert to `INT`.
1496    #[union(Int, Float, String, Bool)]
1497    val: Value,
1498) -> Result<Value> {
1499    super::args::int_from_value(val)
1500}
1501
1502/// Convert a value to FLOAT.
1503///
1504/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
1505///
1506#[oxdock_func(pure, returns = TypeTag::Float)]
1507#[example(
1508    name = "convert",
1509    code = r###"
1510    IMPORT [STD]
1511    LET $f: FLOAT = FLOAT("1.5")
1512    ASSERT_EQ $f 1.5
1513    LET $whole: FLOAT = FLOAT(2)
1514    ASSERT_EQ $whole 2.0
1515    "###
1516)]
1517fn float(
1518    /// Value to convert to `FLOAT`.
1519    #[union(Float, Int, String)]
1520    val: Value,
1521) -> Result<Value> {
1522    super::args::float_from_value(val)
1523}
1524
1525/// Format a byte count canonically (`500B`, `10KB`, `2MB`, `1GB`,
1526/// binary `10KIB` and friends): the inverse of `PARSE_BYTE_COUNT`, so
1527/// formatted values reparse exactly. Negative inputs fail.
1528///
1529#[oxdock_func(pure, returns = TypeTag::String)]
1530#[example(
1531    name = "format and round-trip",
1532    code = r###"
1533    # Byte counts render in the largest exact unit.
1534    IMPORT [STD]
1535    LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
1536    ASSERT_EQ $pretty "1MiB"
1537
1538    # The pair round-trips through the parser.
1539    LET $back: INT = PARSE_BYTE_COUNT($pretty)
1540    ASSERT_EQ $back 1_048_576
1541    "###
1542)]
1543fn format_byte_count(
1544    /// Byte count to format; negatives fail.
1545    bytes: i64,
1546) -> Result<Value> {
1547    if bytes < 0 {
1548        return Err(anyhow::anyhow!(
1549            "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
1550        ));
1551    }
1552    Ok(Value::string(oxdock_parser::command::format_byte_count(
1553        bytes as u64,
1554    )))
1555}
1556
1557/// Parse a byte-count token to `INT` bytes.
1558///
1559/// Bare digits are bytes; suffixes `B`/`KB`/`MB`/`GB`/`TB` scale
1560/// decimal and `KIB`/`MIB`/`GIB`/`TIB` binary, in any case. Plain
1561/// `INT` values pass through (already bytes); integral finite `FLOAT`
1562/// values convert. Pairs with `FORMAT_BYTE_COUNT` for the round trip.
1563///
1564/// ```oxdock
1565/// # Units parse case-insensitively; bare digits are bytes.
1566/// IMPORT [STD]
1567/// LET $bytes: INT = PARSE_BYTE_COUNT("1Gb")
1568/// ASSERT_EQ $bytes 1_000_000_000
1569///
1570/// # Binary suffixes scale by powers of two.
1571/// LET $mebi: INT = PARSE_BYTE_COUNT("2mib")
1572/// ASSERT_EQ $mebi 2_097_152
1573///
1574/// # Digit runs group Rust-literal style.
1575/// LET $grouped: INT = PARSE_BYTE_COUNT("1_000_000")
1576/// ASSERT_EQ $grouped 1_000_000
1577///
1578/// # Plain numbers pass through as bytes already.
1579/// LET $plain: INT = PARSE_BYTE_COUNT(1_048_576)
1580/// ASSERT_EQ $plain 1_048_576
1581///
1582/// # Bare literals group too.
1583/// LET $bare: INT = PARSE_BYTE_COUNT(1_000_000)
1584/// ASSERT_EQ $bare 1_000_000
1585///
1586/// # One optional space separates number from unit.
1587/// LET $spaced: INT = PARSE_BYTE_COUNT("1 GB")
1588/// ASSERT_EQ $spaced 1_000_000_000
1589/// ```
1590///
1591#[oxdock_func(pure, returns = TypeTag::Int)]
1592#[example(
1593    name = "parse",
1594    code = r###"
1595    IMPORT [STD]
1596    LET $n: INT = PARSE_BYTE_COUNT("10KB")
1597    ASSERT_EQ $n 10_000
1598    LET $identity: INT = PARSE_BYTE_COUNT(512)
1599    ASSERT_EQ $identity 512
1600    "###
1601)]
1602fn parse_byte_count(
1603    /// Byte-count token to parse, or bytes already.
1604    #[union(Int, Float, String)]
1605    text: Value,
1606) -> Result<Value> {
1607    if let Some(n) = text.as_i64() {
1608        if n < 0 {
1609            return Err(anyhow::anyhow!(
1610                "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
1611            ));
1612        }
1613        return Ok(Value::int(n));
1614    }
1615    if let Some(f) = text.as_f64() {
1616        if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
1617            return Ok(Value::int(f as i64));
1618        }
1619        return Err(anyhow::anyhow!(
1620            "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
1621        ));
1622    }
1623    let Some(s) = text.as_str() else {
1624        return Err(anyhow::anyhow!(
1625            "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
1626        ));
1627    };
1628    let n = oxdock_parser::command::parse_byte_count(s)?;
1629    let n = i64::try_from(n)
1630        .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
1631    Ok(Value::int(n))
1632}
1633
1634/// Format millisecond durations canonically (`500ms`, `10s`, `2m`,
1635/// `1h`): the inverse of `PARSE_DURATION`, so formatted values
1636/// reparse exactly. Negative inputs fail.
1637///
1638#[oxdock_func(pure, returns = TypeTag::String)]
1639#[example(
1640    name = "format and round-trip",
1641    code = r###"
1642    # Durations render in the largest exact unit.
1643    IMPORT [STD]
1644    LET $pretty: STRING = FORMAT_DURATION(90_000)
1645    ASSERT_EQ $pretty "90s"
1646
1647    # The pair round-trips through the parser.
1648    LET $back: INT = PARSE_DURATION($pretty)
1649    ASSERT_EQ $back 90_000
1650    "###
1651)]
1652fn format_duration(
1653    /// Milliseconds to format; negatives fail.
1654    millis: i64,
1655) -> Result<Value> {
1656    if millis < 0 {
1657        return Err(anyhow::anyhow!(
1658            "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
1659        ));
1660    }
1661    Ok(Value::string(oxdock_parser::command::format_duration(
1662        &std::time::Duration::from_millis(millis as u64),
1663    )))
1664}
1665
1666/// Parse a duration token to `INT` milliseconds.
1667///
1668/// Suffixes `ms`/`s`/`m`/`h`; a bare number means seconds. Pairs with
1669/// `FORMAT_DURATION` for the round trip.
1670///
1671#[oxdock_func(pure, returns = TypeTag::Int)]
1672#[example(
1673    name = "parse",
1674    code = r###"
1675    # A bare number means seconds, like TIMEOUT.
1676    IMPORT [STD]
1677    LET $ms: INT = PARSE_DURATION("2m")
1678    ASSERT_EQ $ms 120_000
1679
1680    # Milliseconds stay exact.
1681    LET $exact: INT = PARSE_DURATION("1500ms")
1682    ASSERT_EQ $exact 1_500
1683
1684    # One optional space separates number from unit.
1685    LET $spaced: INT = PARSE_DURATION("1 h")
1686    ASSERT_EQ $spaced 3_600_000
1687    "###
1688)]
1689fn parse_duration(
1690    /// Duration token to parse.
1691    text: String,
1692) -> Result<Value> {
1693    let duration = oxdock_parser::command::parse_duration(&text)?;
1694    let millis = i64::try_from(duration.as_millis())
1695        .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
1696    Ok(Value::int(millis))
1697}
1698
1699/// List workspace paths matching a glob pattern.
1700///
1701/// Sorted, root-relative LIST; empty on no match or `..` escape.
1702///
1703#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1704#[example(
1705    name = "match",
1706    code = r###"
1707    IMPORT [STD]
1708    WRITE "notes-a.md" "a"
1709    WRITE "notes-b.md" "b"
1710    WRITE "other.txt" "c"
1711    LET $found: LIST<STRING> = GLOB("notes-*.md")
1712    ASSERT_EQ $found.0 "notes-a.md"
1713    ASSERT_EQ $found.1 "notes-b.md"
1714    "###
1715)]
1716fn glob<P: ProcessManager>(
1717    cx: &mut StepCtx<P>,
1718    /// Glob pattern matched against workspace paths.
1719    #[union(String, Path)]
1720    pattern: Value,
1721) -> Result<Value> {
1722    let text = super::args::string_or_path_text(&pattern)?;
1723    super::args::glob_from_value(&[Value::string(text)], cx)
1724}
1725
1726/// Load and parse a TOML file.
1727///
1728/// Reads a workspace file and parses TOML into a DSL value.
1729///
1730#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1731#[example(
1732    name = "load",
1733    code = r###"
1734    IMPORT [STD]
1735    WRITE "cfg.toml" "title = \"demo\""
1736    LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
1737    ASSERT_EQ $cfg.title "demo"
1738    "###
1739)]
1740fn load_toml<P: ProcessManager>(
1741    cx: &mut StepCtx<P>,
1742    /// Workspace file path to load and parse as TOML.
1743    #[union(String, Path)]
1744    path: Value,
1745) -> Result<Value> {
1746    let text = super::args::string_or_path_text(&path)?;
1747    super::args::load_toml_from_value(&[Value::string(text)], cx)
1748}
1749
1750/// Load and parse a JSON file.
1751///
1752/// Reads a workspace file and parses JSON into a DSL value. Returns
1753/// `ANY` by design: a top-level array or scalar parses to `LIST` or a
1754/// scalar word. `LET` coercion still checks the actual value at
1755/// assignment.
1756///
1757#[oxdock_func(rpn, returns = TypeTag::Any)]
1758#[example(
1759    name = "load",
1760    code = r###"
1761    IMPORT [STD]
1762    WRITE "data.json" "{\"a\": 1}"
1763    LET $doc: MAP<ANY> = LOAD_JSON("data.json")
1764    ASSERT_EQ $doc.a 1
1765    "###
1766)]
1767fn load_json<P: ProcessManager>(
1768    cx: &mut StepCtx<P>,
1769    /// Workspace file path to load and parse as JSON.
1770    #[union(String, Path)]
1771    path: Value,
1772) -> Result<Value> {
1773    let text = super::args::string_or_path_text(&path)?;
1774    super::args::load_json_from_value(&[Value::string(text)], cx)
1775}
1776
1777/// Hash a workspace file or directory with SHA-256.
1778///
1779/// The argument is always a path: reads through the workspace guard
1780/// like the file-loading builtins, so relative paths resolve against
1781/// the script cwd. To hash a literal string's bytes instead, use
1782/// `ASSERT_EQ --hash <digest> <string>`, which hashes the actual
1783/// directly. Returns the 64 lowercase hex chars with no trailing
1784/// newline.
1785///
1786#[oxdock_func(rpn, returns = TypeTag::String)]
1787#[example(
1788    name = "hash",
1789    code = r###"
1790    IMPORT [STD]
1791    WRITE payload.txt hello
1792    LET $digest: STRING = HASH_SHA256("payload.txt")
1793    ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
1794    "###
1795)]
1796fn hash_sha256<P: ProcessManager>(
1797    cx: &mut StepCtx<P>,
1798    /// Workspace file or directory path to hash.
1799    #[union(String, Path)]
1800    path: Value,
1801) -> Result<Value> {
1802    use sha2::Digest;
1803
1804    let text = super::args::string_or_path_text(&path)?;
1805    let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
1806    let mut hasher = sha2::Sha256::new();
1807    super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
1808    let digest = hasher.finalize();
1809    let bytes: &[u8] = digest.as_ref();
1810    Ok(Value::string(oxdock_utils::hex_encode(bytes)))
1811}
1812
1813/// Current working directory as a workspace-absolute path.
1814///
1815/// Returns `STRING` because the result is already resolved: a `PATH`
1816/// value is workspace-relative text awaiting guard checks at use time,
1817/// while this directory is already checked and concrete, or absent
1818/// entirely under a pending snapshot. Compare or display it as text.
1819///
1820/// Reports the snapshot-pending sentinel when no concrete directory
1821/// exists yet, so snapshot scripts keep working unchanged.
1822///
1823#[oxdock_func(rpn, returns = TypeTag::String)]
1824#[example(
1825    name = "cwd",
1826    code = r###"
1827    IMPORT [STD]
1828    WORKDIR sub
1829    LET $c: STRING = CWD()
1830    ASSERT_CONTAINS $c "sub"
1831    "###
1832)]
1833fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1834    if cx.state.fs.is_snapshot_pending() {
1835        return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1836    }
1837    let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1838    let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1839    Ok(Value::string(real))
1840}
1841
1842/// Parse TOML text already held in memory.
1843///
1844/// Uses the same conversion as file loading, so fetch bodies, file
1845/// contents, and captured text share one JSON/TOML shape.
1846///
1847#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1848#[example(
1849    name = "parse",
1850    code = r###"
1851    IMPORT [STD]
1852    LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1853    ASSERT_EQ $doc.title "demo"
1854    "###
1855)]
1856fn parse_toml(
1857    /// TOML text already held in memory.
1858    text: String,
1859) -> Result<Value> {
1860    super::args::parse_toml_from_value(Value::string(text))
1861}
1862
1863/// Parse JSON text already held in memory.
1864///
1865/// Uses the same conversion as file loading, so fetch bodies, file
1866/// contents, and captured text share one JSON value shape. Returns
1867/// `ANY` by design, matching `LOAD_JSON`: a top-level array or scalar
1868/// parses to `LIST` or a scalar word. `LET` coercion still checks the
1869/// actual value at assignment.
1870///
1871#[oxdock_func(pure, returns = TypeTag::Any)]
1872#[example(
1873    name = "parse",
1874    code = r###"
1875    # Parse in-memory JSON text with the same conversion as file loading.
1876    IMPORT [STD]
1877    LET $body: STRING = "{\"a\": 1}"
1878    LET $doc: ANY = PARSE_JSON($body)
1879    ASSERT_EQ $doc.a 1
1880
1881    # Top-level arrays parse to LIST, which is why the return is ANY.
1882    LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1883    ASSERT_EQ $items.0 1
1884    ASSERT_EQ $items.1 2
1885    "###
1886)]
1887fn parse_json(
1888    /// JSON text already held in memory.
1889    text: String,
1890) -> Result<Value> {
1891    super::args::parse_json_from_value(Value::string(text))
1892}
1893
1894/// Describe a filesystem entry.
1895///
1896/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
1897/// there is no RPN arm for filesystem IO.
1898///
1899#[oxdock_func(returns = TypeTag::String)]
1900#[example(
1901    name = "describe",
1902    code = r###"
1903    IMPORT [STD]
1904    WRITE "entry.txt" "words"
1905    LET $kind: STRING = PATH_TYPE("entry.txt")
1906    ASSERT_EQ $kind "file"
1907    LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1908    ASSERT_EQ $missing "absent"
1909    "###
1910)]
1911fn path_type<P: ProcessManager>(
1912    cx: &mut StepCtx<P>,
1913    /// Workspace path of the entry to describe.
1914    #[union(String, Path)]
1915    path: Value,
1916) -> Result<Value> {
1917    let text = super::args::string_or_path_text(&path)?;
1918    super::args::path_type_from_value(&[Value::string(text)], cx)
1919}
1920
1921/// Report whether an ordinary file can be created at a path.
1922///
1923/// Walks up to the nearest existing ancestor, requires it be a
1924/// directory, and probes writability by creating and deleting a probe
1925/// file, so retry loops never litter. The empty string is false.
1926/// AST-only by design, like `PATH_TYPE`: there is no RPN arm for
1927/// filesystem IO.
1928///
1929#[oxdock_func(returns = TypeTag::Bool)]
1930#[example(
1931    name = "probe",
1932    code = r###"
1933    # An absent nested path is writable when its ancestor is.
1934    IMPORT [STD]
1935    LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1936    ASSERT_EQ $fresh true
1937
1938    # The empty string never aliases the working directory.
1939    LET $empty: BOOL = PATH_WRITABLE("")
1940    ASSERT_EQ $empty false
1941    "###
1942)]
1943fn path_writable<P: ProcessManager>(
1944    cx: &mut StepCtx<P>,
1945    /// Workspace path to probe for file creation.
1946    #[union(String, Path)]
1947    path: Value,
1948) -> Result<Value> {
1949    let text = super::args::string_or_path_text(&path)?;
1950    super::args::path_writable_from_value(&[Value::string(text)], cx)
1951}
1952
1953/// Report whether a name resolves to an executable file (#100).
1954///
1955/// Bare command names search `env:PATH` (`IS_EXEC("tar")` finds the
1956/// first executable `tar`, plus `tar.exe`, on `PATH`); spellings
1957/// containing a separator check that file directly. True means a real
1958/// file with an executable bit on Unix, or a `PATHEXT` extension on
1959/// Windows: each `env:PATHEXT` entry is probed in order (unset or empty
1960/// probes nothing). Absolute `PATH` entries resolve through the workspace as
1961/// usual, so host probing wants `WORKSPACE SYSTEM` and an inherited
1962/// `PATH`; anything unresolvable reads false, never errors. AST-only
1963/// by design, like `PATH_TYPE`: there is no RPN arm for filesystem IO.
1964///
1965#[oxdock_func(returns = TypeTag::Bool)]
1966#[example(
1967    name = "probe",
1968    code = r###"
1969    # Missing tools read false instead of failing the run.
1970    IMPORT [STD]
1971    LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1972    ASSERT_EQ $missing false
1973
1974    # Plain files are not executable on any platform.
1975    WRITE tool.txt payload
1976    LET $plain: BOOL = IS_EXEC("tool.txt")
1977    ASSERT_EQ $plain false
1978    "###
1979)]
1980fn is_exec<P: ProcessManager>(
1981    cx: &mut StepCtx<P>,
1982    /// Command name or file path to probe.
1983    #[union(String, Path)]
1984    name: Value,
1985) -> Result<Value> {
1986    let text = super::args::string_or_path_text(&name)?;
1987    super::args::is_exec_from_value(&[Value::string(text)], cx)
1988}
1989
1990/// Report whether a map holds a key.
1991///
1992/// Pure MAP probe so scripts can branch on optional fields without
1993/// tripping the strict missing-key error.
1994///
1995#[oxdock_func(pure, returns = TypeTag::Bool)]
1996#[example(
1997    name = "probe",
1998    code = r###"
1999    IMPORT [STD]
2000    LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2001    LET $hit: BOOL = HAS_KEY($m, "a")
2002    ASSERT_EQ $hit true
2003    LET $miss: BOOL = HAS_KEY($m, "b")
2004    ASSERT_EQ $miss false
2005    "###
2006)]
2007fn has_key(
2008    /// Map to probe.
2009    map: BTreeMap<String, Value>,
2010    /// Key to look up.
2011    key: String,
2012) -> Result<Value> {
2013    super::args::has_key_from_value(Value::map(map), &key)
2014}
2015
2016/// Read one map entry with a default for missing keys.
2017///
2018/// Pure MAP getter so optional flags cost one line instead of a
2019/// `HAS_KEY` + index + rebind triple: present keys return their value
2020/// verbatim (no coercion), absent keys return `default`.
2021#[oxdock_func(pure, returns = TypeTag::Any)]
2022#[example(
2023    name = "present and absent",
2024    code = r###"
2025    IMPORT [STD]
2026    LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2027    LET $hit: INT = GET($m, "a", 0)
2028    ASSERT_EQ $hit 1
2029    LET $miss: INT = GET($m, "b", 0)
2030    ASSERT_EQ $miss 0
2031    "###
2032)]
2033fn get(
2034    /// Map to read.
2035    map: BTreeMap<String, Value>,
2036    /// Key to look up.
2037    key: String,
2038    /// Default for absent keys.
2039    default: Value,
2040) -> Result<Value> {
2041    Ok(map.get(&key).cloned().unwrap_or(default))
2042}
2043
2044/// Insert one key into a map.
2045///
2046/// Fails on duplicates so two entries sharing a key fail the run
2047/// instead of silently shadowing each other.
2048///
2049#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2050#[example(
2051    name = "insert",
2052    code = r###"
2053    IMPORT [STD]
2054    LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2055    ASSERT_EQ $m.a 1
2056    "###
2057)]
2058fn map_set(
2059    /// Map to insert into.
2060    map: BTreeMap<String, Value>,
2061    /// Key to insert; duplicates fail.
2062    key: String,
2063    /// Value to store.
2064    value: Value,
2065) -> Result<Value> {
2066    super::args::map_set_from_value(Value::map(map), key, value)
2067}
2068
2069/// Draw a random FLOAT uniformly from [0, 1), optionally seeded.
2070///
2071/// Impure by design: unseeded calls return different values, so this
2072/// runs on the AST script path only, never as a `{{ }}` placeholder
2073/// call. A seed draws the same value on every run, for deterministic
2074/// fixtures. Scale and shift the draw for wider ranges.
2075///
2076#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2077#[example(
2078    name = "seeded draw",
2079    code = r###"
2080    # A seed draws the same value on every run.
2081    IMPORT [STD]
2082    LET $one: FLOAT = RAND({seed: 7})
2083    LET $two: FLOAT = RAND({seed: 7})
2084    ASSERT_EQ $one $two
2085    "###
2086)]
2087#[example(
2088    name = "unseeded draw",
2089    code = r###"
2090    # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2091    IMPORT [STD]
2092    LET $draw: FLOAT = RAND()
2093    LET $delay: FLOAT = 1.0 + $draw * 10.0
2094    IF $delay < 1.0 {
2095        EXIT 1
2096    }
2097    IF $delay >= 11.0 {
2098        EXIT 1
2099    }
2100    ECHO "retrying in {{ $delay }}s"
2101    "###
2102)]
2103fn rand<P: ProcessManager>(
2104    cx: &mut StepCtx<P>,
2105    /// Draw settings: `seed`. Omittable: a missing options MAP fills `{}`.
2106    #[options("seed?: INT")]
2107    #[optional]
2108    options: BTreeMap<String, Value>,
2109) -> Result<Value> {
2110    let _ = cx;
2111    // `check_options` in the wrapper verified the shape above; the
2112    // read below narrows infallibly after.
2113    let seed = options
2114        .get("seed")
2115        .map(|value| value.as_i64().expect("check_options verified INT"));
2116    super::args::rand_float_from_value(seed)
2117}
2118
2119/// Encode a STRING as standard base64.
2120///
2121/// Padded RFC 4648 alphabet, so encoded output pastes into any
2122/// standard decoder. Pairs with `BASE64_DECODE` for the round trip.
2123///
2124#[oxdock_func(pure, returns = TypeTag::String)]
2125#[example(
2126    name = "encode",
2127    code = r###"
2128    # Encode text to standard base64.
2129    IMPORT [STD]
2130    LET $encoded: STRING = BASE64_ENCODE("hello")
2131    ASSERT_EQ $encoded "aGVsbG8="
2132    "###
2133)]
2134fn base64_encode(
2135    /// Text to encode.
2136    text: String,
2137) -> Result<Value> {
2138    super::args::base64_encode_from_value(Value::string(text))
2139}
2140
2141/// Decode standard base64 to a STRING.
2142///
2143/// Fails naming the input on invalid alphabet characters or
2144/// non-UTF-8 payloads instead of rendering a silent empty. Pairs
2145/// with `BASE64_ENCODE` for the round trip.
2146///
2147#[oxdock_func(pure, returns = TypeTag::String)]
2148#[example(
2149    name = "decode",
2150    code = r###"
2151    # Decode standard base64 back to text.
2152    IMPORT [STD]
2153    LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2154    ASSERT_EQ $decoded "hello"
2155    "###
2156)]
2157fn base64_decode(
2158    /// Base64 text to decode.
2159    text: String,
2160) -> Result<Value> {
2161    super::args::base64_decode_from_value(Value::string(text))
2162}
2163
2164/// Encode a script value as JSON with one trailing newline.
2165///
2166/// Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT,
2167/// BOOL, LIST, MAP) survive, anything else fails here instead of
2168/// rendering as a silent empty.
2169///
2170#[oxdock_func(pure, returns = TypeTag::String)]
2171#[example(
2172    name = "encode",
2173    code = r###"
2174    IMPORT [STD]
2175    LET $json: STRING = TO_JSON({a: 1})
2176    ASSERT_EQ $json "{\"a\":1}\n"
2177    "###
2178)]
2179fn to_json(
2180    /// Value to encode as JSON.
2181    #[union(String, Int, Float, Bool, List, Map)]
2182    value: Value,
2183) -> Result<Value> {
2184    super::args::to_json_from_value(value)
2185}
2186
2187/// Name the word a value holds, for data-driven branching.
2188///
2189/// Returns the registered type word (`STRING`, `INT`, `FLOAT`, `BOOL`,
2190/// `LIST`, `MAP`, plus handle words like `PIPE`): the same name the
2191/// value prints in arity and coercion errors, so scripts can branch
2192/// on config shapes (a path string or a path list) without failing.
2193///
2194#[oxdock_func(pure, returns = TypeTag::String)]
2195#[example(
2196    name = "name the word",
2197    code = r###"
2198    IMPORT [STD]
2199    LET $word: STRING = TYPE_OF(42)
2200    ASSERT_EQ $word "INT"
2201    "###
2202)]
2203fn type_of(
2204    /// Value whose word to name.
2205    value: Value,
2206) -> Result<Value> {
2207    super::args::type_of_from_value(value)
2208}
2209
2210/// Merge a LIST of MAPs in order under one duplicate policy.
2211///
2212/// `fail_on_duplicate` fails naming the repeated key, so two files
2213/// claiming one placeholder fail the run instead of shadowing each
2214/// other. `overwrite` lets later files win, for environment overlays.
2215/// Non MAP elements fail naming their position.
2216///
2217#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2218#[example(
2219    name = "merge",
2220    code = r###"
2221    IMPORT [STD]
2222    LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2223    ASSERT_EQ $m.a 1
2224    ASSERT_EQ $m.b 2
2225    "###
2226)]
2227fn merge_maps(
2228    /// LIST of MAPs to merge in order.
2229    maps: Vec<BTreeMap<String, Value>>,
2230    /// Duplicate policy.
2231    #[values("fail_on_duplicate", "overwrite")]
2232    policy: String,
2233) -> Result<Value> {
2234    super::args::merge_maps_from_value(
2235        Value::list(maps.into_iter().map(Value::map).collect()),
2236        policy,
2237    )
2238}
2239
2240/// Report the running engine version.
2241///
2242/// Returns the workspace version baked in at compile time, so scripts
2243/// and agents can branch on engine behavior instead of probing it.
2244#[oxdock_func(pure, returns = TypeTag::String)]
2245#[example(
2246    name = "report",
2247    code = r###"
2248    # The engine reports its own build version as a dotted string.
2249    IMPORT [STD]
2250    LET $v: STRING = VERSION()
2251    ASSERT_CONTAINS $v "."
2252    "###
2253)]
2254fn version() -> Result<Value> {
2255    Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2256}
2257
2258/// List all visible function names.
2259///
2260/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
2261/// plus host-registered names.
2262#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2263#[example(
2264    name = "list",
2265    code = r###"
2266    IMPORT [STD]
2267    LET $names: LIST<STRING> = FUNCTIONS()
2268    ASSERT_CONTAINS $names "STD::INT"
2269    "###
2270)]
2271fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2272    let mut names: Vec<String> = cx
2273        .state
2274        .list_functions()
2275        .into_iter()
2276        .map(|meta| meta.name)
2277        .collect();
2278    names.sort();
2279    names.dedup();
2280    Ok(Value::list(names.into_iter().map(Value::string).collect()))
2281}
2282
2283/// Report the verbatim CLI tail after the script position.
2284///
2285/// Staged per run from `Options.script_args` (#226): everything after
2286/// the script file (or `--script <file>`), with one leading `--`
2287/// stripped. Never merged with interpreter flags, so `--dry-run`
2288/// after the script arrives here instead of enabling dry-run.
2289#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2290#[example(
2291    name = "empty",
2292    code = r###"
2293    # With no staged args the list is empty.
2294    IMPORT [STD]
2295    LET $args: LIST<STRING> = ARGV()
2296    LET $n: INT = LEN($args)
2297    ASSERT_EQ $n 0
2298    "###
2299)]
2300fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2301    Ok(Value::list(
2302        cx.state
2303            .io
2304            .script_args()
2305            .iter()
2306            .cloned()
2307            .map(Value::string)
2308            .collect(),
2309    ))
2310}
2311
2312/// Parse an argv tail against `TYPE FLAGS`, returning flags and positionals.
2313///
2314/// Consumes a `LIST<STRING>` (usually `STD::ARGV()`) with the `lexopt`
2315/// tokenizer. Long `--key=value` binds the string value. Bare long
2316/// `--key` binds `true`. Short `-a` binds `true`. One `--` entry ends
2317/// option parsing, so the rest lands in `positionals`. Duplicate keys
2318/// overwrite in order, so the last occurrence wins.
2319///
2320/// The schema is always `TYPE FLAGS`: a `MAP` shape with scalar
2321/// fields. Present flags coerce to their target (`BOOL` accepts
2322/// `true`/`false` spellings, `INT`/`FLOAT` parse their strings); bare
2323/// `--key` for a non-`BOOL` target fails naming the flag. Missing
2324/// flags fill their `= default`, missing required flags fail, and
2325/// unknown flags fail. Defaults are literals only: `INT`, `FLOAT`,
2326/// `BOOL`, and double-quoted `STRING`. A variable or expression in
2327/// place of a literal fails the `TYPE` statement, so defaults stay
2328/// plain data in the shape. Absent optional flags without a default stay
2329/// absent (read them with a typed `GET` default). `positionals` is
2330/// omitted when empty, so a flags only `MAP<flags: FLAGS>` binds clean.
2331pub struct ParseArgs;
2332
2333impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
2334    fn registration() -> HostRegistration<P> {
2335        let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2336            if values.len() != 1 {
2337                anyhow::bail!("PARSE_ARGS() expects 1 argument, got {}", values.len());
2338            }
2339            let mut iter = values.into_iter();
2340            let args_val = iter.next().expect("arity checked above");
2341            let args = string_list_arg(&args_val, "PARSE_ARGS() argument `$args`")?;
2342            let specs = resolve_flags_specs(cx)?;
2343            let (raw, positionals) = tokenize_raw_args(args)?;
2344            let coerced = coerce_flags(&specs, &raw)?;
2345            let mut out = BTreeMap::new();
2346            out.insert("flags".to_string(), Value::map(coerced));
2347            if !positionals.is_empty() {
2348                out.insert("positionals".to_string(), Value::list(positionals));
2349            }
2350            Ok(Value::map(out))
2351        });
2352        HostRegistration::Stateful {
2353            name: "PARSE_ARGS".to_string(),
2354            meta: FuncMeta {
2355                name: "PARSE_ARGS".to_string(),
2356                module: String::new(),
2357                kind: FuncKind::HostPure,
2358                params: Some(vec![FuncParam {
2359                    name: "args".to_string(),
2360                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2361                    allowed: None,
2362                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2363                    options: None,
2364                    optional: false,
2365                }]),
2366                returns: Some(TypeTag::Record(Arc::from([
2367                    Field {
2368                        name: "flags".to_string(),
2369                        ty: TypeTag::Map,
2370                        docs: "Flags coerced to `TYPE FLAGS`.",
2371                        optional: false,
2372                        default: None,
2373                    },
2374                    Field {
2375                        name: "positionals".to_string(),
2376                        ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
2377                        docs: "Trailing values and entries after the first double dash. Omitted when empty.",
2378                        optional: true,
2379                        default: None,
2380                    },
2381                ]))),
2382                rpn: true,
2383                summary: "Parse an argv tail against TYPE FLAGS.",
2384                docs: "Consumes a `LIST<STRING>` with the `lexopt` tokenizer and coerces flags through `TYPE FLAGS`. See the function reference for the coercion and omission rules.",
2385                examples: &[
2386                    crate::Example {
2387                        name: "flags and positionals",
2388                        fence_meta: None,
2389                        code: indoc::indoc! {r#"
2390                            IMPORT [STD]
2391                            # One schema TYPE drives coercion; the pair binds both slots.
2392                            TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
2393                            TYPE POSITIONS = LIST<STRING>
2394                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
2395                            LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
2396                            LET $flags: FLAGS = $parsed.flags
2397                            ASSERT_EQ $flags.model "gpt-4"
2398                            ASSERT_EQ $flags.verbose true
2399                            ASSERT_EQ $parsed.positionals.0 "serve"
2400                        "#},
2401                    },
2402                    crate::Example {
2403                        name: "optional stays absent",
2404                        fence_meta: None,
2405                        code: indoc::indoc! {r#"
2406                            IMPORT [STD]
2407                            # Absent optionals stay absent; read them with a typed GET default.
2408                            TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
2409                            TYPE POSITIONS = LIST<STRING>
2410                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
2411                            LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
2412                            LET $flags: FLAGS = $parsed.flags
2413                            LET $propose: BOOL = GET($flags, "propose", false)
2414                            ASSERT_EQ $propose false
2415                        "#},
2416                    },
2417                    crate::Example {
2418                        name: "flags only omits positionals",
2419                        fence_meta: None,
2420                        code: indoc::indoc! {r#"
2421                            IMPORT [STD]
2422                            # Empty positionals are omitted, so a flags only shape binds clean.
2423                            TYPE FLAGS = MAP<model: STRING>
2424                            TYPE PARSED = MAP<flags: FLAGS>
2425                            LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
2426                            LET $flags: FLAGS = $parsed.flags
2427                            ASSERT_EQ $flags.model "x"
2428                        "#},
2429                    },
2430                    crate::Example {
2431                        name: "literal defaults",
2432                        fence_meta: None,
2433                        code: indoc::indoc! {r#"
2434                            IMPORT [STD]
2435                            # Defaults are literals only: INT, FLOAT, BOOL,
2436                            # and double-quoted STRING fill absent flags.
2437                            TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
2438                            TYPE PARSED = MAP<flags: FLAGS>
2439                            LET $parsed: PARSED = PARSE_ARGS([])
2440                            LET $flags: FLAGS = $parsed.flags
2441                            ASSERT_EQ $flags.retries 2
2442                            ASSERT_EQ $flags.verbose true
2443                            ASSERT_EQ $flags.model "gpt-4"
2444                            LET $ratio_ok: BOOL = $flags.ratio == 2.5
2445                            ASSERT_EQ $ratio_ok true
2446                        "#},
2447                    },
2448                    crate::Example {
2449                        name: "variable default fails",
2450                        fence_meta: Some("expect_error:\"expected default literal\""),
2451                        code: indoc::indoc! {r#"
2452                            IMPORT [STD]
2453                            # Defaults are literals: a variable in place
2454                            # of a literal fails instead of evaluating.
2455                            TYPE FLAGS = MAP<n: INT = $x>
2456                            TYPE PARSED = MAP<flags: FLAGS>
2457                            LET $p: PARSED = PARSE_ARGS([])
2458                        "#},
2459                    },
2460                    crate::Example {
2461                        name: "missing required",
2462                        fence_meta: Some("expect_error:\"missing required flag\""),
2463                        code: indoc::indoc! {r#"
2464                            IMPORT [STD]
2465                            # Absent required flags fail naming the flag.
2466                            TYPE FLAGS = MAP<model: STRING>
2467                            TYPE PARSED = MAP<flags: FLAGS>
2468                            LET $parsed: PARSED = PARSE_ARGS([])
2469                        "#},
2470                    },
2471                    crate::Example {
2472                        name: "unknown flag",
2473                        fence_meta: Some("expect_error:\"unknown flag\""),
2474                        code: indoc::indoc! {r#"
2475                            IMPORT [STD]
2476                            # Undeclared flags fail instead of passing through.
2477                            TYPE FLAGS = MAP<model: STRING>
2478                            TYPE PARSED = MAP<flags: FLAGS>
2479                            LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
2480                        "#},
2481                    },
2482                ],
2483            },
2484            func,
2485        }
2486    }
2487}
2488
2489/// CLI target types for `PARSE_ARGS` schemas: the four scalar words
2490/// raw flags can coerce into. No new types without extending the
2491/// coercion below together with the schema resolution below it.
2492#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2493enum CliType {
2494    String,
2495    Bool,
2496    Int,
2497    Float,
2498}
2499
2500/// Coerce one raw flag value to its schema target. Raw values are only
2501/// ever `BOOL true` (bare) or `STRING` (equals form); anything else is
2502/// a caller bug. Bare flags for non-`BOOL` targets fail naming the
2503/// flag instead of smuggling `true` into the slot.
2504fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> Result<Value> {
2505    match target {
2506        CliType::Bool => {
2507            if let Some(b) = raw.as_bool() {
2508                return Ok(Value::bool(b));
2509            }
2510            if let Some(s) = raw.as_str() {
2511                match super::args::parse_bool_str(s) {
2512                    Some(b) => return Ok(Value::bool(b)),
2513                    None => anyhow::bail!(
2514                        "PARSE_ARGS flag --{flag} expects BOOL (true/false, 1/0, yes/no, on/off), got {s:?}"
2515                    ),
2516                }
2517            }
2518            anyhow::bail!(
2519                "PARSE_ARGS flag --{flag} expects BOOL, got {}",
2520                raw.type_name()
2521            )
2522        }
2523        CliType::String => {
2524            if let Some(s) = raw.as_str() {
2525                return Ok(Value::string(s.to_string()));
2526            }
2527            anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2528        }
2529        CliType::Int => {
2530            if raw.as_bool().is_some() {
2531                anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2532            }
2533            super::args::int_from_value(raw)
2534                .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects INT"))
2535        }
2536        CliType::Float => {
2537            if raw.as_bool().is_some() {
2538                anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
2539            }
2540            super::args::float_from_value(raw)
2541                .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects FLOAT"))
2542        }
2543    }
2544}
2545
2546/// One CLI flag spec: target type, required bit, and filled default.
2547/// Single alias so the tokenizer, coercion, and both entry points
2548/// share one signature.
2549type CliSpecs = BTreeMap<String, (CliType, bool, Option<Value>)>;
2550
2551/// Checked `LIST<STRING>` extraction for the CLI trio. Single owner
2552/// so all three functions admit exactly the same argv shape.
2553fn string_list_arg(val: &Value, what: &str) -> Result<Vec<String>> {
2554    crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)?;
2555    Ok(val
2556        .as_list()
2557        .expect("check_value_at enforces LIST")
2558        .iter()
2559        .map(|v| {
2560            v.as_str()
2561                .expect("check_value_at enforces STRING")
2562                .to_string()
2563        })
2564        .collect())
2565}
2566
2567/// Shared argv tokenizer. Single owner so flags versus positionals
2568/// split identically for all three entry points. Raw values are only
2569/// `BOOL true` (bare) or `STRING` (equals form).
2570fn tokenize_raw_args(args: Vec<String>) -> Result<(BTreeMap<String, Value>, Vec<Value>)> {
2571    use lexopt::Arg::{Long, Short, Value as ArgValue};
2572    let mut parser = lexopt::Parser::from_args(args);
2573    let mut flags: BTreeMap<String, Value> = BTreeMap::new();
2574    let mut positionals: Vec<Value> = Vec::new();
2575    let utf8 = |value: std::ffi::OsString| -> Result<String> {
2576        value
2577            .into_string()
2578            .map_err(|_| anyhow::anyhow!("PARSE_ARGS: argument must be UTF-8"))
2579    };
2580    loop {
2581        match parser.next() {
2582            Ok(None) => break,
2583            Ok(Some(Long(name))) => {
2584                let key = name.to_owned();
2585                if let Some(raw) = parser.optional_value() {
2586                    flags.insert(key, Value::string(utf8(raw)?));
2587                } else {
2588                    flags.insert(key, Value::bool(true));
2589                }
2590            }
2591            Ok(Some(Short(ch))) => {
2592                flags.insert(ch.to_string(), Value::bool(true));
2593            }
2594            Ok(Some(ArgValue(raw))) => {
2595                positionals.push(Value::string(utf8(raw)?));
2596            }
2597            Err(lexopt::Error::UnexpectedValue { option, value }) => {
2598                let key = option
2599                    .strip_prefix("--")
2600                    .or_else(|| option.strip_prefix('-'))
2601                    .unwrap_or(option.as_str());
2602                flags.insert(key.to_string(), Value::string(utf8(value)?));
2603            }
2604            Err(err) => anyhow::bail!("PARSE_ARGS: {err}"),
2605        }
2606    }
2607    Ok((flags, positionals))
2608}
2609
2610/// Shared flag coercion. Single owner so `PARSE_ARGS` and
2611/// `PARSE_FLAGS` fill, require, and reject identically: present flags
2612/// coerce, missing defaulted flags fill, missing required flags fail,
2613/// missing optionals stay absent, unknown flags fail.
2614fn coerce_flags(
2615    specs: &CliSpecs,
2616    raw: &BTreeMap<String, Value>,
2617) -> Result<BTreeMap<String, Value>> {
2618    let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
2619    for (flag, (target, required, default)) in specs.iter() {
2620        if flag.is_empty() {
2621            anyhow::bail!("PARSE_ARGS schema flag names must be non-empty");
2622        }
2623        if let Some(raw) = raw.get(flag) {
2624            coerced.insert(flag.clone(), coerce_cli_flag(*target, flag, raw.clone())?);
2625        } else if let Some(d) = default {
2626            coerced.insert(flag.clone(), d.clone());
2627        } else if *required {
2628            anyhow::bail!("PARSE_ARGS missing required flag --{flag}");
2629        }
2630    }
2631    for flag in raw.keys() {
2632        if !specs.contains_key(flag) {
2633            anyhow::bail!("PARSE_ARGS unknown flag --{flag}");
2634        }
2635    }
2636    Ok(coerced)
2637}
2638
2639/// Resolve the fixed `TYPE FLAGS` schema into coercion specs: one entry
2640/// per record field, targets from scalar field types, required unless
2641/// optional or defaulted, defaults filled from the shape. Single owner
2642/// so both pair and flags only entry points admit exactly the same
2643/// set. Non-record types and non-scalar fields fail naming the flag.
2644fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<CliSpecs> {
2645    let name = "FLAGS";
2646    let tag = cx
2647        .state
2648        .resolve_tag(name)
2649        .map_err(|err| anyhow::anyhow!("PARSE_ARGS schema type {name:?}: {err:#}"))?;
2650    let TypeTag::Record(fields) = tag else {
2651        anyhow::bail!("PARSE_ARGS schema type {name:?} must be a MAP shape with scalar fields");
2652    };
2653    let mut specs = BTreeMap::new();
2654    for field in fields.iter() {
2655        let target = match field.ty {
2656            TypeTag::String => CliType::String,
2657            TypeTag::Bool => CliType::Bool,
2658            TypeTag::Int => CliType::Int,
2659            TypeTag::Float => CliType::Float,
2660            _ => anyhow::bail!(
2661                "PARSE_ARGS schema for --{}: type must be one of STRING, BOOL, INT, or FLOAT, got {}",
2662                field.name,
2663                field.ty.name(),
2664            ),
2665        };
2666        specs.insert(
2667            field.name.clone(),
2668            (
2669                target,
2670                !field.optional && field.default.is_none(),
2671                field.default.clone(),
2672            ),
2673        );
2674    }
2675    Ok(specs)
2676}
2677
2678/// Parse flags only against `TYPE FLAGS`.
2679///
2680/// Returns the flags `MAP` directly: no pair wrapper. Positional
2681/// arguments fail instead of dropping silently, so a space-separated
2682/// value (`--model gpt-4`) names the mistake instead of binding
2683/// `--model` to `true` and losing `gpt-4`.
2684/// Same tokenizer, coercion, defaults, and errors as `PARSE_ARGS`.
2685pub struct ParseFlags;
2686
2687impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
2688    fn registration() -> HostRegistration<P> {
2689        let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2690            if values.len() != 1 {
2691                anyhow::bail!("PARSE_FLAGS() expects 1 argument, got {}", values.len());
2692            }
2693            let mut iter = values.into_iter();
2694            let args_val = iter.next().expect("arity checked above");
2695            let args = string_list_arg(&args_val, "PARSE_FLAGS() argument `$args`")?;
2696            let specs = resolve_flags_specs(cx)?;
2697            let (raw, positionals) = tokenize_raw_args(args)?;
2698            if !positionals.is_empty() {
2699                let shown: Vec<String> = positionals.iter().map(|pos| pos.to_string()).collect();
2700                anyhow::bail!(
2701                    "PARSE_FLAGS() does not accept positional arguments; found {}",
2702                    shown.join(", ")
2703                );
2704            }
2705            Ok(Value::map(coerce_flags(&specs, &raw)?))
2706        });
2707        HostRegistration::Stateful {
2708            name: "PARSE_FLAGS".to_string(),
2709            meta: FuncMeta {
2710                name: "PARSE_FLAGS".to_string(),
2711                module: String::new(),
2712                kind: FuncKind::HostPure,
2713                params: Some(vec![FuncParam {
2714                    name: "args".to_string(),
2715                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2716                    allowed: None,
2717                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2718                    options: None,
2719                    optional: false,
2720                }]),
2721                returns: Some(TypeTag::Map),
2722                rpn: true,
2723                summary: "Parse flags against TYPE FLAGS.",
2724                docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
2725                examples: &[crate::Example {
2726                    name: "flags only",
2727                    fence_meta: None,
2728                    code: indoc::indoc! {r#"
2729                        IMPORT [STD]
2730                        # Flags only returns the flags MAP directly.
2731                        TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
2732                        LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
2733                        ASSERT_EQ $flags.model "x"
2734                        ASSERT_EQ $flags.retries 2
2735                    "#},
2736                }],
2737            },
2738            func,
2739        }
2740    }
2741}
2742
2743/// Parse positionals only: no schema, no `TYPE FLAGS` needed.
2744///
2745/// Returns trailing values and entries after the first double dash in
2746/// argv order. Tokenizer matches `PARSE_ARGS` exactly.
2747pub struct ParsePositionals;
2748
2749impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
2750    fn registration() -> HostRegistration<P> {
2751        let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
2752            if values.len() != 1 {
2753                anyhow::bail!(
2754                    "PARSE_POSITIONALS() expects 1 argument, got {}",
2755                    values.len()
2756                );
2757            }
2758            let mut iter = values.into_iter();
2759            let args_val = iter.next().expect("arity checked above");
2760            let args = string_list_arg(&args_val, "PARSE_POSITIONALS() argument `$args`")?;
2761            let (_raw, positionals) = tokenize_raw_args(args)?;
2762            Ok(Value::list(positionals))
2763        });
2764        HostRegistration::Stateful {
2765            name: "PARSE_POSITIONALS".to_string(),
2766            meta: FuncMeta {
2767                name: "PARSE_POSITIONALS".to_string(),
2768                module: String::new(),
2769                kind: FuncKind::HostPure,
2770                params: Some(vec![FuncParam {
2771                    name: "args".to_string(),
2772                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2773                    allowed: None,
2774                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2775                    options: None,
2776                    optional: false,
2777                }]),
2778                returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2779                rpn: true,
2780                summary: "Parse positionals in argv order.",
2781                docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
2782                examples: &[crate::Example {
2783                    name: "positionals only",
2784                    fence_meta: None,
2785                    code: indoc::indoc! {r#"
2786                        IMPORT [STD]
2787                        # No schema needed: positionals are always strings in order.
2788                        TYPE POSITIONS = LIST<STRING>
2789                        LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
2790                        ASSERT_EQ $pos.0 "serve"
2791                        ASSERT_EQ $pos.1 "--not-a-flag"
2792                    "#},
2793                }],
2794            },
2795            func,
2796        }
2797    }
2798}
2799
2800/// Describe one function by qualified name.
2801///
2802/// Returns a MAP with name, module, kind, params, returns, rpn, and
2803/// summary. `params` is always a LIST (empty for parameterless
2804/// functions) of entries carrying name, param_type, allowed, docs,
2805/// options, and optional flags, so the shape holds for every entry. Bare names
2806/// fail closed: `DESCRIBE` requires the qualified form (except
2807/// `INSPECT`, which is syntax rather than a registry entry). Errors
2808/// on unknown function.
2809///
2810/// Field table for the `DESCRIBE` result bundle: one source for the
2811/// shape the host mints, so introspection, enforcement, and
2812/// documentation cannot drift apart.
2813
2814#[oxdock_func(
2815    returns = TypeTag::Record(std::sync::Arc::from([Field {
2816        name: "name".to_string(),
2817        ty: TypeTag::String,
2818        docs: "Qualified function name.",
2819        optional: false,
2820        default: None,
2821    }, Field {
2822        name: "module".to_string(),
2823        ty: TypeTag::String,
2824        docs: "Owning module.",
2825        optional: false,
2826        default: None,
2827    }, Field {
2828        name: "kind".to_string(),
2829        ty: TypeTag::String,
2830        docs: "Origin label (`host` or `script`).",
2831        optional: false,
2832        default: None,
2833    }, Field {
2834        name: "params".to_string(),
2835        ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
2836            TypeTag::Any,
2837        )))),
2838        docs: "Parameter entries (empty for parameterless functions).",
2839        optional: false,
2840        default: None,
2841    }, Field {
2842        name: "returns".to_string(),
2843        ty: TypeTag::String,
2844        docs: "Structural return shape (empty when untagged).",
2845        optional: false,
2846        default: None,
2847    }, Field {
2848        name: "rpn".to_string(),
2849        ty: TypeTag::Bool,
2850        docs: "True when callable in RPN position.",
2851        optional: false,
2852        default: None,
2853    }, Field {
2854        name: "summary".to_string(),
2855        ty: TypeTag::String,
2856        docs: "One-line description.",
2857        optional: false,
2858        default: None,
2859    }]))
2860    summary = "Describe one function by qualified name."
2861)]
2862#[example(
2863    name = "describe",
2864    code = r###"
2865    IMPORT [STD]
2866    LET $info: MAP<ANY> = DESCRIBE("STD::INT")
2867    ASSERT_EQ $info.name "STD::INT"
2868    ASSERT_EQ $info.returns "INT"
2869    "###
2870)]
2871fn describe<P: ProcessManager>(
2872    cx: &mut StepCtx<P>,
2873    /// Qualified function name (`MODULE::NAME`).
2874    name: String,
2875) -> Result<Value> {
2876    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
2877        anyhow::bail!(
2878            "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
2879        );
2880    }
2881    cx.state
2882        .describe_function(&name)
2883        .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
2884}
2885
2886/// List all known type names.
2887///
2888/// Sorted LIST of startup plus host-registered type descriptors. Reads the
2889/// run's name directory, so it runs on the AST path like the other
2890/// introspection functions.
2891#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2892#[example(
2893    name = "list",
2894    code = r###"
2895    IMPORT [STD]
2896    LET $names: LIST<STRING> = TYPES()
2897    ASSERT_CONTAINS $names "STRING"
2898    "###
2899)]
2900fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2901    Ok(Value::list(
2902        cx.state
2903            .type_names()
2904            .into_iter()
2905            .map(Value::string)
2906            .collect(),
2907    ))
2908}
2909
2910/// Describe one type by name.
2911///
2912/// Returns a MAP with name, summary, and docs. Errors on unknown type.
2913/// Reads the run's name directory, so it runs on the AST path.
2914///
2915#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2916    name: "name".to_string(),
2917    ty: TypeTag::String,
2918    docs: "Queried type name.",
2919    optional: false,
2920    default: None,
2921}, Field {
2922    name: "summary".to_string(),
2923    ty: TypeTag::String,
2924    docs: "One-line description.",
2925    optional: false,
2926    default: None,
2927}, Field {
2928    name: "docs".to_string(),
2929    ty: TypeTag::String,
2930    docs: "Full documentation text.",
2931    optional: false,
2932    default: None,
2933}])))]
2934#[example(
2935    name = "describe",
2936    code = r###"
2937    IMPORT [STD]
2938    LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
2939    ASSERT_EQ $info.name "STRING"
2940    "###
2941)]
2942fn type_describe<P: ProcessManager>(
2943    cx: &mut StepCtx<P>,
2944    /// Type name to describe.
2945    name: String,
2946) -> Result<Value> {
2947    if let Some(descriptor) = cx.state.describe_type(&name) {
2948        let mut map = BTreeMap::new();
2949        map.insert(
2950            "name".to_string(),
2951            Value::string(descriptor.name.to_string()),
2952        );
2953        map.insert(
2954            "summary".to_string(),
2955            Value::string(descriptor.summary.to_string()),
2956        );
2957        map.insert(
2958            "docs".to_string(),
2959            Value::string(descriptor.docs.to_string()),
2960        );
2961        return Ok(Value::map(map));
2962    }
2963    // Script aliases have no descriptor but introspect the same way:
2964    // the entry names the alias and its canonical target spelling.
2965    if let Some(target) = cx.state.alias_target(&name) {
2966        let mut map = BTreeMap::new();
2967        map.insert("name".to_string(), Value::string(name.clone()));
2968        map.insert(
2969            "summary".to_string(),
2970            Value::string(format!("Script type alias for {target}.")),
2971        );
2972        map.insert(
2973            "docs".to_string(),
2974            Value::string(format!(
2975                "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
2976            )),
2977        );
2978        return Ok(Value::map(map));
2979    }
2980    Err(anyhow::anyhow!("unknown type {name}"))
2981}
2982
2983/// Path of the running interpreter binary.
2984///
2985/// Returns the executing binary as a `STRING`, so one script can
2986/// reinvoke the interpreter on another script without bridging an env
2987/// var. The child re-parses from bytes in a separate process: no
2988/// bindings cross back (only stdout and files), and each run pays
2989/// a spawn. Prefer modules for reuse (statically gated, in-process);
2990/// reach for reinvocation when the child must run isolated, or under
2991/// a different binary than the parent.
2992///
2993/// Unsupported under Miri isolation: the lookup itself fails there
2994/// instead of returning a path.
2995///
2996#[oxdock_func(returns = TypeTag::String)]
2997#[example(
2998    name = "self",
2999    code = r###"
3000    # The running interpreter resolves to a non-empty path.
3001    IMPORT [STD]
3002    LET $exe: STRING = INTERPRETER()
3003    LET $nonempty: BOOL = $exe != ""
3004    ASSERT_EQ $nonempty true
3005    "###
3006)]
3007#[example(
3008    name = "dynamic assembly",
3009    code = r###"
3010    # Assemble the child script dynamically: the parent interpolates
3011    # its own bindings into the pipe, then runs the interpreter on it.
3012    # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3013    # so the child expands it with its own bindings.
3014    # The pipe delivers EOF when the producer step ends, so the child
3015    # reads exactly one script.
3016    IMPORT [STD]
3017    LET $exe: STRING = INTERPRETER()
3018    LET $who: STRING = "Ada"
3019    LET $child: PIPE
3020    WITH_IO [stdout=$child] ECHO """
3021        ECHO "hello {{ $who }}!"
3022        LET $who: STRING = "Grace"
3023        ECHO "child sees \{{ $who }}!"
3024        """
3025    LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3026    ASSERT_CONTAINS $out "hello Ada!"
3027    ASSERT_CONTAINS $out "child sees Grace!"
3028    "###
3029)]
3030fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3031    if let Some(staged) = cx.state.io.interpreter_override() {
3032        return Ok(Value::string(staged));
3033    }
3034    Ok(Value::string(oxdock_process::interpreter_exe()?))
3035}
3036
3037/// Report whether the current context is the entry script.
3038///
3039/// True at entry top level and inside entry-owned functions; false
3040/// inside module-owned functions and module init bodies. Lets a
3041/// library file double as a runnable demo: guard the demo with
3042/// `IF IS_MAIN()` so importing it stays side-effect free.
3043///
3044#[oxdock_func(returns = TypeTag::Bool)]
3045#[example(
3046    name = "main",
3047    code = r###"
3048    # Entry top level runs as main.
3049    IMPORT [STD]
3050    LET $m: BOOL = IS_MAIN()
3051    ASSERT_EQ $m true
3052    "###
3053)]
3054#[example(
3055    name = "library doubles as demo",
3056    fence_meta = "roots:unified",
3057    code = r###"
3058    # A library doubles as a runnable demo: guard the demo with
3059    # IF IS_MAIN() so importing it stays side effect free. The
3060    # parent writes both files, then runs each in a fresh
3061    # interpreter: direct execution prints the demo, importing
3062    # it does not. Unified roots: the child inherits one
3063    # workspace, so parent and child see the same files. The
3064    # exact stdout match proves the demo line stays out of the
3065    # importing run.
3066    IMPORT [STD]
3067
3068    # The library under test: demo guarded by IS_MAIN.
3069    WRITE lib.oxfile """
3070        IMPORT [STD]
3071        FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3072        EXPORT GREET
3073        IF IS_MAIN() {
3074            ECHO "demo: hi Ada"
3075        }
3076        """
3077
3078    # The importer: calls the library, prints only its own line.
3079    WRITE main.oxfile """
3080        IMPORT ["lib.oxfile" AS LIB]
3081        LET $g: STRING = LIB::GREET("Bo")
3082        ECHO "imported: \{{ $g }}"
3083        """
3084
3085    # Direct run executes the demo.
3086    LET $exe: STRING = INTERPRETER()
3087    LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3088    ASSERT_CONTAINS $direct "demo: hi Ada"
3089
3090    # Importing run stays silent apart from its own line.
3091    LET $via: STRING = RUN [$exe, "main.oxfile"]
3092    ASSERT_EQ $via "imported: hi Bo\n"
3093    "###
3094)]
3095fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3096    let main = match cx.state.module_stack.last() {
3097        None | Some(None) => true,
3098        Some(Some(_)) => false,
3099    };
3100    Ok(Value::bool(main))
3101}
3102
3103/// Report whether a standard stream is a terminal.
3104///
3105/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
3106/// answers for the step's stream as currently bound, so scripts can adapt
3107/// prompts, colors, and progress output. Anything diverted from the
3108/// terminal reports false without touching host handles: `WITH_IO` pipe
3109/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
3110/// runner sinks, and any materialized stdin stream (only a directly
3111/// inherited fd falls back to the process check). A transparent root tee
3112/// still answers the session question via the process check. The name
3113/// matches exactly (no case folding): anything else bails. AST-only:
3114/// reads the step context like the other introspection functions.
3115///
3116#[oxdock_func(returns = TypeTag::Bool)]
3117#[example(
3118    name = "null stdin",
3119    code = r###"
3120    # A null stdin is never a terminal, in every harness.
3121    IMPORT [STD]
3122    LET $term: BOOL = IS_TERMINAL("stdin")
3123    ASSERT_EQ $term false
3124    "###
3125)]
3126fn is_terminal<P: ProcessManager>(
3127    cx: &mut StepCtx<P>,
3128    /// Stream name: `stdin`, `stdout`, or `stderr` (exact match).
3129    #[values("stdin", "stdout", "stderr")]
3130    stream_name: String,
3131) -> Result<Value> {
3132    use std::io::IsTerminal;
3133    let terminal = match stream_name.as_str() {
3134        "stdin" => {
3135            // A script-pipe backend is definitive; Null is /dev/null.
3136            // Only a directly inherited fd answers the process check: a
3137            // materialized Stream is always a binding (staged input,
3138            // WITH_IO pipe, or OS half), never the raw fd.
3139            if cx.stdin_pipe.is_some() {
3140                false
3141            } else {
3142                match &cx.stdin {
3143                    CommandStdin::Null => false,
3144                    #[cfg(not(miri))]
3145                    CommandStdin::OsPipe(_) => false,
3146                    CommandStdin::Stream(_) => false,
3147                    CommandStdin::Inherit => std::io::stdin().is_terminal(),
3148                }
3149            }
3150        }
3151        "stdout" => {
3152            if cx.out_pipe.is_some() {
3153                // WITH_IO script-pipe binding: never a terminal.
3154                false
3155            } else if cx.state.io.stdout().is_some() {
3156                // Staged runner sink: the root tee diverts bytes to the
3157                // sink only, never to real stdout.
3158                false
3159            } else {
3160                match &cx.out {
3161                    // Unbound: inherited straight through.
3162                    None => std::io::stdout().is_terminal(),
3163                    // OS kernel pipe: never a terminal.
3164                    #[cfg(not(miri))]
3165                    Some(StreamHandle::Os(_)) => false,
3166                    // Root tee (transparent: forwards to real stdout when
3167                    // unstaged, so terminal-ness survives) versus a genuine
3168                    // diversion. WITH_IO bindings never reach here (script
3169                    // pipes trip out_pipe, OS pipes trip Os, staged sinks
3170                    // trip above). LET-capture cannot reach here either:
3171                    // assign_capture installs no sink for a bare NAME(...)
3172                    // call, so a direct query always observes the ambient
3173                    // routing. The process check answers the session
3174                    // question.
3175                    Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
3176                }
3177            }
3178        }
3179        "stderr" => {
3180            if cx.state.io.stderr().is_some() {
3181                // Staged runner sink: diverted, never a terminal.
3182                false
3183            } else {
3184                match &cx.err {
3185                    // Unbound: inherited straight through.
3186                    None => std::io::stderr().is_terminal(),
3187                    // OS kernel pipe: never a terminal.
3188                    #[cfg(not(miri))]
3189                    Some(StreamHandle::Os(_)) => false,
3190                    // Root never tees stderr and LET never captures it,
3191                    // so a bound handle here is always a WITH_IO binding.
3192                    Some(StreamHandle::Stream(_)) => false,
3193                }
3194            }
3195        }
3196        _ => anyhow::bail!(
3197            // Unreachable through the macro path: the generated
3198            // extractor rejects non-members before the body runs, and
3199            // the static pre-pass rejects bad literals earlier still.
3200            // Kept as a bail (never a panic) for hand-built callers.
3201            "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
3202        ),
3203    };
3204    Ok(Value::bool(terminal))
3205}
3206
3207/// Create a counting semaphore admitting at most `max` concurrent holders.
3208///
3209/// Non-positive maxima bail. The word names a shared backend: every clone
3210/// observes the same count, and admission runs through
3211/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
3212/// readout.
3213///
3214#[oxdock_func(returns = TypeTag::Semaphore)]
3215#[example(
3216    name = "mint",
3217    code = r###"
3218    # Mint a semaphore admitting at most two holders.
3219    IMPORT [STD]
3220    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3221
3222    # A fresh semaphore reports its full cap as available.
3223    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3224    ASSERT_EQ $free 2
3225    "###
3226)]
3227fn semaphore_new<P: ProcessManager>(
3228    cx: &mut StepCtx<P>,
3229    /// Maximum concurrent holders; must be positive.
3230    max: i64,
3231) -> Result<Value> {
3232    let _ = cx;
3233    if max <= 0 {
3234        return Err(anyhow::anyhow!(
3235            "SEMAPHORE_NEW() requires a positive max, got {max}"
3236        ));
3237    }
3238    Ok(Value::semaphore(max as usize))
3239}
3240
3241/// Attempt one non-blocking acquire, always answering a MAP.
3242///
3243/// `held` is `true` with the permit under the `permit` key, or `false`
3244/// with no `permit` key: branch on `$m.held` directly. The DSL has no
3245/// null, so the absent key is the miss shape. Do not read `$m.permit`
3246/// unless `held`: missing-key access bails strictly.
3247/// Never waits, so no wait can wedge.
3248///
3249#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3250    name: "held".to_string(),
3251    ty: TypeTag::Bool,
3252    docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
3253    optional: false,
3254    default: None,
3255}, Field {
3256    name: "permit".to_string(),
3257    ty: TypeTag::Permit,
3258    docs: "Permit handle; read only when `held`.",
3259    optional: true,
3260    default: None,
3261}])))]
3262#[example(
3263    name = "acquire",
3264    code = r###"
3265    # First acquire holds with a permit to bind.
3266    IMPORT [STD]
3267    LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
3268    LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3269    ASSERT_EQ $first.held true
3270    LET $permit: PERMIT = $first.permit
3271
3272    # A capped semaphore answers held false with no permit key.
3273    LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3274    ASSERT_EQ $second.held false
3275    LET $has_permit: BOOL = HAS_KEY($second, "permit")
3276    ASSERT_EQ $has_permit false
3277    "###
3278)]
3279fn semaphore_try_acquire<P: ProcessManager>(
3280    cx: &mut StepCtx<P>,
3281    /// Semaphore handle from `SEMAPHORE_NEW`.
3282    sem: Arc<SemaphoreState>,
3283) -> Result<Value> {
3284    let _ = cx;
3285    let mut map = BTreeMap::new();
3286    if sem.try_acquire() {
3287        map.insert("held".to_string(), Value::bool(true));
3288        map.insert("permit".to_string(), Value::permit(&sem));
3289    } else {
3290        map.insert("held".to_string(), Value::bool(false));
3291    }
3292    Ok(Value::map(map))
3293}
3294
3295/// Read free permits under the lock, with no mutation.
3296///
3297/// Observability only (audit lines, healthchecks: `active = max - free`).
3298/// Exact at read time and stale the instant the caller acts on it, so it
3299/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
3300///
3301#[oxdock_func(pure, returns = TypeTag::Int)]
3302#[example(
3303    name = "readout",
3304    code = r###"
3305    # Hold one permit on a cap of two.
3306    IMPORT [STD]
3307    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3308    LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3309    ASSERT_EQ $acq.held true
3310
3311    # One held permit leaves exactly one free.
3312    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3313    ASSERT_EQ $free 1
3314    "###
3315)]
3316fn semaphore_available(
3317    /// Semaphore handle from `SEMAPHORE_NEW`.
3318    sem: Arc<SemaphoreState>,
3319) -> Result<Value> {
3320    Ok(Value::int(sem.available() as i64))
3321}
3322
3323/// Trim Unicode whitespace from both ends of text.
3324///
3325/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
3326/// Pipes stream on a pump thread with O(chunk) memory: leading
3327/// whitespace falls at the stream head while trailing whitespace
3328/// holds in the spill substrate until the next segment proves it
3329/// interior, so unbounded streams never buffer unbounded memory.
3330///
3331#[oxdock_func(
3332    rpn,
3333    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3334    template = text_trim_string
3335)]
3336#[example(
3337    name = "trim",
3338    code = r###"
3339    # Leading and trailing whitespace falls away.
3340    IMPORT [STD]
3341    LET $clean: STRING = TEXT_TRIM("  hello  ")
3342    ASSERT_EQ $clean "hello"
3343    "###
3344)]
3345#[example(
3346    name = "trim pipe mirrors",
3347    code = r###"
3348    # Pipe input mints pipe output with the same transform.
3349    IMPORT [STD]
3350    LET $cap: PIPE
3351    WITH_IO [stdout=$cap] {
3352        ECHO "  hello  "
3353    }
3354    LET $out: PIPE = TEXT_TRIM($cap)
3355    WITH_IO [stdin=$out] READ_LINE $line
3356    ASSERT_EQ $line "hello"
3357    "###
3358)]
3359#[example(
3360    name = "trim template",
3361    code = r###"
3362    # String inputs run inside placeholders too.
3363    IMPORT [STD]
3364    LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM("  hello  ") }}'
3365    ASSERT_EQ $msg "clean:hello"
3366    "###
3367)]
3368#[example(
3369    name = "trim file template",
3370    code = r###"
3371    # EXPAND templates resolve the same registry.
3372    IMPORT [STD]
3373    WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\"  hello  \") }}"
3374    LET $out: STRING = EXPAND "tpl.txt"
3375    ASSERT_EQ $out "clean:hello"
3376    "###
3377)]
3378fn text_trim<P: ProcessManager>(
3379    cx: &mut StepCtx<P>,
3380    /// Text to trim.
3381    #[union(String, Pipe)]
3382    text: Value,
3383) -> Result<Value> {
3384    super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
3385}
3386
3387/// Template projection of `TEXT_TRIM`: the same trim for `{{ }}`
3388/// placeholders, which carry no step IO for pipes.
3389fn text_trim_string(text: Value) -> Result<Value> {
3390    super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
3391}
3392
3393/// Strip one leading prefix, returning the input unchanged when absent.
3394///
3395/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
3396/// Pipes decide on the first `prefix.len()` bytes and stream the rest
3397/// untouched. Matching is case-sensitive; there is no
3398/// case-insensitive mode.
3399/// Used for tag prefix strips such as `v1.2.3` to `1.2.3`.
3400///
3401#[oxdock_func(
3402    rpn,
3403    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3404    template = text_trim_prefix_string
3405)]
3406#[example(
3407    name = "strip prefix",
3408    code = r###"
3409    # A present prefix falls away; absence returns the input unchanged.
3410    IMPORT [STD]
3411    LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
3412    ASSERT_EQ $bare "1.2.3"
3413
3414    # Missing prefixes pass through untouched.
3415    LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
3416    ASSERT_EQ $same "1.2.3"
3417    "###
3418)]
3419#[example(
3420    name = "strip prefix pipe mirrors",
3421    code = r###"
3422    # Pipe input mints pipe output with the same strip.
3423    IMPORT [STD]
3424    LET $cap: PIPE
3425    WITH_IO [stdout=$cap] {
3426        ECHO "v1.2.3"
3427    }
3428    LET $trimmed: PIPE = TEXT_TRIM($cap)
3429    LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
3430    WITH_IO [stdin=$out] READ_LINE $line
3431    ASSERT_EQ $line "1.2.3"
3432    "###
3433)]
3434#[example(
3435    name = "strip prefix template",
3436    code = r###"
3437    # String inputs run inside placeholders too.
3438    IMPORT [STD]
3439    LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
3440    ASSERT_EQ $msg "bare:1.2.3"
3441    "###
3442)]
3443fn text_trim_prefix<P: ProcessManager>(
3444    cx: &mut StepCtx<P>,
3445    /// Text to strip.
3446    #[union(String, Pipe)]
3447    text: Value,
3448    /// Leading prefix to remove once.
3449    prefix: String,
3450) -> Result<Value> {
3451    super::args::mirror_stream(
3452        cx,
3453        "TEXT_TRIM_PREFIX",
3454        &text,
3455        super::args::TextPump::TrimPrefix(prefix),
3456    )
3457}
3458
3459/// Template projection of `TEXT_TRIM_PREFIX`: the same strip for
3460/// `{{ }}` placeholders, which carry no step IO for pipes.
3461fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
3462    super::args::mirror_string(
3463        "TEXT_TRIM_PREFIX",
3464        &text,
3465        super::args::TextPump::TrimPrefix(prefix),
3466    )
3467}
3468
3469/// Strip one trailing suffix, returning the input unchanged when absent.
3470///
3471/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
3472/// Pipes hold a `suffix.len()` trailing window and stream the rest.
3473/// Matching is case-sensitive; there is no case-insensitive mode.
3474///
3475#[oxdock_func(
3476    rpn,
3477    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3478    template = text_trim_suffix_string
3479)]
3480#[example(
3481    name = "strip suffix",
3482    code = r###"
3483    # A present suffix falls away; absence returns the input unchanged.
3484    IMPORT [STD]
3485    LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
3486    ASSERT_EQ $bare "archive.tar"
3487
3488    # Missing suffixes pass through untouched.
3489    LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
3490    ASSERT_EQ $same "archive.tar"
3491    "###
3492)]
3493#[example(
3494    name = "strip suffix pipe mirrors",
3495    code = r###"
3496    # Pipe input mints pipe output with the same strip.
3497    IMPORT [STD]
3498    LET $cap: PIPE
3499    WITH_IO [stdout=$cap] {
3500        ECHO "archive.tar.gz"
3501    }
3502    LET $trimmed: PIPE = TEXT_TRIM($cap)
3503    LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
3504    WITH_IO [stdin=$out] READ_LINE $line
3505    ASSERT_EQ $line "archive.tar"
3506    "###
3507)]
3508#[example(
3509    name = "strip suffix template",
3510    code = r###"
3511    # String inputs run inside placeholders too.
3512    IMPORT [STD]
3513    LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
3514    ASSERT_EQ $msg "bare:archive.tar"
3515    "###
3516)]
3517fn text_trim_suffix<P: ProcessManager>(
3518    cx: &mut StepCtx<P>,
3519    /// Text to strip.
3520    #[union(String, Pipe)]
3521    text: Value,
3522    /// Trailing suffix to remove once.
3523    suffix: String,
3524) -> Result<Value> {
3525    super::args::mirror_stream(
3526        cx,
3527        "TEXT_TRIM_SUFFIX",
3528        &text,
3529        super::args::TextPump::TrimSuffix(suffix),
3530    )
3531}
3532
3533/// Template projection of `TEXT_TRIM_SUFFIX`: the same strip for
3534/// `{{ }}` placeholders, which carry no step IO for pipes.
3535fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
3536    super::args::mirror_string(
3537        "TEXT_TRIM_SUFFIX",
3538        &text,
3539        super::args::TextPump::TrimSuffix(suffix),
3540    )
3541}
3542
3543/// Join a directory and a file name with the host-native separator.
3544///
3545/// Both inputs accept `STRING` or workspace `PATH` words; the result
3546/// is a `STRING` joined with the platform separator, so installers
3547/// never hand-roll separators in templates. No filesystem access:
3548/// missing parents fail later at the consumer. Stays `STRING` (not
3549/// `PATH`) on purpose: the joined value is a not-yet-validated
3550/// destination string like `$dir` itself, and `PATH` words
3551/// re-canonicalize to forward slashes on template expansion, which
3552/// would undo the native join.
3553#[oxdock_func(returns = TypeTag::String)]
3554#[example(
3555    name = "join path",
3556    code = r###"
3557    # Directory and file stem join with the native separator.
3558    # Source `\\` is one backslash at runtime; `/` works on Windows
3559    # too, native just reads better there.
3560    IMPORT [STD]
3561    LET $p: STRING = PATH_JOIN("some-dir", "some-file")
3562    [family:unix] ASSERT_EQ $p "some-dir/some-file"
3563    [family:windows] ASSERT_EQ $p "some-dir\\some-file"
3564    "###
3565)]
3566fn path_join<P: ProcessManager>(
3567    _cx: &mut StepCtx<P>,
3568    /// Directory half of the destination.
3569    #[union(String, Path)]
3570    dir: Value,
3571    /// File half of the destination.
3572    #[union(String, Path)]
3573    name: Value,
3574) -> Result<Value> {
3575    let d = super::args::string_or_path_text(&dir)?;
3576    let n = super::args::string_or_path_text(&name)?;
3577    Ok(Value::string(oxdock_fs::join_native(&d, &n)))
3578}
3579
3580/// Uppercase text with full Unicode mapping.
3581///
3582/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
3583/// Pipes map chunk by chunk across a char-boundary carry, so
3584/// multibyte characters split across reads still fold correctly.
3585///
3586#[oxdock_func(
3587    rpn,
3588    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3589    template = text_to_upper_string
3590)]
3591#[example(
3592    name = "uppercase",
3593    code = r###"
3594    # Text folds to uppercase.
3595    IMPORT [STD]
3596    LET $loud: STRING = TEXT_TO_UPPER("hello")
3597    ASSERT_EQ $loud "HELLO"
3598    "###
3599)]
3600#[example(
3601    name = "uppercase pipe mirrors",
3602    code = r###"
3603    # Pipe input mints pipe output with the same fold.
3604    IMPORT [STD]
3605    LET $cap: PIPE
3606    WITH_IO [stdout=$cap] {
3607        ECHO "hello"
3608    }
3609    LET $out: PIPE = TEXT_TO_UPPER($cap)
3610    WITH_IO [stdin=$out] READ_LINE $line
3611    ASSERT_EQ $line "HELLO"
3612    "###
3613)]
3614#[example(
3615    name = "uppercase template",
3616    code = r###"
3617    # String inputs run inside placeholders too.
3618    IMPORT [STD]
3619    LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
3620    ASSERT_EQ $msg "loud:HELLO"
3621    "###
3622)]
3623fn text_to_upper<P: ProcessManager>(
3624    cx: &mut StepCtx<P>,
3625    /// Text to uppercase.
3626    #[union(String, Pipe)]
3627    text: Value,
3628) -> Result<Value> {
3629    super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3630}
3631
3632/// Template projection of `TEXT_TO_UPPER`: the same fold for `{{ }}`
3633/// placeholders, which carry no step IO for pipes.
3634fn text_to_upper_string(text: Value) -> Result<Value> {
3635    super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
3636}
3637
3638/// Lowercase text with full Unicode mapping.
3639///
3640/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
3641/// Pipes map chunk by chunk across a char-boundary carry, like
3642/// `TEXT_TO_UPPER`.
3643///
3644#[oxdock_func(
3645    rpn,
3646    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3647    template = text_to_lower_string
3648)]
3649#[example(
3650    name = "lowercase",
3651    code = r###"
3652    # Text folds to lowercase.
3653    IMPORT [STD]
3654    LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
3655    ASSERT_EQ $quiet "hello"
3656    "###
3657)]
3658#[example(
3659    name = "lowercase pipe mirrors",
3660    code = r###"
3661    # Pipe input mints pipe output with the same fold.
3662    IMPORT [STD]
3663    LET $cap: PIPE
3664    WITH_IO [stdout=$cap] {
3665        ECHO "HELLO"
3666    }
3667    LET $out: PIPE = TEXT_TO_LOWER($cap)
3668    WITH_IO [stdin=$out] READ_LINE $line
3669    ASSERT_EQ $line "hello"
3670    "###
3671)]
3672#[example(
3673    name = "lowercase template",
3674    code = r###"
3675    # String inputs run inside placeholders too.
3676    IMPORT [STD]
3677    LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
3678    ASSERT_EQ $msg "quiet:hello"
3679    "###
3680)]
3681fn text_to_lower<P: ProcessManager>(
3682    cx: &mut StepCtx<P>,
3683    /// Text to lowercase.
3684    #[union(String, Pipe)]
3685    text: Value,
3686) -> Result<Value> {
3687    super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3688}
3689
3690/// Template projection of `TEXT_TO_LOWER`: the same fold for `{{ }}`
3691/// placeholders, which carry no step IO for pipes.
3692fn text_to_lower_string(text: Value) -> Result<Value> {
3693    super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
3694}
3695
3696/// Replace every literal occurrence of `from` with `to`.
3697///
3698/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
3699/// Pipes scan through a `from.len()` sliding window, so needles split
3700/// across chunk reads still rewrite.
3701/// Literal sliding search, not a pattern: an empty `from` fails
3702/// closed, and regex work with captures belongs to
3703/// `TEXT_REPLACE_REGEX`. Matching is case-sensitive; there is no
3704/// case-insensitive mode.
3705///
3706#[oxdock_func(
3707    rpn,
3708    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3709    template = text_replace_string
3710)]
3711#[example(
3712    name = "replace",
3713    code = r###"
3714    # Every literal occurrence rewrites in place.
3715    IMPORT [STD]
3716    LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
3717    ASSERT_EQ $fixed "hello there"
3718    "###
3719)]
3720#[example(
3721    name = "replace pipe mirrors",
3722    code = r###"
3723    # Pipe input mints pipe output with the same rewrite.
3724    IMPORT [STD]
3725    LET $cap: PIPE
3726    WITH_IO [stdout=$cap] {
3727        ECHO "hello world"
3728    }
3729    LET $trimmed: PIPE = TEXT_TRIM($cap)
3730    LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
3731    WITH_IO [stdin=$out] READ_LINE $line
3732    ASSERT_EQ $line "hello there"
3733    "###
3734)]
3735#[example(
3736    name = "replace template",
3737    code = r###"
3738    # String inputs run inside placeholders too.
3739    IMPORT [STD]
3740    LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
3741    ASSERT_EQ $msg "fixed:hello there"
3742    "###
3743)]
3744fn text_replace<P: ProcessManager>(
3745    cx: &mut StepCtx<P>,
3746    /// Text to rewrite.
3747    #[union(String, Pipe)]
3748    text: Value,
3749    /// Literal text to search for; empty fails closed.
3750    from: String,
3751    /// Literal replacement text.
3752    to: String,
3753) -> Result<Value> {
3754    super::args::mirror_stream(
3755        cx,
3756        "TEXT_REPLACE",
3757        &text,
3758        super::args::TextPump::ReplaceLiteral { from, to },
3759    )
3760}
3761
3762/// Template projection of `TEXT_REPLACE`: the same rewrite for `{{ }}`
3763/// placeholders, which carry no step IO for pipes.
3764fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
3765    super::args::mirror_string(
3766        "TEXT_REPLACE",
3767        &text,
3768        super::args::TextPump::ReplaceLiteral { from, to },
3769    )
3770}
3771
3772/// Replace every regex match, expanding `$1` and `$name` captures.
3773///
3774/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
3775/// Eager-only framing: matches span chunks, so pipe inputs stage
3776/// through the spill substrate instead of streaming.
3777/// Bad patterns fail closed naming the pattern and its position.
3778/// Matching is case-sensitive unless the pattern carries an inline
3779/// `(?i)` flag, which makes uppercase and lowercase letters match
3780/// each other.
3781/// The literal counterpart is `TEXT_REPLACE`.
3782///
3783#[oxdock_func(
3784    rpn,
3785    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
3786    template = text_replace_regex_string
3787)]
3788#[example(
3789    name = "replace with captures",
3790    code = r###"
3791    # Capture groups expand in the replacement.
3792    IMPORT [STD]
3793    LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
3794    ASSERT_EQ $swapped "13/10/2026"
3795    "###
3796)]
3797#[example(
3798    name = "replace regex pipe mirrors",
3799    code = r###"
3800    # Pipe input mints pipe output with the same rewrite.
3801    IMPORT [STD]
3802    LET $cap: PIPE
3803    WITH_IO [stdout=$cap] {
3804        ECHO "2026-10-13"
3805    }
3806    LET $trimmed: PIPE = TEXT_TRIM($cap)
3807    LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
3808    WITH_IO [stdin=$out] READ_LINE $line
3809    ASSERT_EQ $line "13/10/2026"
3810    "###
3811)]
3812#[example(
3813    name = "replace regex template",
3814    code = r###"
3815    # String inputs run inside placeholders too.
3816    IMPORT [STD]
3817    LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
3818    ASSERT_EQ $msg "swapped:13/10/2026"
3819    "###
3820)]
3821fn text_replace_regex<P: ProcessManager>(
3822    cx: &mut StepCtx<P>,
3823    /// Text to rewrite.
3824    #[union(String, Pipe)]
3825    text: Value,
3826    /// Regex pattern to match.
3827    pattern: String,
3828    /// Replacement with `$1` and `$name` capture expansion.
3829    replacement: String,
3830) -> Result<Value> {
3831    if let Some(s) = text.as_str() {
3832        let out =
3833            super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
3834        return Ok(Value::string(out));
3835    }
3836    let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
3837    let out = super::args::text_replace_regex_str(
3838        &content,
3839        &pattern,
3840        &replacement,
3841        "TEXT_REPLACE_REGEX",
3842    )?;
3843    super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
3844}
3845
3846/// Template projection of `TEXT_REPLACE_REGEX`: the same rewrite for
3847/// `{{ }}` placeholders, which carry no step IO for pipes.
3848fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
3849    let Some(s) = text.as_str() else {
3850        return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
3851    };
3852    let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
3853    Ok(Value::string(out))
3854}
3855
3856/// Split text on a literal delimiter into a `LIST<STRING>`.
3857///
3858/// An empty delimiter splits into single characters. Eager-only by
3859/// design: splitting into a list has no line framing to stream.
3860/// Delimiters match case-sensitively; there is no
3861/// case-insensitive mode.
3862///
3863#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3864#[example(
3865    name = "split",
3866    code = r###"
3867    # Delimiters split into list items.
3868    IMPORT [STD]
3869    LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
3870    ASSERT_EQ $parts.0 "a"
3871    ASSERT_EQ $parts.1 "b"
3872    ASSERT_EQ $parts.2 "c"
3873    "###
3874)]
3875fn text_split(
3876    /// Text to split.
3877    text: String,
3878    /// Literal delimiter; empty splits into characters.
3879    delimiter: String,
3880) -> Result<Value> {
3881    Ok(super::args::text_list_value(super::args::text_split_str(
3882        &text, &delimiter,
3883    )))
3884}
3885
3886/// Join a `LIST<STRING>` with a literal separator into a `STRING`.
3887///
3888#[oxdock_func(pure, returns = TypeTag::String)]
3889#[example(
3890    name = "join",
3891    code = r###"
3892    # List items join with the separator between them.
3893    IMPORT [STD]
3894    LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
3895    ASSERT_EQ $joined "a,b,c"
3896    "###
3897)]
3898fn text_join(
3899    /// List elements to join.
3900    elements: Vec<String>,
3901    /// Literal delimiter placed between elements.
3902    delimiter: String,
3903) -> Result<Value> {
3904    Ok(Value::string(elements.join(delimiter.as_str())))
3905}
3906
3907/// Split a shell command string into argv words.
3908///
3909/// Parses POSIX shell word syntax (single and double quotes, backslash
3910/// escapes) with the `shell-words` crate, the same splitter the remote
3911/// plugins use. Returns a `LIST<STRING>`. Unbalanced quotes fail.
3912/// Inverse of `SHELL_JOIN_ARGS`: joining the result re-splits
3913/// to the same words.
3914///
3915/// Shell syntax only: plain prose with no quoting splits on
3916/// whitespace like any shell would, which is rarely what prose wants.
3917///
3918#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3919#[example(
3920    name = "split args",
3921    code = r###"
3922    # Quoted segments stay one word.
3923    IMPORT [STD]
3924    LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
3925    ASSERT_EQ $argv.0 "gh"
3926    ASSERT_EQ $argv.3 "153"
3927    ASSERT_EQ $argv.5 "notes.md"
3928
3929    # Quotes and escapes parse the shell way.
3930    LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
3931    ASSERT_EQ $quoted.0 "say"
3932    ASSERT_EQ $quoted.1 "hi there"
3933    ASSERT_EQ $quoted.2 "a b"
3934    "###
3935)]
3936fn shell_split_args(
3937    /// Shell command string to split into words.
3938    command: String,
3939) -> Result<Value> {
3940    match shell_words::split(&command) {
3941        Ok(words) => Ok(super::args::text_list_value(words)),
3942        Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
3943    }
3944}
3945
3946/// Join argv words into one shell-parseable string.
3947///
3948/// Quotes each word with POSIX single-quote escaping through the
3949/// `shell-words` crate, so the result re-splits to the same words.
3950/// Inverse of `SHELL_SPLIT_ARGS` on the word side: splitting the
3951/// result returns the input list unchanged.
3952///
3953#[oxdock_func(pure, returns = TypeTag::String)]
3954#[example(
3955    name = "join args",
3956    code = r###"
3957    # Plain words join with spaces and no quoting.
3958    IMPORT [STD]
3959    LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
3960    ASSERT_EQ $plain "gh issue list"
3961
3962    # Words with spaces quote, and the round trip is exact.
3963    LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
3964    LET $joined: STRING = SHELL_JOIN_ARGS($words)
3965    LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
3966    ASSERT_EQ $back.0 "say"
3967    ASSERT_EQ $back.1 "hi there"
3968    ASSERT_EQ $back.2 "a'b"
3969    "###
3970)]
3971fn shell_join_args(
3972    /// Words to join into a shell command string.
3973    words: Vec<String>,
3974) -> Result<Value> {
3975    Ok(Value::string(shell_words::join(&words)))
3976}
3977
3978/// Split text into lines with universal newline handling.
3979///
3980/// Normalizes through the line-ending crate first so LF, CRLF, CR,
3981/// and mixed endings all split, then delegates the split itself to
3982/// `LineEnding::split` instead of hand-rolled scanning.
3983/// Returns a `LIST<STRING>`; eager-only like `TEXT_SPLIT`.
3984///
3985#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3986#[example(
3987    name = "lines",
3988    code = r###"
3989    # Newlines split into line items.
3990    IMPORT [STD]
3991    LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
3992    ASSERT_EQ $lines.0 "one"
3993    ASSERT_EQ $lines.1 "two"
3994    ASSERT_EQ $lines.2 "three"
3995
3996    # Windows endings split the same way after normalization.
3997    LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
3998    ASSERT_EQ $crlf.0 "one"
3999    ASSERT_EQ $crlf.1 "two"
4000    ASSERT_EQ $crlf.2 "three"
4001
4002    # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4003    LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4004    ASSERT_EQ $mixed.0 "a"
4005    ASSERT_EQ $mixed.1 "b"
4006    ASSERT_EQ $mixed.2 "c"
4007    ASSERT_EQ $mixed.3 "d"
4008    "###
4009)]
4010fn text_lines(
4011    /// Text to split into lines.
4012    text: String,
4013) -> Result<Value> {
4014    Ok(super::args::text_list_value(super::args::text_lines_str(
4015        &text,
4016    )))
4017}
4018
4019/// Split text into whitespace-separated fields, ignoring empties.
4020///
4021/// Returns a `LIST<STRING>`; the checksum-line parser that replaces
4022/// `cut -d' ' -f1` in CI legs.
4023///
4024#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4025#[example(
4026    name = "fields",
4027    code = r###"
4028    # Runs of whitespace separate fields; empties never appear.
4029    IMPORT [STD]
4030    LET $fields: LIST<STRING> = TEXT_FIELDS("  abc  def ")
4031    ASSERT_EQ $fields.0 "abc"
4032    ASSERT_EQ $fields.1 "def"
4033    "###
4034)]
4035fn text_fields(
4036    /// Text to split into fields.
4037    text: String,
4038) -> Result<Value> {
4039    Ok(super::args::text_list_value(super::args::text_fields_str(
4040        &text,
4041    )))
4042}
4043
4044/// Read lines `from` through `to` as a `LIST<STRING>`: the `sed -n
4045/// 'A,Bp'` window over universal newlines, for reading one file
4046/// section without holding the surrounding text.
4047///
4048/// Lines are 1-based and inclusive on both ends. Ranges past the end
4049/// clamp like sed instead of failing; a start before line 1 or past
4050/// `to` fails closed, since no line reading satisfies it.
4051///
4052#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4053#[example(
4054    name = "line range",
4055    code = r###"
4056    # Lines 2 through 3 come back as a list, 1-based inclusive.
4057    IMPORT [STD]
4058    LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
4059    ASSERT_EQ $window.0 "two"
4060    ASSERT_EQ $window.1 "three"
4061
4062    # Ranges past the end clamp instead of failing.
4063    LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
4064    ASSERT_EQ $tail.0 "two"
4065    "###
4066)]
4067fn text_lines_range(
4068    /// Text whose lines to window.
4069    text: String,
4070    /// First line, 1-based inclusive.
4071    from: i64,
4072    /// Last line, inclusive; past the end clamps.
4073    to: i64,
4074) -> Result<Value> {
4075    Ok(super::args::text_list_value(
4076        super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
4077    ))
4078}
4079
4080/// Report whether text matches a regex pattern.
4081///
4082/// Returns `BOOL`. Bad patterns fail closed naming the pattern and
4083/// its position. Matching is case-sensitive unless the pattern
4084/// carries an inline `(?i)` flag, which makes uppercase and lowercase
4085/// letters match each other.
4086///
4087#[oxdock_func(pure, returns = TypeTag::Bool)]
4088#[example(
4089    name = "match",
4090    code = r###"
4091    # Regex matches report true; misses report false.
4092    IMPORT [STD]
4093    LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
4094    ASSERT_EQ $hit true
4095
4096    # A miss is false, not a failure.
4097    LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
4098    ASSERT_EQ $miss false
4099    "###
4100)]
4101fn text_match(
4102    /// Text to test.
4103    text: String,
4104    /// Regex pattern to match.
4105    pattern: String,
4106) -> Result<Value> {
4107    let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
4108    Ok(Value::bool(re.is_match(&text)))
4109}
4110
4111/// Convert a value to BOOL.
4112///
4113/// Trims ASCII whitespace; accepts `true`/`false`, `1`/`0`,
4114/// `yes`/`no`, `on`/`off` in any case. Passes Bool through. Empty
4115/// and anything else fail: an empty string is not a boolean, so
4116/// absent env names (which read empty) must go through `BOOL_OR`
4117/// with a stated default instead of converting here.
4118///
4119#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
4120#[example(
4121    name = "convert",
4122    code = r###"
4123    IMPORT [STD]
4124    LET $n: BOOL = BOOL("yes")
4125    ASSERT_EQ $n true
4126    LET $f: BOOL = BOOL("0")
4127    ASSERT_EQ $f false
4128    "###
4129)]
4130fn bool_convert(
4131    /// Value to convert to `BOOL`.
4132    #[union(Bool, String)]
4133    val: Value,
4134) -> Result<Value> {
4135    if let Some(b) = val.as_bool() {
4136        return Ok(Value::bool(b));
4137    }
4138    let Some(s) = val.as_str() else {
4139        return Err(anyhow::anyhow!(
4140            "BOOL needs a Bool or String, found {val:?}"
4141        ));
4142    };
4143    match super::args::parse_bool_str(s) {
4144        Some(b) => Ok(Value::bool(b)),
4145        None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
4146    }
4147}
4148
4149/// Coerce text to `BOOL`, substituting a default for empty.
4150///
4151/// Returns `BOOL`. Blank input (a declared-but-absent env name, which
4152/// reads empty) resolves to `default` instead of failing, so each flag
4153/// site states its own absent polarity explicitly: negative-polarity
4154/// flags (`dry_run`) default true, positive ones default false. No
4155/// implicit polarity lives in the coercion. Non-blank garbage still
4156/// fails naming the input, exactly like `LET $x: BOOL` coercion.
4157///
4158#[oxdock_func(pure, returns = TypeTag::Bool)]
4159#[example(
4160    name = "absent-default",
4161    code = r###"
4162    # Absent names read empty; the default settles the polarity.
4163    IMPORT [STD]
4164    INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
4165    LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
4166    ASSERT_EQ $dry true
4167
4168    # Present values coerce strictly, ignoring the default.
4169    LET $off: BOOL = BOOL_OR("false", true)
4170    ASSERT_EQ $off false
4171    "###
4172)]
4173fn bool_or(
4174    /// Text to coerce (`true`/`false`, `1`/`0`, `yes`/`no`/`on`/`off`, any case).
4175    text: String,
4176    /// Absent-value default, used when the text is blank.
4177    default: bool,
4178) -> Result<Value> {
4179    if text.trim().is_empty() {
4180        return Ok(Value::bool(default));
4181    }
4182    match super::args::parse_bool_str(&text) {
4183        Some(b) => Ok(Value::bool(b)),
4184        None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
4185    }
4186}
4187
4188/// Extract capture groups for the first regex match.
4189///
4190/// Returns a `LIST<STRING>` where index 0 is the full match and the
4191/// rest are groups in order; non-participating groups bind empty so
4192/// indexes stay stable. No match binds an empty list. Matching is
4193/// case-sensitive unless the pattern carries an inline `(?i)` flag,
4194/// which makes uppercase and lowercase letters match each other.
4195///
4196#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4197#[example(
4198    name = "extract",
4199    code = r###"
4200    # Index zero is the full match; groups follow in order.
4201    IMPORT [STD]
4202    LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
4203    ASSERT_EQ $caps.0 "abc123"
4204    ASSERT_EQ $caps.1 "abc"
4205    ASSERT_EQ $caps.2 "123"
4206    "###
4207)]
4208fn text_extract(
4209    /// Text to search.
4210    text: String,
4211    /// Regex pattern with capture groups.
4212    pattern: String,
4213) -> Result<Value> {
4214    let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
4215    Ok(super::args::text_list_value(groups))
4216}
4217
4218/// Report whether text starts with a literal prefix.
4219///
4220/// Returns `BOOL`; the literal check behind tag and target branching
4221/// such as `matrix.target` suffix and prefix tests. Matching is
4222/// case-sensitive; there is no case-insensitive mode.
4223///
4224#[oxdock_func(pure, returns = TypeTag::Bool)]
4225#[example(
4226    name = "starts with",
4227    code = r###"
4228    # Present prefixes report true; misses report false.
4229    IMPORT [STD]
4230    LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
4231    ASSERT_EQ $hit true
4232
4233    # A miss is false, not a failure.
4234    LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
4235    ASSERT_EQ $miss false
4236    "###
4237)]
4238fn text_starts_with(
4239    /// Text to test.
4240    text: String,
4241    /// Literal prefix to look for.
4242    prefix: String,
4243) -> Result<Value> {
4244    Ok(Value::bool(text.starts_with(prefix.as_str())))
4245}
4246
4247/// Report whether text ends with a literal suffix.
4248///
4249/// Returns `BOOL`; the `endsWith(matrix.target, 'linux-musl')`
4250/// check in CI legs. Matching is case-sensitive; there is no
4251/// case-insensitive mode.
4252///
4253#[oxdock_func(pure, returns = TypeTag::Bool)]
4254#[example(
4255    name = "ends with",
4256    code = r###"
4257    # Present suffixes report true; misses report false.
4258    IMPORT [STD]
4259    LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
4260    ASSERT_EQ $hit true
4261
4262    # A miss is false, not a failure.
4263    LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
4264    ASSERT_EQ $miss false
4265    "###
4266)]
4267fn text_ends_with(
4268    /// Text to test.
4269    text: String,
4270    /// Literal suffix to look for.
4271    suffix: String,
4272) -> Result<Value> {
4273    Ok(Value::bool(text.ends_with(suffix.as_str())))
4274}
4275
4276/// Report whether text holds a literal substring.
4277///
4278/// Returns `BOOL`; the substring search behind target filtering
4279/// alongside the prefix and suffix tests. Matching is
4280/// case-sensitive; there is no case-insensitive mode.
4281///
4282#[oxdock_func(pure, returns = TypeTag::Bool)]
4283#[example(
4284    name = "contains",
4285    code = r###"
4286    # Present needles report true; misses report false.
4287    IMPORT [STD]
4288    LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
4289    ASSERT_EQ $hit true
4290
4291    # A miss is false, not a failure.
4292    LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
4293    ASSERT_EQ $miss false
4294    "###
4295)]
4296fn text_contains(
4297    /// Text to search.
4298    text: String,
4299    /// Literal substring to look for.
4300    needle: String,
4301) -> Result<Value> {
4302    Ok(Value::bool(text.contains(needle.as_str())))
4303}
4304
4305/// Count the elements of a text, list, or map as an `INT`.
4306///
4307/// Strings count Unicode scalars: multibyte characters count once
4308/// each, so this is not the byte length (`"héllo"` binds 5, not 6).
4309/// Lists count elements, maps count entries; empty values bind 0.
4310/// The `${#var}` and `wc -m` counterpart for scripts that size tags,
4311/// digests, and table rows.
4312///
4313#[oxdock_func(pure, returns = TypeTag::Int)]
4314#[example(
4315    name = "length",
4316    code = r###"
4317    # Plain text counts one per character.
4318    IMPORT [STD]
4319    LET $n: INT = LEN("hello")
4320    ASSERT_EQ $n 5
4321
4322    # Multibyte characters count once each, not per byte.
4323    LET $wide: INT = LEN("héllo")
4324    ASSERT_EQ $wide 5
4325
4326    # Lists count elements, maps count entries.
4327    LET $items: LIST<STRING> = ["a", "b", "c"]
4328    LET $nitems: INT = LEN($items)
4329    ASSERT_EQ $nitems 3
4330    LET $row: MAP<name: STRING> = {name: "ada"}
4331    LET $nkeys: INT = LEN($row)
4332    ASSERT_EQ $nkeys 1
4333    LET $empty: INT = LEN([])
4334    ASSERT_EQ $empty 0
4335    "###
4336)]
4337fn len(
4338    /// Value to measure.
4339    #[union(String, List, Map)]
4340    value: Value,
4341) -> Result<Value> {
4342    if let Some(text) = value.as_str() {
4343        return Ok(Value::int(text.chars().count() as i64));
4344    }
4345    if let Some(items) = value.as_list() {
4346        return Ok(Value::int(items.len() as i64));
4347    }
4348    if let Some(entries) = value.as_map() {
4349        return Ok(Value::int(entries.len() as i64));
4350    }
4351    Err(anyhow::anyhow!(
4352        "LEN needs a STRING, LIST, or MAP value, got {}",
4353        value.type_name()
4354    ))
4355}
4356
4357/// Count non-overlapping literal occurrences of a needle.
4358///
4359/// Matches never share bytes, so `"aaa"` holds one `"aa"`, matching
4360/// `grep -o 'aa' | wc -l`. An empty needle fails closed instead of
4361/// binding every character boundary. Matching is case-sensitive;
4362/// there is no case-insensitive mode.
4363///
4364#[oxdock_func(pure, returns = TypeTag::Int)]
4365#[example(
4366    name = "count",
4367    code = r###"
4368    # Every non-overlapping occurrence counts once.
4369    IMPORT [STD]
4370    LET $n: INT = TEXT_COUNT("hello world", "o")
4371    ASSERT_EQ $n 2
4372
4373    # Overlapping candidates never double count.
4374    LET $once: INT = TEXT_COUNT("aaa", "aa")
4375    ASSERT_EQ $once 1
4376    "###
4377)]
4378fn text_count(
4379    /// Text to search.
4380    text: String,
4381    /// Literal needle to count; empty fails closed.
4382    needle: String,
4383) -> Result<Value> {
4384    let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
4385    Ok(Value::int(n))
4386}
4387
4388/// Count lines matching a regex pattern.
4389///
4390/// Lines split with universal newline handling, like `TEXT_LINES`,
4391/// and each line reports independently: this is `grep -c`, so a line
4392/// with two matches still counts once. Bad patterns fail closed
4393/// naming the pattern and its position. Matching is case-sensitive
4394/// unless the pattern carries an inline `(?i)` flag, which makes
4395/// uppercase and lowercase letters match each other.
4396///
4397#[oxdock_func(pure, returns = TypeTag::Int)]
4398#[example(
4399    name = "count matches",
4400    code = r###"
4401    # One line matches once no matter how many times it hits.
4402    IMPORT [STD]
4403    LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
4404    ASSERT_EQ $n 2
4405
4406    # A miss binds zero, never an error.
4407    LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
4408    ASSERT_EQ $none 0
4409    "###
4410)]
4411fn text_count_matches(
4412    /// Text whose lines to test.
4413    text: String,
4414    /// Regex pattern tested per line.
4415    pattern: String,
4416) -> Result<Value> {
4417    let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
4418    Ok(Value::int(n))
4419}
4420
4421/// Keep the lines matching a regex pattern.
4422///
4423/// Splits with universal newline handling, like `TEXT_LINES`, and
4424/// returns every matching line in order: plain `grep`, so a miss
4425/// binds an empty list instead of failing. A trailing options MAP
4426/// carries `invert`: `TEXT_GREP($text, $pattern, {invert: true})`
4427/// keeps every non-matching line instead, the `grep -v` shape. The
4428/// MAP omits freely; a missing MAP keeps matches. Matching is
4429/// case-sensitive unless the pattern carries an inline `(?i)` flag,
4430/// which makes uppercase and lowercase letters match each other. Bad
4431/// patterns fail closed naming the pattern and its position.
4432///
4433#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4434#[example(
4435    name = "grep",
4436    code = r###"
4437    # Matching lines come back as a list, in order.
4438    IMPORT [STD]
4439    LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
4440    ASSERT_EQ $hits.0 "one"
4441    ASSERT_EQ $hits.1 "one more"
4442
4443    # A miss binds an empty list, never an error.
4444    LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
4445    LET $joined: STRING = TEXT_JOIN($miss, ",")
4446    ASSERT_EQ $joined ""
4447
4448    # The (?i) flag ignores case, so uppercase lines match too.
4449    LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
4450    ASSERT_EQ $folded.0 "One"
4451    ASSERT_EQ $folded.1 "ONE more"
4452    "###
4453)]
4454#[example(
4455    name = "grep invert",
4456    code = r###"
4457    # The invert option keeps every non-matching line instead.
4458    IMPORT [STD]
4459    LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
4460    ASSERT_EQ $kept.0 "two"
4461
4462    # A pattern matching every line binds an empty list, never an error.
4463    LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
4464    LET $joined: STRING = TEXT_JOIN($none, ",")
4465    ASSERT_EQ $joined ""
4466
4467    # Options ride into placeholders as MAP literals. Placeholder
4468    # strings unescape only backslash and quote, so multiline text
4469    # arrives through a variable.
4470    LET $two_lines: STRING = "one\ntwo"
4471    LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
4472    ASSERT_EQ $msg "kept:two"
4473    "###
4474)]
4475fn text_grep(
4476    /// Text whose lines to filter.
4477    text: String,
4478    /// Regex pattern keeping a line.
4479    pattern: String,
4480    /// Filter settings: `invert`. Omittable: a missing options MAP fills `{}`.
4481    #[options("invert?: BOOL")]
4482    #[optional]
4483    options: BTreeMap<String, Value>,
4484) -> Result<Value> {
4485    // `check_options` in the wrapper verified the shape above (keys
4486    // and value types); the read below narrows infallibly after.
4487    let invert = super::args::text_invert_flag(&options);
4488    Ok(super::args::text_list_value(super::args::text_grep_str(
4489        &text,
4490        &pattern,
4491        invert,
4492        "TEXT_GREP",
4493    )?))
4494}
4495
4496/// True when a pipe sits at end of stream: closed with nothing buffered,
4497/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
4498/// Live writers, pinned keepers, and buffered bytes all answer false.
4499/// Never blocks: a reader already blocked stays blocked, so branch on
4500/// `EOF` before reading, not after. OS pairs and unbound handles answer
4501/// best-effort (kernel bytes are invisible there; see `INSPECT`).
4502/// Non-pipe arguments bail at the boundary: the parameter declares
4503/// `PIPE`, so the extractor and the static pass reject them before
4504/// the body runs.
4505///
4506#[oxdock_func(returns = TypeTag::Bool)]
4507#[example(
4508    name = "drain to end",
4509    code = r###"
4510    # Capture two lines, then drain to end of stream with no sentinel line.
4511    IMPORT [STD]
4512    LET $cap: PIPE
4513    WITH_IO [stdout=$cap] {
4514        ECHO "one"
4515        ECHO "two"
4516    }
4517
4518    # The loop exits on close, and the count proves both lines drained.
4519    LET $n: INT = 0
4520    WHILE !EOF($cap) {
4521        WITH_IO [stdin=$cap] READ_LINE $line
4522        $n = $n + 1
4523    }
4524    ASSERT_EQ $n 2
4525    "###
4526)]
4527fn eof<P: ProcessManager>(
4528    cx: &mut StepCtx<P>,
4529    /// Pipe handle to query for end of stream.
4530    pipe: PipeHandle,
4531) -> Result<Value> {
4532    let info = cx.state.io.inspect_pipe(&pipe);
4533    Ok(Value::bool(info.closed && info.buffered == 0))
4534}
4535
4536/// Field table for the `TASK_POLL` result map. Shared by the declared
4537/// return tag and the generated schema and reference docs, so the
4538/// shape agents see is the shape the builtin builds.
4539fn task_poll_result_fields() -> Arc<[Field]> {
4540    Arc::from(vec![
4541        Field {
4542            name: "state".to_string(),
4543            ty: TypeTag::String,
4544            docs: "Task phase: `running` or `finished`.",
4545            optional: false,
4546            default: None,
4547        },
4548        Field {
4549            name: "ok".to_string(),
4550            ty: TypeTag::Bool,
4551            docs: "True unless the task failed.",
4552            optional: false,
4553            default: None,
4554        },
4555        Field {
4556            name: "stdout_tail".to_string(),
4557            ty: TypeTag::String,
4558            docs: "Bounded stdout tail, live while running.",
4559            optional: false,
4560            default: None,
4561        },
4562        Field {
4563            name: "stderr_tail".to_string(),
4564            ty: TypeTag::String,
4565            docs: "Bounded stderr tail, live while running.",
4566            optional: false,
4567            default: None,
4568        },
4569        Field {
4570            name: "truncated_bytes".to_string(),
4571            ty: TypeTag::Int,
4572            docs: "Dropped head bytes past the per-stream cap.",
4573            optional: false,
4574            default: None,
4575        },
4576        Field {
4577            name: "exit_code".to_string(),
4578            ty: TypeTag::Int,
4579            docs: "Process exit code, present once finished.",
4580            optional: true,
4581            default: None,
4582        },
4583        Field {
4584            name: "result".to_string(),
4585            ty: TypeTag::Any,
4586            docs: "Task `RETURN` value, present on clean finish.",
4587            optional: true,
4588            default: None,
4589        },
4590        Field {
4591            name: "error".to_string(),
4592            ty: TypeTag::String,
4593            docs: "Failure text, present on failed finish.",
4594            optional: true,
4595            default: None,
4596        },
4597    ])
4598}
4599
4600/// Poll a background task without consuming it.
4601///
4602/// Reports the running state, the output tails accumulated so far,
4603/// and the final outcome once finished. Repeated polls are safe, and
4604/// a later `AWAIT` still joins normally. Polling after `AWAIT` fails
4605/// like double-await: the handle is spent.
4606///
4607/// Map keys: `state` always names the phase (`"running"` or
4608/// `"finished"`); `ok` is true unless the task failed; `stdout_tail`
4609/// and `stderr_tail` carry bounded output with `truncated_bytes`
4610/// counting dropped head bytes. Finished tasks add `exit_code`;
4611/// clean finishes add `result`, failed ones add `error` instead.
4612#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
4613#[example(
4614    name = "running poll",
4615    code = r###"
4616    # A sleeping task is still running on the first poll.
4617    IMPORT [STD]
4618    LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
4619    LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
4620    ASSERT_EQ $m.state "running"
4621    ASSERT_EQ $m.ok true
4622    # Clean up the sleeper so the run ends promptly.
4623    CANCEL $t
4624    "###
4625)]
4626#[example(
4627    name = "finished poll",
4628    code = r###"
4629    # A finished task reports its value and final tails, then still awaits.
4630    IMPORT [STD]
4631    LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
4632    # Do other work while the task runs; poll once it should be done.
4633    SLEEP 2s
4634    LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
4635    ASSERT_EQ $m.state "finished"
4636    ASSERT_EQ $m.result "done"
4637    LET $o: STRING = AWAIT $t
4638    ASSERT_EQ $o "done"
4639    "###
4640)]
4641fn task_poll<P: ProcessManager>(
4642    cx: &mut StepCtx<P>,
4643    /// Task handle from ASYNC.
4644    task: HandleValue,
4645) -> Result<Value> {
4646    let entry =
4647        super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
4648    let obs = entry.observe_completion();
4649    let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
4650    let mut out = BTreeMap::new();
4651    out.insert(
4652        "state".to_string(),
4653        Value::string(if obs.running { "running" } else { "finished" }.to_string()),
4654    );
4655    out.insert("ok".to_string(), Value::bool(obs.ok));
4656    if !obs.running {
4657        out.insert("exit_code".to_string(), Value::int(obs.exit_code));
4658    }
4659    if let Some(result) = obs.result {
4660        out.insert("result".to_string(), result);
4661    }
4662    if !obs.error.is_empty() {
4663        out.insert("error".to_string(), Value::string(obs.error));
4664    }
4665    out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
4666    out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
4667    out.insert(
4668        "truncated_bytes".to_string(),
4669        Value::int(dropped.min(i64::MAX as u64) as i64),
4670    );
4671    Ok(Value::map(out))
4672}
4673
4674fn meta_to_value(meta: &FuncMeta) -> Value {
4675    let mut map = BTreeMap::new();
4676    map.insert("name".to_string(), Value::string(meta.name.clone()));
4677    map.insert("module".to_string(), Value::string(meta.module.clone()));
4678    map.insert(
4679        "kind".to_string(),
4680        Value::string(meta.kind.label().to_string()),
4681    );
4682    let params = match &meta.params {
4683        Some(params) => Value::list(
4684            params
4685                .iter()
4686                .map(|p| {
4687                    let mut entry = BTreeMap::new();
4688                    entry.insert("name".to_string(), Value::string(p.name.clone()));
4689                    entry.insert(
4690                        "param_type".to_string(),
4691                        Value::string(
4692                            p.param_type
4693                                .as_ref()
4694                                .map(render_structural)
4695                                .unwrap_or_default(),
4696                        ),
4697                    );
4698                    entry.insert(
4699                        "allowed".to_string(),
4700                        Value::string(
4701                            p.allowed
4702                                .map(|values| values.join(", "))
4703                                .unwrap_or_default(),
4704                        ),
4705                    );
4706                    entry.insert("docs".to_string(), Value::string(String::new()));
4707                    entry.insert("optional".to_string(), Value::bool(p.optional));
4708                    entry.insert(
4709                        "options".to_string(),
4710                        match p.options {
4711                            Some(keys) => Value::list(
4712                                keys.iter()
4713                                    .map(|key| {
4714                                        let mut option = BTreeMap::new();
4715                                        option.insert(
4716                                            "name".to_string(),
4717                                            Value::string(key.name.to_string()),
4718                                        );
4719                                        option.insert(
4720                                            "value_type".to_string(),
4721                                            Value::string(render_structural(&key.value)),
4722                                        );
4723                                        option.insert(
4724                                            "required".to_string(),
4725                                            Value::bool(key.required),
4726                                        );
4727                                        option.insert(
4728                                            "default".to_string(),
4729                                            Value::string(
4730                                                key.default.unwrap_or_default().to_string(),
4731                                            ),
4732                                        );
4733                                        Value::map(option)
4734                                    })
4735                                    .collect(),
4736                            ),
4737                            None => Value::string(String::new()),
4738                        },
4739                    );
4740                    Value::map(entry)
4741                })
4742                .collect(),
4743        ),
4744        // Parameterless functions mint an empty LIST, never an empty
4745        // STRING: the `DESCRIBE` return tag promises `LIST<MAP<ANY>>`
4746        // for every entry, and the boundary enforces it.
4747        None => Value::list(Vec::new()),
4748    };
4749    map.insert("params".to_string(), params);
4750    map.insert(
4751        "returns".to_string(),
4752        Value::string(
4753            meta.returns
4754                .as_ref()
4755                .map(render_structural)
4756                .unwrap_or_default(),
4757        ),
4758    );
4759    map.insert("rpn".to_string(), Value::bool(meta.rpn));
4760    map.insert(
4761        "summary".to_string(),
4762        Value::string(meta.summary.to_string()),
4763    );
4764    Value::map(map)
4765}
4766
4767/// One named record schema: a shape host functions produce and scripts
4768/// bind by name (`LET $s: SSH_SESSION_INFO`). Travels with its module
4769/// so schemas register exactly when their producer does.
4770#[derive(Debug, Clone)]
4771pub struct RecordSchema {
4772    pub name: &'static str,
4773    pub fields: std::sync::Arc<[Field]>,
4774}
4775
4776/// One host library: functions and types registered under a single module
4777/// name. `Engine::register_module` stages these; runs expose them as
4778/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
4779#[derive(Clone)]
4780pub struct HostModule<P: ProcessManager> {
4781    pub name: String,
4782    pub funcs: Vec<HostRegistration<P>>,
4783    pub types: Vec<&'static TypeDescriptor>,
4784    pub record_schemas: Vec<RecordSchema>,
4785    /// Shared module state (endpoint registries and the like), stashed
4786    /// at registration and reachable from bodies through
4787    /// `StepCtx::module_state`. Lets every entry stay `#[oxdock_func]`:
4788    /// the macro only generates closers-over-nothing, so state that
4789    /// cannot ride in a value travels here instead of a hand-built
4790    /// closure. Prefer `.with_state(...)` over spelling this field.
4791    pub states: Vec<ModuleState>,
4792}
4793
4794/// One shared state object traveling with its module. Keyed by the
4795/// owning module name plus the value type at registration, so two
4796/// modules sharing one state type never collide.
4797#[derive(Clone)]
4798pub struct ModuleState {
4799    id: std::any::TypeId,
4800    state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
4801}
4802
4803/// A pre-run steps inspection: pure function of the parsed steps,
4804///
4805/// shared so the struct field stays under the complexity lint.
4806pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
4807
4808/// A pre-run check riding in a module's `states`: the runner executes
4809/// every staged check against the parsed steps before the first step
4810/// runs, so unmapped services fail fast with zero side effects. Modules
4811/// attach one with `.with_state(Arc::new(check))`; the runner discovers
4812/// them by type, so no struct field or plugin knowledge is needed here.
4813#[derive(Clone)]
4814pub struct PreRunCheck {
4815    check: Arc<PreRunInspector>,
4816}
4817
4818impl PreRunCheck {
4819    /// Wrap a steps inspector as a pre-run check.
4820    pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
4821        Self {
4822            check: Arc::new(check),
4823        }
4824    }
4825
4826    /// Run the inspection: `Ok` lets execution start.
4827    pub fn run(&self, steps: &[Step]) -> Result<()> {
4828        (self.check)(steps)
4829    }
4830}
4831
4832impl<P: ProcessManager> HostModule<P> {
4833    /// Attach shared state for bodies to fetch with
4834    /// `cx.module_state::<T>("MODULE")`. Chainable, like registration.
4835    pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
4836        self.states.push(ModuleState {
4837            id: std::any::TypeId::of::<T>(),
4838            state,
4839        });
4840        self
4841    }
4842
4843    /// Run every staged [`PreRunCheck`] against already-parsed steps.
4844    /// The runner calls this before the first step executes; the first
4845    /// failing check aborts the run with no side effects.
4846    pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
4847        for state in &self.states {
4848            if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
4849                check.run(steps)?;
4850            }
4851        }
4852        Ok(())
4853    }
4854}
4855
4856impl<P: ProcessManager> ExecState<P> {
4857    /// Register one [`HostModule`]: every function becomes callable as
4858    /// `MODULE::NAME`, every type joins the run's name directory.
4859    pub fn register_module(&mut self, module: HostModule<P>) {
4860        for registration in module.funcs {
4861            match registration {
4862                HostRegistration::Stateful { name, meta, func } => {
4863                    self.functions.register_host(&module.name, name, meta, func);
4864                }
4865                HostRegistration::Pure { name, meta, func } => {
4866                    self.functions
4867                        .register_pure_host(&module.name, name, meta, func);
4868                }
4869                HostRegistration::Both {
4870                    name,
4871                    meta,
4872                    func,
4873                    template,
4874                } => {
4875                    self.functions
4876                        .register_both_host(&module.name, name, meta, func, template);
4877                }
4878            }
4879        }
4880        for descriptor in module.types {
4881            self.register_type(descriptor);
4882        }
4883        for schema in module.record_schemas {
4884            self.register_record_schema(schema.name, schema.fields);
4885        }
4886        for state in module.states {
4887            self.module_states
4888                .insert((module.name.clone(), state.id), state.state);
4889        }
4890    }
4891
4892    /// All visible functions: natives plus hosts plus current DSL definitions.
4893    pub fn list_functions(&self) -> Vec<FuncMeta> {
4894        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
4895        // TODO: Make a "virtual function" and don't hardcode
4896        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
4897            out.push(FuncMeta {
4898                name: KEYWORD_INSPECT.to_string(),
4899                module: STD_MODULE_NAME.to_string(),
4900                kind: FuncKind::HostCtx,
4901                params: None,
4902                returns: Some(TypeTag::Map),
4903                rpn: false,
4904                summary: "Inspect a variable binding.",
4905                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
4906                examples: &[],
4907            });
4908        }
4909        out.sort_by(|a, b| a.name.cmp(&b.name));
4910        out
4911    }
4912
4913    /// Describe one function by name, or `None` when unknown.
4914    pub fn describe_function(&self, name: &str) -> Option<Value> {
4915        if let Some(meta) = self.functions.meta(name) {
4916            return Some(meta_to_value(&meta));
4917        }
4918        // TODO: Make a "virtual function" and don't hardcode
4919        if name == KEYWORD_INSPECT {
4920            return Some(meta_to_value(&FuncMeta {
4921                name: KEYWORD_INSPECT.to_string(),
4922                module: STD_MODULE_NAME.to_string(),
4923                kind: FuncKind::HostCtx,
4924                params: None,
4925                returns: Some(TypeTag::Map),
4926                rpn: false,
4927                summary: "Inspect a variable binding.",
4928                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
4929                examples: &[],
4930            }));
4931        }
4932        None
4933    }
4934
4935    pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
4936        self.functions.clone_pure_fn(name)
4937    }
4938
4939    /// Shared snapshot of every registered pure function for
4940    /// placeholder and host driven expansion. Public so host crates
4941    /// resolve calls through the live registry instead of hardcoding
4942    /// module or function names. Cloning the `Arc` never copies the map.
4943    pub fn pure_function_table(&self) -> Arc<PureTable> {
4944        self.functions.pure_shared()
4945    }
4946
4947    pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
4948        self.functions.clone_ctx_fn(name)
4949    }
4950
4951    pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
4952        self.functions.meta(name)
4953    }
4954}
4955
4956#[cfg(test)]
4957mod tests {
4958    use super::*;
4959
4960    #[test]
4961    fn placeholder_resolver_dispatches_table_entries() {
4962        // Single dispatch implementation for every expansion path:
4963        // known names route to the entry, unknown names fail with
4964        // the sorted known-functions listing.
4965        let echo: PureFn = Arc::new(|args| {
4966            args.into_iter()
4967                .next()
4968                .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
4969        });
4970        let mut entries = HashMap::new();
4971        entries.insert("ECHO".to_string(), echo);
4972        let mut table = PureTable::new();
4973        table.insert("T".to_string(), entries);
4974        let resolve = placeholder_resolver(Arc::new(table));
4975        let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
4976        assert_eq!(out.as_str().expect("string"), "hi");
4977        let err = format!(
4978            "{:#}",
4979            resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
4980        );
4981        assert!(
4982            err.contains("unknown placeholder function 'T::NOPE'"),
4983            "names the call: {err}"
4984        );
4985        assert!(
4986            err.contains("known functions: T::ECHO"),
4987            "lists known names: {err}"
4988        );
4989    }
4990
4991    #[test]
4992    fn describe_entry_renders_union_spellings() {
4993        // Union params and returns render through the same structural
4994        // renderer every other tag uses: `DESCRIBE` (and the generated
4995        // reference built on it) names the admission set, never a
4996        // bare word or an empty string. Built by macro, so the
4997        // spelling cannot drift from the members.
4998        let union = oxdock_parser::union_tag!(String, Pipe);
4999        let meta = FuncMeta {
5000            name: "T::F".to_string(),
5001            module: "T".to_string(),
5002            kind: FuncKind::HostPure,
5003            params: Some(vec![FuncParam {
5004                name: "text".to_string(),
5005                param_type: Some(union.clone()),
5006                allowed: None,
5007                docs: "",
5008                options: None,
5009                optional: false,
5010            }]),
5011            returns: Some(union),
5012            rpn: false,
5013            summary: "test-only",
5014            docs: "test-only",
5015            examples: &[],
5016        };
5017        let value = meta_to_value(&meta);
5018        let map = value.as_map().expect("describe value is a map");
5019        let params = map
5020            .get("params")
5021            .expect("params key")
5022            .as_list()
5023            .expect("params is a list");
5024        let first = params[0].as_map().expect("entry is a map");
5025        assert_eq!(
5026            first.get("param_type").and_then(Value::as_str),
5027            Some("STRING|PIPE"),
5028            "param renders the set"
5029        );
5030        assert_eq!(
5031            map.get("returns").and_then(Value::as_str),
5032            Some("STRING|PIPE"),
5033            "returns render the set"
5034        );
5035    }
5036
5037    #[test]
5038    fn describe_entry_renders_handle_payload() {
5039        // Shaped handles render structurally (HANDLE<STRING>, not
5040        // bare HANDLE): script ASYNC FUNC declarations surface their
5041        // payload through DESCRIBE exactly as declared.
5042        let meta = FuncMeta {
5043            name: "SCRIPT::FETCH".to_string(),
5044            module: "SCRIPT".to_string(),
5045            kind: FuncKind::Script,
5046            params: Some(vec![]),
5047            returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
5048            rpn: false,
5049            summary: "test-only",
5050            docs: "test-only",
5051            examples: &[],
5052        };
5053        let value = meta_to_value(&meta);
5054        let map = value.as_map().expect("describe value is a map");
5055        assert_eq!(
5056            map.get("returns").and_then(Value::as_str),
5057            Some("HANDLE<STRING>"),
5058            "returns render the payload"
5059        );
5060    }
5061
5062    #[test]
5063    fn describe_entry_carries_optional_flag() {
5064        // The `optional` key on params entries is the machine-readable
5065        // half of the `?` rendering: pin both values through the same
5066        // builder the runtime serves, not through prose.
5067        let meta = FuncMeta {
5068            name: "T::F".to_string(),
5069            module: "T".to_string(),
5070            kind: FuncKind::HostPure,
5071            params: Some(vec![
5072                FuncParam {
5073                    name: "url".to_string(),
5074                    param_type: Some(TypeTag::String),
5075                    allowed: None,
5076                    docs: "",
5077                    options: None,
5078                    optional: false,
5079                },
5080                FuncParam {
5081                    name: "options".to_string(),
5082                    param_type: Some(TypeTag::Map),
5083                    allowed: None,
5084                    docs: "",
5085                    options: None,
5086                    optional: true,
5087                },
5088            ]),
5089            returns: Some(TypeTag::String),
5090            rpn: false,
5091            summary: "test-only",
5092            docs: "test-only",
5093            examples: &[],
5094        };
5095        let value = meta_to_value(&meta);
5096        let map = value.as_map().expect("describe value is a map");
5097        let params = map
5098            .get("params")
5099            .expect("params key")
5100            .as_list()
5101            .expect("params is a list");
5102        assert_eq!(params.len(), 2);
5103        let first = params[0].as_map().expect("entry is a map");
5104        let second = params[1].as_map().expect("entry is a map");
5105        assert_eq!(
5106            first.get("optional").and_then(Value::as_bool),
5107            Some(false),
5108            "required param must read false"
5109        );
5110        assert_eq!(
5111            second.get("optional").and_then(Value::as_bool),
5112            Some(true),
5113            "omittable param must read true"
5114        );
5115    }
5116
5117    #[test]
5118    fn template_twins_mirror_string_paths_and_refuse_pipes() {
5119        // Every template twin answers strings through the shared pump
5120        // semantics and refuses pipes naming the step IO they need:
5121        // placeholder evaluation carries no step context to pump
5122        // through. Table-driven so a twinless mirror op fails here
5123        // naming it.
5124        let pipe = Value::pipe_fresh();
5125        type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
5126        let cases: Vec<TwinCase> = vec![
5127            (
5128                "TEXT_TRIM",
5129                Box::new(|| text_trim_string(Value::string("  hello  ".to_string()))),
5130            ),
5131            (
5132                "TEXT_TRIM_PREFIX",
5133                Box::new(|| {
5134                    text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
5135                }),
5136            ),
5137            (
5138                "TEXT_TRIM_SUFFIX",
5139                Box::new(|| {
5140                    text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
5141                }),
5142            ),
5143            (
5144                "TEXT_TO_UPPER",
5145                Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
5146            ),
5147            (
5148                "TEXT_TO_LOWER",
5149                Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
5150            ),
5151            (
5152                "TEXT_REPLACE",
5153                Box::new(|| {
5154                    text_replace_string(
5155                        Value::string("ab".to_string()),
5156                        "b".to_string(),
5157                        "c".to_string(),
5158                    )
5159                }),
5160            ),
5161            (
5162                "TEXT_REPLACE_REGEX",
5163                Box::new(|| {
5164                    text_replace_regex_string(
5165                        Value::string("ab".to_string()),
5166                        "b".to_string(),
5167                        "c".to_string(),
5168                    )
5169                }),
5170            ),
5171        ];
5172        assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
5173        for (name, run) in &cases {
5174            let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
5175            assert!(
5176                value.as_str().is_some(),
5177                "{name} twin must answer STRING, got {}",
5178                value.type_name()
5179            );
5180        }
5181        assert_eq!(
5182            text_trim_string(Value::string("  hello  ".to_string()))
5183                .expect("trim twin")
5184                .as_str(),
5185            Some("hello")
5186        );
5187        // Pipes refuse through the shared message on every twin.
5188        let pipe_cases: Vec<(&str, Result<Value>)> = vec![
5189            ("TEXT_TRIM", text_trim_string(pipe.clone())),
5190            (
5191                "TEXT_TRIM_PREFIX",
5192                text_trim_prefix_string(pipe.clone(), "v".to_string()),
5193            ),
5194            (
5195                "TEXT_TRIM_SUFFIX",
5196                text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
5197            ),
5198            ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
5199            ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
5200            (
5201                "TEXT_REPLACE",
5202                text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
5203            ),
5204            (
5205                "TEXT_REPLACE_REGEX",
5206                text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
5207            ),
5208        ];
5209        for (name, result) in pipe_cases {
5210            let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
5211            assert!(
5212                format!("{err:#}").contains("step IO"),
5213                "{name} refusal names the missing context: {err:#}"
5214            );
5215        }
5216    }
5217
5218    #[test]
5219    fn shell_words_join_split_round_trip() {
5220        // Join and split are absolute inverses on the word side: the
5221        // joiner quotes through `shell-words`, the splitter parses the
5222        // same syntax, so every adversarial word survives the round trip.
5223        let words = vec![
5224            "gh".to_string(),
5225            "issue".to_string(),
5226            "comment".to_string(),
5227            "with spaces".to_string(),
5228            "it's".to_string(),
5229            "say \"hi\"".to_string(),
5230            "$HOME".to_string(),
5231            "$(whoami)".to_string(),
5232            "C:\\path\\to".to_string(),
5233            "naïve café".to_string(),
5234            "".to_string(),
5235        ];
5236        let joined = shell_words::join(&words);
5237        let back = shell_words::split(&joined).expect("join output must parse");
5238        assert_eq!(back, words);
5239        assert!(shell_words::split("unbalanced \"quote").is_err());
5240    }
5241}