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