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