Skip to main content

oxdock_core/exec/
native.rs

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