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