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::{
7    Field, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step, TypeTag,
8    Value, base_name, qualify, render_structural, split_qualified,
9};
10use oxdock_pipe::PipeHandle;
11use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
12
13use super::io::StreamHandle;
14use super::state::ExecState;
15use super::steps::StepCtx;
16use super::typing::TypeDescriptor;
17
18/// Origin of a callable in the unified function registry. `Script` is an
19/// interpreted `FUNC` body; `HostCtx` and `HostPure` are compiled Rust
20/// functions (the `#[oxdock_func]` host export macro). Builtins and
21/// runtime-registered hosts share the host kinds; only `DESCRIBE` output
22/// shows the label, and both host kinds keep rendering as `host`.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum FuncKind {
25    Script,
26    HostCtx,
27    HostPure,
28}
29
30impl FuncKind {
31    pub fn label(&self) -> &'static str {
32        match self {
33            FuncKind::Script => "script",
34            FuncKind::HostCtx | FuncKind::HostPure => "host",
35        }
36    }
37}
38
39/// One declared parameter of a registered function. `param_type` is `None`
40/// for unconstrained `Value` parameters (the macro accepts any value).
41/// `allowed` names the closed value set for constrained `STRING`
42/// parameters, declared once via `#[values(...)]`: the generated
43/// extractor enforces membership and the reference renders the set,
44/// so the list cannot rot apart from the check. `docs` carries the
45/// parameter's description (parsed from the `# Arguments` doc section
46/// for macro functions, written inline for hand-built entries) and
47/// renders into every reference surface. `options` declares the known
48/// keys of a `MAP` options parameter: same single-source rule as
49/// `allowed`, with per-key types, required flags, defaults, and docs.
50/// `optional` marks a trailing `MAP` parameter callers may omit: the
51/// runtime fills an empty MAP, and signatures render `= {}`. Only
52/// trailing `MAP` params may be optional (run-start validation
53/// rejects anything else), so omission always means "no options".
54/// The macro never emits optional params: only hand-built entries
55/// use them, and only for options MAPs.
56#[derive(Debug, Clone)]
57pub struct FuncParam {
58    pub name: String,
59    pub param_type: Option<TypeTag>,
60    pub allowed: Option<&'static [&'static str]>,
61    pub docs: &'static str,
62    pub options: Option<&'static [ParamOption]>,
63    pub optional: bool,
64}
65
66/// Required argument count: total params minus trailing optionals.
67/// Callers may pass any count in `required..=total`; omitted trailing
68/// MAPs fill with an empty MAP. Shared by the static arity gate and
69/// the runtime gate so the two can never disagree.
70pub fn required_arity(params: &[FuncParam]) -> usize {
71    params
72        .iter()
73        .rev()
74        .take_while(|param| param.optional)
75        .fold(params.len(), |count, _| count - 1)
76}
77
78/// Fill omitted trailing optional MAP params with empty MAPs. The
79/// caller guarantees `values.len()` is within
80/// `required_arity(params)..=params.len()`; anything else is a bug,
81/// not a user error, so over- and under-counts panic loudly.
82pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
83    assert!(
84        values.len() <= params.len(),
85        "arity gate must run before fill_optional_args"
86    );
87    assert!(
88        values.len() >= required_arity(params),
89        "arity gate must run before fill_optional_args"
90    );
91    while values.len() < params.len() {
92        values.push(Value::map(BTreeMap::new()));
93    }
94    values
95}
96
97/// One known key of a `MAP` options parameter: name, value type,
98/// whether callers must pass it, the rendered default for optional
99/// keys, and what it controls. Declared once per options parameter
100/// (macro `#[options(...)]` plus the `# Options` doc section, or
101/// inline for hand-built entries) and rendered into signatures,
102/// `DESCRIBE` output, and generated references alike.
103#[derive(Debug, Clone)]
104pub struct ParamOption {
105    pub name: &'static str,
106    pub value: TypeTag,
107    pub required: bool,
108    pub default: Option<&'static str>,
109}
110
111/// Introspectable metadata for one function. Single source for
112/// `DESCRIBE(name)` output and the static function reference. `rpn` names
113/// whether the function also runs on the compiled math path (`true` for
114/// pure functions and opted-in stateful ones); everything runs on the AST
115/// path.
116#[derive(Debug, Clone)]
117pub struct FuncMeta {
118    pub name: String,
119    /// Owning module (`STD` for builtins, `SCRIPT` for DSL definitions,
120    /// the host module name otherwise). `name` is always the qualified
121    /// `MODULE::BASE` form, so listings and `DESCRIBE` never lose origin.
122    pub module: String,
123    pub kind: FuncKind,
124    pub params: Option<Vec<FuncParam>>,
125    pub returns: Option<TypeTag>,
126    pub rpn: bool,
127    pub summary: &'static str,
128    pub docs: &'static str,
129    /// Executable examples, rendered as ```oxdock fences into the
130    /// generated reference and executed by docs_conformance like
131    /// command examples. The single precondition mechanism: the
132    /// returns gate executes these blocks to cover functions blind
133    /// sampling cannot reach.
134    pub examples: &'static [crate::Example],
135}
136
137/// Pure scalar function: no filesystem, no scope, no process access.
138/// Usable from both AST evaluation and compiled RPN math.
139pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
140
141/// Stateful/IO function with full step context (fs, cwd, envs, vars, pipes).
142pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
143
144/// Export hook for a DSL function, implemented by `#[oxdock_func]` on a
145/// registration marker. The engine calls `registration()` and never names
146/// a generated symbol.
147pub trait OxDockFn<P: ProcessManager> {
148    /// The registry entry deriving from the Rust signature plus doc
149    /// comments: name, metadata, and entry point, composed.
150    fn registration() -> HostRegistration<P>;
151}
152
153/// One host-registered function, grouped into a [`HostModule`] and passed
154/// to `Engine::register_module`. Build the entry with the `#[oxdock_func]`-
155/// generated registration marker, or by hand. `Pure` entries run
156/// on both the AST and the compiled RPN math paths; `Stateful` entries run
157/// on the AST path with full step context.
158pub enum HostRegistration<P: ProcessManager> {
159    Stateful {
160        name: String,
161        meta: FuncMeta,
162        func: NativeFn<P>,
163    },
164    Pure {
165        name: String,
166        meta: FuncMeta,
167        func: PureFn,
168    },
169}
170
171// Manual `Clone` (a derive would demand `P: Clone`): entries share their
172// function pointers through the `Arc`s and deep-copy the metadata.
173impl<P: ProcessManager> Clone for HostRegistration<P> {
174    fn clone(&self) -> Self {
175        match self {
176            HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
177                name: name.clone(),
178                meta: meta.clone(),
179                func: Arc::clone(func),
180            },
181            HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
182                name: name.clone(),
183                meta: meta.clone(),
184                func: Arc::clone(func),
185            },
186        }
187    }
188}
189
190impl<P: ProcessManager> HostRegistration<P> {
191    /// Introspectable metadata for this entry, for documentation tooling
192    /// that reads modules without registering them.
193    pub fn meta(&self) -> &FuncMeta {
194        match self {
195            HostRegistration::Stateful { meta, .. } => meta,
196            HostRegistration::Pure { meta, .. } => meta,
197        }
198    }
199}
200
201/// One user-defined function body (`FUNC NAME($p: TYPE, ...) { ... }`).
202/// Param types resolve to tags at definition time, where the type
203/// directory is in scope; the registry never holds raw type strings.
204#[derive(Debug, Clone)]
205pub(super) struct FuncDefData {
206    pub(super) params: Vec<(String, TypeTag)>,
207    pub(super) body: Vec<Step>,
208}
209
210/// Executable body behind one registry entry: an interpreted script, a
211/// pure scalar function, or a stateful function with step context.
212pub(super) enum FuncBody<P: ProcessManager> {
213    Script(FuncDefData),
214    Pure(PureFn),
215    Ctx(NativeFn<P>),
216}
217
218// Manual `Clone` (a derive would demand `P: Clone`).
219impl<P: ProcessManager> Clone for FuncBody<P> {
220    fn clone(&self) -> Self {
221        match self {
222            FuncBody::Script(def) => FuncBody::Script(def.clone()),
223            FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
224            FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
225        }
226    }
227}
228
229/// One entry in the unified function registry: introspectable metadata
230/// (mandatory for every entry, backing the pre-evaluation arity gate)
231/// plus the executable body.
232pub(super) struct FuncEntry<P: ProcessManager> {
233    pub(super) meta: FuncMeta,
234    pub(super) body: FuncBody<P>,
235}
236
237// Manual `Clone` (a derive would demand `P: Clone`).
238impl<P: ProcessManager> Clone for FuncEntry<P> {
239    fn clone(&self) -> Self {
240        Self {
241            meta: self.meta.clone(),
242            body: self.body.clone(),
243        }
244    }
245}
246
247/// Names defined in one lexical scope frame: `defined` rejects duplicates
248/// in the same scope, `shadowed` restores outer definitions on exit.
249struct ScopeFrame<P: ProcessManager> {
250    defined: HashSet<String>,
251    shadowed: Vec<(String, FuncEntry<P>)>,
252}
253
254// Manual `Clone` (a derive would demand `P: Clone`).
255impl<P: ProcessManager> Clone for ScopeFrame<P> {
256    fn clone(&self) -> Self {
257        Self {
258            defined: self.defined.clone(),
259            shadowed: self.shadowed.clone(),
260        }
261    }
262}
263
264/// The single function registry: DSL `FUNC` definitions, builtins, and
265/// host extensions share one lookup table, one metadata path, and one
266/// dispatch order. Script entries scope lexically (defined names revert on
267/// scope exit, shadowing an outer definition restores it); native entries
268/// persist for the run. Shared across `fork()` via clone; the entry maps
269/// clone while scope frames stay per state.
270/// Module to function-name table of pure entries, shared by reference.
271/// Nested so placeholder dispatch looks up `table[module][func]` with
272/// zero allocation; rebuilt only when native entries register.
273pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
274
275pub struct FunctionRegistry<P: ProcessManager> {
276    entries: HashMap<String, FuncEntry<P>>,
277    scopes: Vec<ScopeFrame<P>>,
278    pure_shared: Arc<PureTable>,
279}
280
281impl<P: ProcessManager> FunctionRegistry<P> {
282    pub(super) fn with_builtins() -> Self {
283        let mut reg = Self {
284            entries: HashMap::new(),
285            pure_shared: Arc::new(HashMap::new()),
286            scopes: vec![ScopeFrame {
287                defined: HashSet::new(),
288                shadowed: Vec::new(),
289            }],
290        };
291        // Every builtin registers through the same `HostRegistration`
292        // entries hosts use: no separate authoring path for engine natives.
293        // Builtins land in the `STD` module, exactly like a host module.
294        for host in Self::builtin_registrations() {
295            match host {
296                HostRegistration::Stateful { name, meta, func } => {
297                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
298                }
299                HostRegistration::Pure { name, meta, func } => {
300                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
301                }
302            }
303        }
304        reg
305    }
306
307    /// All builtins as host-style registrations, built from the same
308    /// `#[oxdock_func]`-generated markers hosts use. `with_builtins`
309    /// consumes this list, so builtins and hosts share one registration
310    /// pathway instead of two authoring models.
311    pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
312        vec![
313            Int::registration(),
314            Float::registration(),
315            FormatByteCount::registration(),
316            ParseByteCount::registration(),
317            FormatDuration::registration(),
318            ParseDuration::registration(),
319            Types::registration(),
320            TypeDescribe::registration(),
321            Glob::registration(),
322            LoadToml::registration(),
323            LoadJson::registration(),
324            ParseToml::registration(),
325            ParseJson::registration(),
326            PathType::registration(),
327            PathWritable::registration(),
328            IsExec::registration(),
329            HasKey::registration(),
330            MapSet::registration(),
331            MergeMaps::registration(),
332            Base64Encode::registration(),
333            Base64Decode::registration(),
334            Rand::registration(),
335            ToJson::registration(),
336            TypeOf::registration(),
337            Functions::registration(),
338            Describe::registration(),
339            IsTerminal::registration(),
340            Eof::registration(),
341            SemaphoreNew::registration(),
342            SemaphoreTryAcquire::registration(),
343            SemaphoreAvailable::registration(),
344        ]
345    }
346
347    /// Every name the registry answers to. Backs parse-time shadow
348    /// validation through `builtin_function_names`.
349    pub(super) fn keys(&self) -> HashSet<String> {
350        self.entries.keys().cloned().collect()
351    }
352
353    /// Single lookup for every callable: script, pure, or stateful.
354    pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
355        self.entries.get(name).cloned()
356    }
357
358    fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
359        self.entries.insert(name, FuncEntry { meta, body });
360        self.rebuild_pure_shared();
361    }
362
363    /// Rebuild the shared pure table. Runs only on native insertion:
364    /// script definitions insert `Script` bodies directly and never
365    /// affect the pure set, so this stays correct between rebuilds.
366    fn rebuild_pure_shared(&mut self) {
367        let mut table: PureTable = HashMap::new();
368        for (name, entry) in &self.entries {
369            let FuncBody::Pure(ref func) = entry.body else {
370                continue;
371            };
372            if let Some((module, base)) = split_qualified(name) {
373                table
374                    .entry(module.to_string())
375                    .or_default()
376                    .insert(base.to_string(), Arc::clone(func));
377            }
378        }
379        self.pure_shared = Arc::new(table);
380    }
381
382    /// Insert under `MODULE::BASE`, stamping provenance on the metadata.
383    /// The single choke point for every registry entry: builtins pass
384    /// `STD`, hosts pass their module, scripts pass `SCRIPT`.
385    fn insert_qualified(
386        &mut self,
387        module: &str,
388        base: String,
389        mut meta: FuncMeta,
390        body: FuncBody<P>,
391    ) {
392        meta.name = qualify(module, &base);
393        meta.module = module.to_string();
394        // Last-write-wins would silently reroute calls, so a repeated
395        // qualified name is a programmer error, never a shadow: panic like
396        // conflicting type registrations do. `SCRIPT` definitions bypass
397        // this path (`define_script` owns their scoped shadowing).
398        if self.entries.contains_key(&meta.name) {
399            panic!("duplicate function registration `{}`", meta.name);
400        }
401        self.insert_native(meta.name.clone(), meta, body);
402    }
403
404    pub(super) fn register_host(
405        &mut self,
406        module: &str,
407        name: String,
408        mut meta: FuncMeta,
409        func: NativeFn<P>,
410    ) {
411        meta.kind = FuncKind::HostCtx;
412        self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
413    }
414
415    pub(super) fn register_pure_host(
416        &mut self,
417        module: &str,
418        name: String,
419        mut meta: FuncMeta,
420        func: PureFn,
421    ) {
422        meta.kind = FuncKind::HostPure;
423        self.insert_qualified(module, name, meta, FuncBody::Pure(func));
424    }
425
426    /// Define a DSL `FUNC`: names colliding with any known base name cannot
427    /// shadow, same-scope duplicates cannot redefine, and nested shadowing
428    /// of an outer script definition restores on scope exit. Stored as
429    /// `SCRIPT::NAME`, exactly like every other qualified entry.
430    pub(super) fn define_script(
431        &mut self,
432        name: &str,
433        params: &[(String, TypeTag)],
434        body: &[Step],
435    ) -> Result<()> {
436        let qualified = qualify(SCRIPT_MODULE_NAME, name);
437        let shadowable = matches!(
438            self.entries.get(&qualified).map(|entry| &entry.body),
439            Some(FuncBody::Script(_))
440        );
441        // Reserved spans every module: compare base names so the message
442        // keeps naming the bare script identifier.
443        let reserved = self
444            .entries
445            .keys()
446            .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
447        if reserved && !shadowable {
448            anyhow::bail!("cannot shadow reserved function `{name}`");
449        }
450        if self
451            .scopes
452            .last()
453            .is_some_and(|frame| frame.defined.contains(&qualified))
454        {
455            anyhow::bail!("duplicate function `{name}` in same scope");
456        }
457        let old = self.entries.insert(
458            qualified.clone(),
459            FuncEntry {
460                meta: FuncMeta {
461                    name: qualified.clone(),
462                    module: SCRIPT_MODULE_NAME.to_string(),
463                    kind: FuncKind::Script,
464                    params: Some(
465                        params
466                            .iter()
467                            .map(|(name, param_type)| FuncParam {
468                                name: name.clone(),
469                                param_type: Some(param_type.clone()),
470                                allowed: None,
471                                // Script `FUNC` params carry no prose:
472                                // declarations have no doc syntax.
473                                docs: "",
474                                options: None,
475                                optional: false,
476                            })
477                            .collect(),
478                    ),
479                    returns: None,
480                    rpn: false,
481                    summary: "DSL-defined function.",
482                    docs: "Defined via FUNC in script.",
483                    examples: &[],
484                },
485                body: FuncBody::Script(FuncDefData {
486                    params: params.to_vec(),
487                    body: body.to_vec(),
488                }),
489            },
490        );
491        if let Some(frame) = self.scopes.last_mut() {
492            frame.defined.insert(qualified.clone());
493            if let Some(old) = old {
494                frame.shadowed.push((qualified, old));
495            }
496        }
497        Ok(())
498    }
499
500    /// Open a lexical scope frame for script definitions. Native entries
501    /// persist; only script names track here.
502    pub(super) fn push_scope(&mut self) {
503        self.scopes.push(ScopeFrame {
504            defined: HashSet::new(),
505            shadowed: Vec::new(),
506        });
507    }
508
509    /// Close a lexical scope frame: names defined inside revert, and any
510    /// outer definition they shadowed is restored.
511    pub(super) fn pop_scope(&mut self) {
512        let Some(frame) = self.scopes.pop() else {
513            return;
514        };
515        for name in frame.defined {
516            self.entries.remove(&name);
517        }
518        for (name, old) in frame.shadowed {
519            self.entries.insert(name, old);
520        }
521    }
522
523    /// True when `name` is an interpreted script definition (needing call
524    /// scoping and depth budgeting through `call_func_value` rather than
525    /// inline evaluation).
526    pub(super) fn contains_script(&self, name: &str) -> bool {
527        matches!(
528            self.entries.get(name).map(|entry| &entry.body),
529            Some(FuncBody::Script(_))
530        )
531    }
532
533    /// Clone the pure fn for `name` (ending the registry borrow) so callers
534    /// can invoke it without holding `&self` across a `&mut StepCtx` use.
535    fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
536        match self.entries.get(name)?.body {
537            FuncBody::Pure(ref func) => Some(Arc::clone(func)),
538            _ => None,
539        }
540    }
541
542    /// Shared snapshot of every pure entry, nested by module and base
543    /// name. Cloning the `Arc` is refcount-only: placeholder dispatch
544    /// borrows this per expansion with no map copies.
545    pub(super) fn pure_shared(&self) -> Arc<PureTable> {
546        Arc::clone(&self.pure_shared)
547    }
548
549    /// Every entry's metadata, scripts included, sorted by name. Backs
550    /// run-start type tag validation.
551    pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
552        self.entries_metas()
553    }
554
555    /// Clone the ctx fn for `name` (ending the registry borrow) so callers
556    /// can invoke it with `&mut StepCtx` without double-borrowing state.
557    fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
558        match self.entries.get(name)?.body {
559            FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
560            _ => None,
561        }
562    }
563
564    fn meta(&self, name: &str) -> Option<FuncMeta> {
565        self.entries.get(name).map(|entry| entry.meta.clone())
566    }
567
568    fn native_metas(&self) -> Vec<FuncMeta> {
569        let mut out: Vec<FuncMeta> = Vec::new();
570        for entry in self.entries.values() {
571            if !matches!(entry.body, FuncBody::Script(_)) {
572                out.push(entry.meta.clone());
573            }
574        }
575        out.sort_by(|a, b| a.name.cmp(&b.name));
576        out
577    }
578
579    /// Every entry's metadata, scripts included, sorted by name. Backs
580    /// runtime `FUNCTIONS()` listings.
581    fn entries_metas(&self) -> Vec<FuncMeta> {
582        let mut out: Vec<FuncMeta> = self
583            .entries
584            .values()
585            .map(|entry| entry.meta.clone())
586            .collect();
587        out.sort_by(|a, b| a.name.cmp(&b.name));
588        out
589    }
590}
591
592impl<P: ProcessManager> Clone for FunctionRegistry<P> {
593    fn clone(&self) -> Self {
594        Self {
595            entries: self.entries.clone(),
596            scopes: self.scopes.clone(),
597            pure_shared: Arc::clone(&self.pure_shared),
598        }
599    }
600}
601
602/// Names of all compiled-in builtins plus `INSPECT` (a dedicated AST/RPN
603/// node, not a registry entry). Read straight off a stock registry, so the
604/// `#[oxdock_func]` annotations stay the single source of truth: adding a
605/// builtin extends this set with no parallel list to update. Seeds
606/// parse-time shadow validation, so the parser crate keeps zero
607/// compile-time knowledge of builtin names.
608pub fn builtin_function_names() -> HashSet<String> {
609    let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
610    names.insert(KEYWORD_INSPECT.to_string());
611    names
612}
613
614/// Metadata of every builtin function, sorted by name, for static
615/// rendering (docs-gen). Same single source as `builtin_function_names`:
616/// the `#[oxdock_func]` annotations, never a parallel list.
617pub fn builtin_function_metas() -> Vec<FuncMeta> {
618    FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
619}
620
621/// Stock `STD` module table derived from the `#[oxdock_func]` builtins:
622/// the single source of truth for builtin membership and RPN eligibility.
623/// Seeds parse-time module resolution, so the parser crate keeps zero
624/// compile-time knowledge of builtin names.
625pub fn std_module_table() -> oxdock_parser::ModuleTable {
626    // Registry names are qualified (`STD::GLOB`); the table holds bases.
627    let functions: HashSet<String> = builtin_function_metas()
628        .into_iter()
629        .map(|meta| base_name(&meta.name).to_string())
630        .collect();
631    oxdock_parser::ModuleTable {
632        modules: HashMap::from([(
633            STD_MODULE_NAME.to_string(),
634            Some(oxdock_parser::ModuleFuncs { functions }),
635        )]),
636    }
637}
638
639// Builtins below use the `#[oxdock_func]` host export macro, the exact same authoring
640// model as host-registered functions: metadata, arity checks, and argument
641// unpacking derive from the signature plus doc comments, so adding a native
642// means writing one small typed function plus one line each in
643// `builtin_registrations` (consumed by `with_builtins`) and the
644// `FUNCTIONS`/`DESCRIBE`/`TYPES` surface, which all read the same symbols.
645
646/// Convert a value to INT.
647///
648/// Trims ASCII whitespace and parses i64. Passes Int through; Float only
649/// when integral and finite; Bool as 1/0.
650///
651#[oxdock_func(pure, returns = TypeTag::Int)]
652#[example(
653    name = "convert",
654    code = r###"
655    IMPORT [STD]
656    LET $n: INT = INT("42")
657    ASSERT_EQ $n 42
658    LET $flag: INT = INT(true)
659    ASSERT_EQ $flag 1
660    "###
661)]
662fn int(
663    /// Value to convert to `INT`.
664    #[union(Int, Float, String, Bool)]
665    val: Value,
666) -> Result<Value> {
667    super::args::int_from_value(val)
668}
669
670/// Convert a value to FLOAT.
671///
672/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
673///
674#[oxdock_func(pure, returns = TypeTag::Float)]
675#[example(
676    name = "convert",
677    code = r###"
678    IMPORT [STD]
679    LET $f: FLOAT = FLOAT("1.5")
680    ASSERT_EQ $f 1.5
681    LET $whole: FLOAT = FLOAT(2)
682    ASSERT_EQ $whole 2.0
683    "###
684)]
685fn float(
686    /// Value to convert to `FLOAT`.
687    #[union(Float, Int, String)]
688    val: Value,
689) -> Result<Value> {
690    super::args::float_from_value(val)
691}
692
693/// Format a byte count canonically (`500B`, `10KB`, `2MB`, `1GB`,
694/// binary `10KIB` and friends): the inverse of `PARSE_BYTE_COUNT`, so
695/// formatted values reparse exactly. Negative inputs fail.
696///
697#[oxdock_func(pure, returns = TypeTag::String)]
698#[example(
699    name = "format and round-trip",
700    code = r###"
701    # Byte counts render in the largest exact unit.
702    IMPORT [STD]
703    LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
704    ASSERT_EQ $pretty "1MiB"
705
706    # The pair round-trips through the parser.
707    LET $back: INT = PARSE_BYTE_COUNT($pretty)
708    ASSERT_EQ $back 1_048_576
709    "###
710)]
711fn format_byte_count(
712    /// Byte count to format; negatives fail.
713    bytes: i64,
714) -> Result<Value> {
715    if bytes < 0 {
716        return Err(anyhow::anyhow!(
717            "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
718        ));
719    }
720    Ok(Value::string(oxdock_parser::command::format_byte_count(
721        bytes as u64,
722    )))
723}
724
725/// Parse a byte-count token to `INT` bytes.
726///
727/// Bare digits are bytes; suffixes `B`/`KB`/`MB`/`GB`/`TB` scale
728/// decimal and `KIB`/`MIB`/`GIB`/`TIB` binary, in any case. Plain
729/// `INT` values pass through (already bytes); integral finite `FLOAT`
730/// values convert. Pairs with `FORMAT_BYTE_COUNT` for the round trip.
731///
732/// ```oxdock
733/// # Units parse case-insensitively; bare digits are bytes.
734/// IMPORT [STD]
735/// LET $bytes: INT = PARSE_BYTE_COUNT("1Gb")
736/// ASSERT_EQ $bytes 1_000_000_000
737///
738/// # Binary suffixes scale by powers of two.
739/// LET $mebi: INT = PARSE_BYTE_COUNT("2mib")
740/// ASSERT_EQ $mebi 2_097_152
741///
742/// # Digit runs group Rust-literal style.
743/// LET $grouped: INT = PARSE_BYTE_COUNT("1_000_000")
744/// ASSERT_EQ $grouped 1_000_000
745///
746/// # Plain numbers pass through as bytes already.
747/// LET $plain: INT = PARSE_BYTE_COUNT(1_048_576)
748/// ASSERT_EQ $plain 1_048_576
749///
750/// # Bare literals group too.
751/// LET $bare: INT = PARSE_BYTE_COUNT(1_000_000)
752/// ASSERT_EQ $bare 1_000_000
753///
754/// # One optional space separates number from unit.
755/// LET $spaced: INT = PARSE_BYTE_COUNT("1 GB")
756/// ASSERT_EQ $spaced 1_000_000_000
757/// ```
758///
759#[oxdock_func(pure, returns = TypeTag::Int)]
760#[example(
761    name = "parse",
762    code = r###"
763    IMPORT [STD]
764    LET $n: INT = PARSE_BYTE_COUNT("10KB")
765    ASSERT_EQ $n 10_000
766    LET $identity: INT = PARSE_BYTE_COUNT(512)
767    ASSERT_EQ $identity 512
768    "###
769)]
770fn parse_byte_count(
771    /// Byte-count token to parse, or bytes already.
772    #[union(Int, Float, String)]
773    text: Value,
774) -> Result<Value> {
775    if let Some(n) = text.as_i64() {
776        if n < 0 {
777            return Err(anyhow::anyhow!(
778                "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
779            ));
780        }
781        return Ok(Value::int(n));
782    }
783    if let Some(f) = text.as_f64() {
784        if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
785            return Ok(Value::int(f as i64));
786        }
787        return Err(anyhow::anyhow!(
788            "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
789        ));
790    }
791    let Some(s) = text.as_str() else {
792        return Err(anyhow::anyhow!(
793            "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
794        ));
795    };
796    let n = oxdock_parser::command::parse_byte_count(s)?;
797    let n = i64::try_from(n)
798        .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
799    Ok(Value::int(n))
800}
801
802/// Format millisecond durations canonically (`500ms`, `10s`, `2m`,
803/// `1h`): the inverse of `PARSE_DURATION`, so formatted values
804/// reparse exactly. Negative inputs fail.
805///
806#[oxdock_func(pure, returns = TypeTag::String)]
807#[example(
808    name = "format and round-trip",
809    code = r###"
810    # Durations render in the largest exact unit.
811    IMPORT [STD]
812    LET $pretty: STRING = FORMAT_DURATION(90_000)
813    ASSERT_EQ $pretty "90s"
814
815    # The pair round-trips through the parser.
816    LET $back: INT = PARSE_DURATION($pretty)
817    ASSERT_EQ $back 90_000
818    "###
819)]
820fn format_duration(
821    /// Milliseconds to format; negatives fail.
822    millis: i64,
823) -> Result<Value> {
824    if millis < 0 {
825        return Err(anyhow::anyhow!(
826            "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
827        ));
828    }
829    Ok(Value::string(oxdock_parser::command::format_duration(
830        &std::time::Duration::from_millis(millis as u64),
831    )))
832}
833
834/// Parse a duration token to `INT` milliseconds.
835///
836/// Suffixes `ms`/`s`/`m`/`h`; a bare number means seconds. Pairs with
837/// `FORMAT_DURATION` for the round trip.
838///
839#[oxdock_func(pure, returns = TypeTag::Int)]
840#[example(
841    name = "parse",
842    code = r###"
843    # A bare number means seconds, like TIMEOUT.
844    IMPORT [STD]
845    LET $ms: INT = PARSE_DURATION("2m")
846    ASSERT_EQ $ms 120_000
847
848    # Milliseconds stay exact.
849    LET $exact: INT = PARSE_DURATION("1500ms")
850    ASSERT_EQ $exact 1_500
851
852    # One optional space separates number from unit.
853    LET $spaced: INT = PARSE_DURATION("1 h")
854    ASSERT_EQ $spaced 3_600_000
855    "###
856)]
857fn parse_duration(
858    /// Duration token to parse.
859    text: String,
860) -> Result<Value> {
861    let duration = oxdock_parser::command::parse_duration(&text)?;
862    let millis = i64::try_from(duration.as_millis())
863        .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
864    Ok(Value::int(millis))
865}
866
867/// List workspace paths matching a glob pattern.
868///
869/// Sorted, root-relative LIST; empty on no match or `..` escape.
870///
871#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
872#[example(
873    name = "match",
874    code = r###"
875    IMPORT [STD]
876    WRITE "notes-a.md" "a"
877    WRITE "notes-b.md" "b"
878    WRITE "other.txt" "c"
879    LET $found: LIST<STRING> = GLOB("notes-*.md")
880    ASSERT_EQ $found.0 "notes-a.md"
881    ASSERT_EQ $found.1 "notes-b.md"
882    "###
883)]
884fn glob<P: ProcessManager>(
885    cx: &mut StepCtx<P>,
886    /// Glob pattern matched against workspace paths.
887    #[union(String, Path)]
888    pattern: Value,
889) -> Result<Value> {
890    let text = super::args::string_or_path_text(&pattern)?;
891    super::args::glob_from_value(&[Value::string(text)], cx)
892}
893
894/// Load and parse a TOML file.
895///
896/// Reads a workspace file and parses TOML into a DSL value.
897///
898#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
899#[example(
900    name = "load",
901    code = r###"
902    IMPORT [STD]
903    WRITE "cfg.toml" "title = \"demo\""
904    LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
905    ASSERT_EQ $cfg.title "demo"
906    "###
907)]
908fn load_toml<P: ProcessManager>(
909    cx: &mut StepCtx<P>,
910    /// Workspace file path to load and parse as TOML.
911    #[union(String, Path)]
912    path: Value,
913) -> Result<Value> {
914    let text = super::args::string_or_path_text(&path)?;
915    super::args::load_toml_from_value(&[Value::string(text)], cx)
916}
917
918/// Load and parse a JSON file.
919///
920/// Reads a workspace file and parses JSON into a DSL value. Returns
921/// `ANY` by design: a top-level array or scalar parses to `LIST` or a
922/// scalar word. `LET` coercion still checks the actual value at
923/// assignment.
924///
925#[oxdock_func(rpn, returns = TypeTag::Any)]
926#[example(
927    name = "load",
928    code = r###"
929    IMPORT [STD]
930    WRITE "data.json" "{\"a\": 1}"
931    LET $doc: MAP<ANY> = LOAD_JSON("data.json")
932    ASSERT_EQ $doc.a 1
933    "###
934)]
935fn load_json<P: ProcessManager>(
936    cx: &mut StepCtx<P>,
937    /// Workspace file path to load and parse as JSON.
938    #[union(String, Path)]
939    path: Value,
940) -> Result<Value> {
941    let text = super::args::string_or_path_text(&path)?;
942    super::args::load_json_from_value(&[Value::string(text)], cx)
943}
944
945/// Parse TOML text already held in memory.
946///
947/// Uses the same conversion as file loading, so fetch bodies, file
948/// contents, and captured text share one JSON/TOML shape.
949///
950#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
951#[example(
952    name = "parse",
953    code = r###"
954    IMPORT [STD]
955    LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
956    ASSERT_EQ $doc.title "demo"
957    "###
958)]
959fn parse_toml(
960    /// TOML text already held in memory.
961    text: String,
962) -> Result<Value> {
963    super::args::parse_toml_from_value(Value::string(text))
964}
965
966/// Parse JSON text already held in memory.
967///
968/// Uses the same conversion as file loading, so fetch bodies, file
969/// contents, and captured text share one JSON value shape. Returns
970/// `ANY` by design, matching `LOAD_JSON`: a top-level array or scalar
971/// parses to `LIST` or a scalar word. `LET` coercion still checks the
972/// actual value at assignment.
973///
974#[oxdock_func(pure, returns = TypeTag::Any)]
975#[example(
976    name = "parse",
977    code = r###"
978    # Parse in-memory JSON text with the same conversion as file loading.
979    IMPORT [STD]
980    LET $body: STRING = "{\"a\": 1}"
981    LET $doc: ANY = PARSE_JSON($body)
982    ASSERT_EQ $doc.a 1
983
984    # Top-level arrays parse to LIST, which is why the return is ANY.
985    LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
986    ASSERT_EQ $items.0 1
987    ASSERT_EQ $items.1 2
988    "###
989)]
990fn parse_json(
991    /// JSON text already held in memory.
992    text: String,
993) -> Result<Value> {
994    super::args::parse_json_from_value(Value::string(text))
995}
996
997/// Describe a filesystem entry.
998///
999/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
1000/// there is no RPN arm for filesystem IO.
1001///
1002#[oxdock_func(returns = TypeTag::String)]
1003#[example(
1004    name = "describe",
1005    code = r###"
1006    IMPORT [STD]
1007    WRITE "entry.txt" "words"
1008    LET $kind: STRING = PATH_TYPE("entry.txt")
1009    ASSERT_EQ $kind "file"
1010    LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1011    ASSERT_EQ $missing "absent"
1012    "###
1013)]
1014fn path_type<P: ProcessManager>(
1015    cx: &mut StepCtx<P>,
1016    /// Workspace path of the entry to describe.
1017    #[union(String, Path)]
1018    path: Value,
1019) -> Result<Value> {
1020    let text = super::args::string_or_path_text(&path)?;
1021    super::args::path_type_from_value(&[Value::string(text)], cx)
1022}
1023
1024/// Report whether an ordinary file can be created at a path.
1025///
1026/// Walks up to the nearest existing ancestor, requires it be a
1027/// directory, and probes writability by creating and deleting a probe
1028/// file, so retry loops never litter. The empty string is false.
1029/// AST-only by design, like `PATH_TYPE`: there is no RPN arm for
1030/// filesystem IO.
1031///
1032#[oxdock_func(returns = TypeTag::Bool)]
1033#[example(
1034    name = "probe",
1035    code = r###"
1036    # An absent nested path is writable when its ancestor is.
1037    IMPORT [STD]
1038    LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1039    ASSERT_EQ $fresh true
1040
1041    # The empty string never aliases the working directory.
1042    LET $empty: BOOL = PATH_WRITABLE("")
1043    ASSERT_EQ $empty false
1044    "###
1045)]
1046fn path_writable<P: ProcessManager>(
1047    cx: &mut StepCtx<P>,
1048    /// Workspace path to probe for file creation.
1049    #[union(String, Path)]
1050    path: Value,
1051) -> Result<Value> {
1052    let text = super::args::string_or_path_text(&path)?;
1053    super::args::path_writable_from_value(&[Value::string(text)], cx)
1054}
1055
1056/// Report whether a name resolves to an executable file (#100).
1057///
1058/// Bare command names search `env:PATH` (`IS_EXEC("tar")` finds the
1059/// first executable `tar`, plus `tar.exe`, on `PATH`); spellings
1060/// containing a separator check that file directly. True means a real
1061/// file with an executable bit on Unix, or a `PATHEXT` extension on
1062/// Windows: each `env:PATHEXT` entry is probed in order (default
1063/// `.COM;.EXE;.BAT;.CMD`, an explicitly empty value probes nothing). Absolute `PATH` entries resolve through the workspace as
1064/// usual, so host probing wants `WORKSPACE SYSTEM` and an inherited
1065/// `PATH`; anything unresolvable reads false, never errors. AST-only
1066/// by design, like `PATH_TYPE`: there is no RPN arm for filesystem IO.
1067///
1068#[oxdock_func(returns = TypeTag::Bool)]
1069#[example(
1070    name = "probe",
1071    code = r###"
1072    # Missing tools read false instead of failing the run.
1073    IMPORT [STD]
1074    LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1075    ASSERT_EQ $missing false
1076
1077    # Plain files are not executable on any platform.
1078    WRITE tool.txt payload
1079    LET $plain: BOOL = IS_EXEC("tool.txt")
1080    ASSERT_EQ $plain false
1081    "###
1082)]
1083fn is_exec<P: ProcessManager>(
1084    cx: &mut StepCtx<P>,
1085    /// Command name or file path to probe.
1086    #[union(String, Path)]
1087    name: Value,
1088) -> Result<Value> {
1089    let text = super::args::string_or_path_text(&name)?;
1090    super::args::is_exec_from_value(&[Value::string(text)], cx)
1091}
1092
1093/// Report whether a map holds a key.
1094///
1095/// Pure MAP probe so scripts can branch on optional fields without
1096/// tripping the strict missing-key error.
1097///
1098#[oxdock_func(pure, returns = TypeTag::Bool)]
1099#[example(
1100    name = "probe",
1101    code = r###"
1102    IMPORT [STD]
1103    LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1104    LET $hit: BOOL = HAS_KEY($m, "a")
1105    ASSERT_EQ $hit true
1106    LET $miss: BOOL = HAS_KEY($m, "b")
1107    ASSERT_EQ $miss false
1108    "###
1109)]
1110fn has_key(
1111    /// Map to probe.
1112    map: BTreeMap<String, Value>,
1113    /// Key to look up.
1114    key: String,
1115) -> Result<Value> {
1116    super::args::has_key_from_value(Value::map(map), &key)
1117}
1118
1119/// Insert one key into a map.
1120///
1121/// Fails on duplicates so two entries sharing a key fail the run
1122/// instead of silently shadowing each other.
1123///
1124#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1125#[example(
1126    name = "insert",
1127    code = r###"
1128    IMPORT [STD]
1129    LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1130    ASSERT_EQ $m.a 1
1131    "###
1132)]
1133fn map_set(
1134    /// Map to insert into.
1135    map: BTreeMap<String, Value>,
1136    /// Key to insert; duplicates fail.
1137    key: String,
1138    /// Value to store.
1139    value: Value,
1140) -> Result<Value> {
1141    super::args::map_set_from_value(Value::map(map), key, value)
1142}
1143
1144/// Draw a random FLOAT uniformly from [0, 1), optionally seeded.
1145///
1146/// Impure by design: unseeded calls return different values, so this
1147/// runs on the AST script path only, never as a `{{ }}` placeholder
1148/// call. A seed draws the same value on every run, for deterministic
1149/// fixtures. Scale and shift the draw for wider ranges.
1150///
1151#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1152#[example(
1153    name = "seeded draw",
1154    code = r###"
1155    # A seed draws the same value on every run.
1156    IMPORT [STD]
1157    LET $one: FLOAT = RAND({seed: 7})
1158    LET $two: FLOAT = RAND({seed: 7})
1159    ASSERT_EQ $one $two
1160    "###
1161)]
1162#[example(
1163    name = "unseeded draw",
1164    code = r###"
1165    # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1166    IMPORT [STD]
1167    LET $draw: FLOAT = RAND()
1168    LET $delay: FLOAT = 1.0 + $draw * 10.0
1169    IF $delay < 1.0 {
1170        EXIT 1
1171    }
1172    IF $delay >= 11.0 {
1173        EXIT 1
1174    }
1175    ECHO "retrying in {{ $delay }}s"
1176    "###
1177)]
1178fn rand<P: ProcessManager>(
1179    cx: &mut StepCtx<P>,
1180    /// Draw settings: `seed`. Omittable: a missing options MAP fills `{}`.
1181    #[options("seed?: INT")]
1182    #[optional]
1183    options: BTreeMap<String, Value>,
1184) -> Result<Value> {
1185    let _ = cx;
1186    // `check_options` in the wrapper verified the shape above; the
1187    // read below narrows infallibly after.
1188    let seed = options
1189        .get("seed")
1190        .map(|value| value.as_i64().expect("check_options verified INT"));
1191    super::args::rand_float_from_value(seed)
1192}
1193
1194/// Encode a STRING as standard base64.
1195///
1196/// Padded RFC 4648 alphabet, so encoded output pastes into any
1197/// standard decoder. Pairs with `BASE64_DECODE` for the round trip.
1198///
1199#[oxdock_func(pure, returns = TypeTag::String)]
1200#[example(
1201    name = "encode",
1202    code = r###"
1203    # Encode text to standard base64.
1204    IMPORT [STD]
1205    LET $encoded: STRING = BASE64_ENCODE("hello")
1206    ASSERT_EQ $encoded "aGVsbG8="
1207    "###
1208)]
1209fn base64_encode(
1210    /// Text to encode.
1211    text: String,
1212) -> Result<Value> {
1213    super::args::base64_encode_from_value(Value::string(text))
1214}
1215
1216/// Decode standard base64 to a STRING.
1217///
1218/// Fails naming the input on invalid alphabet characters or
1219/// non-UTF-8 payloads instead of rendering a silent empty. Pairs
1220/// with `BASE64_ENCODE` for the round trip.
1221///
1222#[oxdock_func(pure, returns = TypeTag::String)]
1223#[example(
1224    name = "decode",
1225    code = r###"
1226    # Decode standard base64 back to text.
1227    IMPORT [STD]
1228    LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1229    ASSERT_EQ $decoded "hello"
1230    "###
1231)]
1232fn base64_decode(
1233    /// Base64 text to decode.
1234    text: String,
1235) -> Result<Value> {
1236    super::args::base64_decode_from_value(Value::string(text))
1237}
1238
1239/// Encode a script value as JSON with one trailing newline.
1240///
1241/// Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT,
1242/// BOOL, LIST, MAP) survive, anything else fails here instead of
1243/// rendering as a silent empty.
1244///
1245#[oxdock_func(pure, returns = TypeTag::String)]
1246#[example(
1247    name = "encode",
1248    code = r###"
1249    IMPORT [STD]
1250    LET $json: STRING = TO_JSON({a: 1})
1251    ASSERT_EQ $json "{\"a\":1}\n"
1252    "###
1253)]
1254fn to_json(
1255    /// Value to encode as JSON.
1256    #[union(String, Int, Float, Bool, List, Map)]
1257    value: Value,
1258) -> Result<Value> {
1259    super::args::to_json_from_value(value)
1260}
1261
1262/// Name the word a value holds, for data-driven branching.
1263///
1264/// Returns the registered type word (`STRING`, `INT`, `FLOAT`, `BOOL`,
1265/// `LIST`, `MAP`, plus handle words like `PIPE`): the same name the
1266/// value prints in arity and coercion errors, so scripts can branch
1267/// on config shapes (a path string or a path list) without failing.
1268///
1269#[oxdock_func(pure, returns = TypeTag::String)]
1270#[example(
1271    name = "name the word",
1272    code = r###"
1273    IMPORT [STD]
1274    LET $word: STRING = TYPE_OF(42)
1275    ASSERT_EQ $word "INT"
1276    "###
1277)]
1278fn type_of(
1279    /// Value whose word to name.
1280    value: Value,
1281) -> Result<Value> {
1282    super::args::type_of_from_value(value)
1283}
1284
1285/// Merge a LIST of MAPs in order under one duplicate policy.
1286///
1287/// `fail_on_duplicate` fails naming the repeated key, so two files
1288/// claiming one placeholder fail the run instead of shadowing each
1289/// other. `overwrite` lets later files win, for environment overlays.
1290/// Non MAP elements fail naming their position.
1291///
1292#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1293#[example(
1294    name = "merge",
1295    code = r###"
1296    IMPORT [STD]
1297    LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1298    ASSERT_EQ $m.a 1
1299    ASSERT_EQ $m.b 2
1300    "###
1301)]
1302fn merge_maps(
1303    /// LIST of MAPs to merge in order.
1304    maps: Vec<BTreeMap<String, Value>>,
1305    /// Duplicate policy.
1306    #[values("fail_on_duplicate", "overwrite")]
1307    policy: String,
1308) -> Result<Value> {
1309    super::args::merge_maps_from_value(
1310        Value::list(maps.into_iter().map(Value::map).collect()),
1311        policy,
1312    )
1313}
1314
1315/// List all visible function names.
1316///
1317/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
1318/// plus host-registered names.
1319#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1320#[example(
1321    name = "list",
1322    code = r###"
1323    IMPORT [STD]
1324    LET $names: LIST<STRING> = FUNCTIONS()
1325    ASSERT_CONTAINS $names "STD::INT"
1326    "###
1327)]
1328fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1329    let mut names: Vec<String> = cx
1330        .state
1331        .list_functions()
1332        .into_iter()
1333        .map(|meta| meta.name)
1334        .collect();
1335    names.sort();
1336    names.dedup();
1337    Ok(Value::list(names.into_iter().map(Value::string).collect()))
1338}
1339
1340/// Describe one function by qualified name.
1341///
1342/// Returns a MAP with name, module, kind, params, returns, rpn, and
1343/// summary. `params` is always a LIST (empty for parameterless
1344/// functions) of entries carrying name, param_type, allowed, docs,
1345/// options, and optional flags, so the shape holds for every entry. Bare names
1346/// fail closed: `DESCRIBE` requires the qualified form (except
1347/// `INSPECT`, which is syntax rather than a registry entry). Errors
1348/// on unknown function.
1349///
1350/// Field table for the `DESCRIBE` result bundle: one source for the
1351/// shape the host mints, so introspection, enforcement, and
1352/// documentation cannot drift apart.
1353
1354#[oxdock_func(
1355    returns = TypeTag::Record(std::sync::Arc::from([Field {
1356        name: "name".to_string(),
1357        ty: TypeTag::String,
1358        docs: "Qualified function name.",
1359        optional: false,
1360    }, Field {
1361        name: "module".to_string(),
1362        ty: TypeTag::String,
1363        docs: "Owning module.",
1364        optional: false,
1365    }, Field {
1366        name: "kind".to_string(),
1367        ty: TypeTag::String,
1368        docs: "Origin label (`host` or `script`).",
1369        optional: false,
1370    }, Field {
1371        name: "params".to_string(),
1372        ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1373            TypeTag::Any,
1374        )))),
1375        docs: "Parameter entries (empty for parameterless functions).",
1376        optional: false,
1377    }, Field {
1378        name: "returns".to_string(),
1379        ty: TypeTag::String,
1380        docs: "Structural return shape (empty when untagged).",
1381        optional: false,
1382    }, Field {
1383        name: "rpn".to_string(),
1384        ty: TypeTag::Bool,
1385        docs: "True when callable in RPN position.",
1386        optional: false,
1387    }, Field {
1388        name: "summary".to_string(),
1389        ty: TypeTag::String,
1390        docs: "One-line description.",
1391        optional: false,
1392    }]))
1393    summary = "Describe one function by qualified name."
1394)]
1395#[example(
1396    name = "describe",
1397    code = r###"
1398    IMPORT [STD]
1399    LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1400    ASSERT_EQ $info.name "STD::INT"
1401    ASSERT_EQ $info.returns "INT"
1402    "###
1403)]
1404fn describe<P: ProcessManager>(
1405    cx: &mut StepCtx<P>,
1406    /// Qualified function name (`MODULE::NAME`).
1407    name: String,
1408) -> Result<Value> {
1409    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1410        anyhow::bail!(
1411            "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1412        );
1413    }
1414    cx.state
1415        .describe_function(&name)
1416        .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1417}
1418
1419/// List all known type names.
1420///
1421/// Sorted LIST of startup plus host-registered type descriptors. Reads the
1422/// run's name directory, so it runs on the AST path like the other
1423/// introspection functions.
1424#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1425#[example(
1426    name = "list",
1427    code = r###"
1428    IMPORT [STD]
1429    LET $names: LIST<STRING> = TYPES()
1430    ASSERT_CONTAINS $names "STRING"
1431    "###
1432)]
1433fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1434    Ok(Value::list(
1435        cx.state
1436            .type_names()
1437            .into_iter()
1438            .map(Value::string)
1439            .collect(),
1440    ))
1441}
1442
1443/// Describe one type by name.
1444///
1445/// Returns a MAP with name, summary, and docs. Errors on unknown type.
1446/// Reads the run's name directory, so it runs on the AST path.
1447///
1448#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1449    name: "name".to_string(),
1450    ty: TypeTag::String,
1451    docs: "Queried type name.",
1452    optional: false,
1453}, Field {
1454    name: "summary".to_string(),
1455    ty: TypeTag::String,
1456    docs: "One-line description.",
1457    optional: false,
1458}, Field {
1459    name: "docs".to_string(),
1460    ty: TypeTag::String,
1461    docs: "Full documentation text.",
1462    optional: false,
1463}])))]
1464#[example(
1465    name = "describe",
1466    code = r###"
1467    IMPORT [STD]
1468    LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1469    ASSERT_EQ $info.name "STRING"
1470    "###
1471)]
1472fn type_describe<P: ProcessManager>(
1473    cx: &mut StepCtx<P>,
1474    /// Type name to describe.
1475    name: String,
1476) -> Result<Value> {
1477    if let Some(descriptor) = cx.state.describe_type(&name) {
1478        let mut map = BTreeMap::new();
1479        map.insert(
1480            "name".to_string(),
1481            Value::string(descriptor.name.to_string()),
1482        );
1483        map.insert(
1484            "summary".to_string(),
1485            Value::string(descriptor.summary.to_string()),
1486        );
1487        map.insert(
1488            "docs".to_string(),
1489            Value::string(descriptor.docs.to_string()),
1490        );
1491        return Ok(Value::map(map));
1492    }
1493    // Script aliases have no descriptor but introspect the same way:
1494    // the entry names the alias and its canonical target spelling.
1495    if let Some(target) = cx.state.alias_target(&name) {
1496        let mut map = BTreeMap::new();
1497        map.insert("name".to_string(), Value::string(name.clone()));
1498        map.insert(
1499            "summary".to_string(),
1500            Value::string(format!("Script type alias for {target}.")),
1501        );
1502        map.insert(
1503            "docs".to_string(),
1504            Value::string(format!(
1505                "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1506            )),
1507        );
1508        return Ok(Value::map(map));
1509    }
1510    Err(anyhow::anyhow!("unknown type {name}"))
1511}
1512
1513/// Report whether a standard stream is a terminal.
1514///
1515/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
1516/// answers for the step's stream as currently bound, so scripts can adapt
1517/// prompts, colors, and progress output. Anything diverted from the
1518/// terminal reports false without touching host handles: `WITH_IO` pipe
1519/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
1520/// runner sinks, and any materialized stdin stream (only a directly
1521/// inherited fd falls back to the process check). A transparent root tee
1522/// still answers the session question via the process check. The name
1523/// matches exactly (no case folding): anything else bails. AST-only:
1524/// reads the step context like the other introspection functions.
1525///
1526#[oxdock_func(returns = TypeTag::Bool)]
1527#[example(
1528    name = "null stdin",
1529    code = r###"
1530    # A null stdin is never a terminal, in every harness.
1531    IMPORT [STD]
1532    LET $term: BOOL = IS_TERMINAL("stdin")
1533    ASSERT_EQ $term false
1534    "###
1535)]
1536fn is_terminal<P: ProcessManager>(
1537    cx: &mut StepCtx<P>,
1538    /// Stream name: `stdin`, `stdout`, or `stderr` (exact match).
1539    #[values("stdin", "stdout", "stderr")]
1540    stream_name: String,
1541) -> Result<Value> {
1542    use std::io::IsTerminal;
1543    let terminal = match stream_name.as_str() {
1544        "stdin" => {
1545            // A script-pipe backend is definitive; Null is /dev/null.
1546            // Only a directly inherited fd answers the process check: a
1547            // materialized Stream is always a binding (staged input,
1548            // WITH_IO pipe, or OS half), never the raw fd.
1549            if cx.stdin_pipe.is_some() {
1550                false
1551            } else {
1552                match &cx.stdin {
1553                    CommandStdin::Null => false,
1554                    #[cfg(not(miri))]
1555                    CommandStdin::OsPipe(_) => false,
1556                    CommandStdin::Stream(_) => false,
1557                    CommandStdin::Inherit => std::io::stdin().is_terminal(),
1558                }
1559            }
1560        }
1561        "stdout" => {
1562            if cx.out_pipe.is_some() {
1563                // WITH_IO script-pipe binding: never a terminal.
1564                false
1565            } else if cx.state.io.stdout().is_some() {
1566                // Staged runner sink: the root tee diverts bytes to the
1567                // sink only, never to real stdout.
1568                false
1569            } else {
1570                match &cx.out {
1571                    // Unbound: inherited straight through.
1572                    None => std::io::stdout().is_terminal(),
1573                    // OS kernel pipe: never a terminal.
1574                    #[cfg(not(miri))]
1575                    Some(StreamHandle::Os(_)) => false,
1576                    // Root tee (transparent: forwards to real stdout when
1577                    // unstaged, so terminal-ness survives) versus a genuine
1578                    // diversion. WITH_IO bindings never reach here (script
1579                    // pipes trip out_pipe, OS pipes trip Os, staged sinks
1580                    // trip above). LET-capture cannot reach here either:
1581                    // assign_capture installs no sink for a bare NAME(...)
1582                    // call, so a direct query always observes the ambient
1583                    // routing. The process check answers the session
1584                    // question.
1585                    Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
1586                }
1587            }
1588        }
1589        "stderr" => {
1590            if cx.state.io.stderr().is_some() {
1591                // Staged runner sink: diverted, never a terminal.
1592                false
1593            } else {
1594                match &cx.err {
1595                    // Unbound: inherited straight through.
1596                    None => std::io::stderr().is_terminal(),
1597                    // OS kernel pipe: never a terminal.
1598                    #[cfg(not(miri))]
1599                    Some(StreamHandle::Os(_)) => false,
1600                    // Root never tees stderr and LET never captures it,
1601                    // so a bound handle here is always a WITH_IO binding.
1602                    Some(StreamHandle::Stream(_)) => false,
1603                }
1604            }
1605        }
1606        _ => anyhow::bail!(
1607            // Unreachable through the macro path: the generated
1608            // extractor rejects non-members before the body runs, and
1609            // the static pre-pass rejects bad literals earlier still.
1610            // Kept as a bail (never a panic) for hand-built callers.
1611            "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
1612        ),
1613    };
1614    Ok(Value::bool(terminal))
1615}
1616
1617/// Create a counting semaphore admitting at most `max` concurrent holders.
1618///
1619/// Non-positive maxima bail. The word names a shared backend: every clone
1620/// observes the same count, and admission runs through
1621/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
1622/// readout.
1623///
1624#[oxdock_func(returns = TypeTag::Semaphore)]
1625#[example(
1626    name = "mint",
1627    code = r###"
1628    # Mint a semaphore admitting at most two holders.
1629    IMPORT [STD]
1630    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1631
1632    # A fresh semaphore reports its full cap as available.
1633    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1634    ASSERT_EQ $free 2
1635    "###
1636)]
1637fn semaphore_new<P: ProcessManager>(
1638    cx: &mut StepCtx<P>,
1639    /// Maximum concurrent holders; must be positive.
1640    max: i64,
1641) -> Result<Value> {
1642    let _ = cx;
1643    if max <= 0 {
1644        return Err(anyhow::anyhow!(
1645            "SEMAPHORE_NEW() requires a positive max, got {max}"
1646        ));
1647    }
1648    Ok(Value::semaphore(max as usize))
1649}
1650
1651/// Attempt one non-blocking acquire, always answering a MAP.
1652///
1653/// `held` is `true` with the permit under the `permit` key, or `false`
1654/// with no `permit` key: branch on `$m.held` directly. The DSL has no
1655/// null, so the absent key is the miss shape. Do not read `$m.permit`
1656/// unless `held`: missing-key access bails strictly.
1657/// Never waits, so no wait can wedge.
1658///
1659#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1660    name: "held".to_string(),
1661    ty: TypeTag::Bool,
1662    docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
1663    optional: false,
1664}, Field {
1665    name: "permit".to_string(),
1666    ty: TypeTag::Permit,
1667    docs: "Permit handle; read only when `held`.",
1668    optional: true,
1669}])))]
1670#[example(
1671    name = "acquire",
1672    code = r###"
1673    # First acquire holds with a permit to bind.
1674    IMPORT [STD]
1675    LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
1676    LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1677    ASSERT_EQ $first.held true
1678    LET $permit: PERMIT = $first.permit
1679
1680    # A capped semaphore answers held false with no permit key.
1681    LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1682    ASSERT_EQ $second.held false
1683    LET $has_permit: BOOL = HAS_KEY($second, "permit")
1684    ASSERT_EQ $has_permit false
1685    "###
1686)]
1687fn semaphore_try_acquire<P: ProcessManager>(
1688    cx: &mut StepCtx<P>,
1689    /// Semaphore handle from `SEMAPHORE_NEW`.
1690    sem: Arc<SemaphoreState>,
1691) -> Result<Value> {
1692    let _ = cx;
1693    let mut map = BTreeMap::new();
1694    if sem.try_acquire() {
1695        map.insert("held".to_string(), Value::bool(true));
1696        map.insert("permit".to_string(), Value::permit(&sem));
1697    } else {
1698        map.insert("held".to_string(), Value::bool(false));
1699    }
1700    Ok(Value::map(map))
1701}
1702
1703/// Read free permits under the lock, with no mutation.
1704///
1705/// Observability only (audit lines, healthchecks: `active = max - free`).
1706/// Exact at read time and stale the instant the caller acts on it, so it
1707/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
1708///
1709#[oxdock_func(pure, returns = TypeTag::Int)]
1710#[example(
1711    name = "readout",
1712    code = r###"
1713    # Hold one permit on a cap of two.
1714    IMPORT [STD]
1715    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
1716    LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
1717    ASSERT_EQ $acq.held true
1718
1719    # One held permit leaves exactly one free.
1720    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
1721    ASSERT_EQ $free 1
1722    "###
1723)]
1724fn semaphore_available(
1725    /// Semaphore handle from `SEMAPHORE_NEW`.
1726    sem: Arc<SemaphoreState>,
1727) -> Result<Value> {
1728    Ok(Value::int(sem.available() as i64))
1729}
1730
1731/// True when a pipe sits at end of stream: closed with nothing buffered,
1732/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
1733/// Live writers, pinned keepers, and buffered bytes all answer false.
1734/// Never blocks: a reader already blocked stays blocked, so branch on
1735/// `EOF` before reading, not after. OS pairs and unbound handles answer
1736/// best-effort (kernel bytes are invisible there; see `INSPECT`).
1737/// Non-pipe arguments bail at the boundary: the parameter declares
1738/// `PIPE`, so the extractor and the static pass reject them before
1739/// the body runs.
1740///
1741#[oxdock_func(returns = TypeTag::Bool)]
1742#[example(
1743    name = "drain to end",
1744    code = r###"
1745    # Capture two lines, then drain to end of stream with no sentinel line.
1746    IMPORT [STD]
1747    LET $cap: PIPE
1748    WITH_IO [stdout=$cap] {
1749        ECHO "one"
1750        ECHO "two"
1751    }
1752
1753    # The loop exits on close, and the count proves both lines drained.
1754    LET $n: INT = 0
1755    WHILE !EOF($cap) {
1756        WITH_IO [stdin=$cap] READ_LINE $line
1757        $n = $n + 1
1758    }
1759    ASSERT_EQ $n 2
1760    "###
1761)]
1762fn eof<P: ProcessManager>(
1763    cx: &mut StepCtx<P>,
1764    /// Pipe handle to query for end of stream.
1765    pipe: PipeHandle,
1766) -> Result<Value> {
1767    let info = cx.state.io.inspect_pipe(&pipe);
1768    Ok(Value::bool(info.closed && info.buffered == 0))
1769}
1770
1771fn meta_to_value(meta: &FuncMeta) -> Value {
1772    let mut map = BTreeMap::new();
1773    map.insert("name".to_string(), Value::string(meta.name.clone()));
1774    map.insert("module".to_string(), Value::string(meta.module.clone()));
1775    map.insert(
1776        "kind".to_string(),
1777        Value::string(meta.kind.label().to_string()),
1778    );
1779    let params = match &meta.params {
1780        Some(params) => Value::list(
1781            params
1782                .iter()
1783                .map(|p| {
1784                    let mut entry = BTreeMap::new();
1785                    entry.insert("name".to_string(), Value::string(p.name.clone()));
1786                    entry.insert(
1787                        "param_type".to_string(),
1788                        Value::string(
1789                            p.param_type
1790                                .as_ref()
1791                                .map(render_structural)
1792                                .unwrap_or_default(),
1793                        ),
1794                    );
1795                    entry.insert(
1796                        "allowed".to_string(),
1797                        Value::string(
1798                            p.allowed
1799                                .map(|values| values.join(", "))
1800                                .unwrap_or_default(),
1801                        ),
1802                    );
1803                    entry.insert("docs".to_string(), Value::string(String::new()));
1804                    entry.insert("optional".to_string(), Value::bool(p.optional));
1805                    entry.insert(
1806                        "options".to_string(),
1807                        match p.options {
1808                            Some(keys) => Value::list(
1809                                keys.iter()
1810                                    .map(|key| {
1811                                        let mut option = BTreeMap::new();
1812                                        option.insert(
1813                                            "name".to_string(),
1814                                            Value::string(key.name.to_string()),
1815                                        );
1816                                        option.insert(
1817                                            "value_type".to_string(),
1818                                            Value::string(render_structural(&key.value)),
1819                                        );
1820                                        option.insert(
1821                                            "required".to_string(),
1822                                            Value::bool(key.required),
1823                                        );
1824                                        option.insert(
1825                                            "default".to_string(),
1826                                            Value::string(
1827                                                key.default.unwrap_or_default().to_string(),
1828                                            ),
1829                                        );
1830                                        Value::map(option)
1831                                    })
1832                                    .collect(),
1833                            ),
1834                            None => Value::string(String::new()),
1835                        },
1836                    );
1837                    Value::map(entry)
1838                })
1839                .collect(),
1840        ),
1841        // Parameterless functions mint an empty LIST, never an empty
1842        // STRING: the `DESCRIBE` return tag promises `LIST<MAP<ANY>>`
1843        // for every entry, and the boundary enforces it.
1844        None => Value::list(Vec::new()),
1845    };
1846    map.insert("params".to_string(), params);
1847    map.insert(
1848        "returns".to_string(),
1849        Value::string(
1850            meta.returns
1851                .as_ref()
1852                .map(render_structural)
1853                .unwrap_or_default(),
1854        ),
1855    );
1856    map.insert("rpn".to_string(), Value::bool(meta.rpn));
1857    map.insert(
1858        "summary".to_string(),
1859        Value::string(meta.summary.to_string()),
1860    );
1861    Value::map(map)
1862}
1863
1864/// One named record schema: a shape host functions produce and scripts
1865/// bind by name (`LET $s: SSH_SESSION_INFO`). Travels with its module
1866/// so schemas register exactly when their producer does.
1867#[derive(Debug, Clone)]
1868pub struct RecordSchema {
1869    pub name: &'static str,
1870    pub fields: std::sync::Arc<[Field]>,
1871}
1872
1873/// One host library: functions and types registered under a single module
1874/// name. `Engine::register_module` stages these; runs expose them as
1875/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
1876#[derive(Clone)]
1877pub struct HostModule<P: ProcessManager> {
1878    pub name: String,
1879    pub funcs: Vec<HostRegistration<P>>,
1880    pub types: Vec<&'static TypeDescriptor>,
1881    pub record_schemas: Vec<RecordSchema>,
1882    /// Shared module state (endpoint registries and the like), stashed
1883    /// at registration and reachable from bodies through
1884    /// `StepCtx::module_state`. Lets every entry stay `#[oxdock_func]`:
1885    /// the macro only generates closers-over-nothing, so state that
1886    /// cannot ride in a value travels here instead of a hand-built
1887    /// closure. Prefer `.with_state(...)` over spelling this field.
1888    pub states: Vec<ModuleState>,
1889}
1890
1891/// One shared state object traveling with its module. Keyed by the
1892/// owning module name plus the value type at registration, so two
1893/// modules sharing one state type never collide.
1894#[derive(Clone)]
1895pub struct ModuleState {
1896    id: std::any::TypeId,
1897    state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
1898}
1899
1900/// A pre-run steps inspection: pure function of the parsed steps,
1901///
1902/// shared so the struct field stays under the complexity lint.
1903pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
1904
1905/// A pre-run check riding in a module's `states`: the runner executes
1906/// every staged check against the parsed steps before the first step
1907/// runs, so unmapped services fail fast with zero side effects. Modules
1908/// attach one with `.with_state(Arc::new(check))`; the runner discovers
1909/// them by type, so no struct field or plugin knowledge is needed here.
1910#[derive(Clone)]
1911pub struct PreRunCheck {
1912    check: Arc<PreRunInspector>,
1913}
1914
1915impl PreRunCheck {
1916    /// Wrap a steps inspector as a pre-run check.
1917    pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
1918        Self {
1919            check: Arc::new(check),
1920        }
1921    }
1922
1923    /// Run the inspection: `Ok` lets execution start.
1924    pub fn run(&self, steps: &[Step]) -> Result<()> {
1925        (self.check)(steps)
1926    }
1927}
1928
1929impl<P: ProcessManager> HostModule<P> {
1930    /// Attach shared state for bodies to fetch with
1931    /// `cx.module_state::<T>("MODULE")`. Chainable, like registration.
1932    pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
1933        self.states.push(ModuleState {
1934            id: std::any::TypeId::of::<T>(),
1935            state,
1936        });
1937        self
1938    }
1939
1940    /// Run every staged [`PreRunCheck`] against already-parsed steps.
1941    /// The runner calls this before the first step executes; the first
1942    /// failing check aborts the run with no side effects.
1943    pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
1944        for state in &self.states {
1945            if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
1946                check.run(steps)?;
1947            }
1948        }
1949        Ok(())
1950    }
1951}
1952
1953impl<P: ProcessManager> ExecState<P> {
1954    /// Register one [`HostModule`]: every function becomes callable as
1955    /// `MODULE::NAME`, every type joins the run's name directory.
1956    pub fn register_module(&mut self, module: HostModule<P>) {
1957        for registration in module.funcs {
1958            match registration {
1959                HostRegistration::Stateful { name, meta, func } => {
1960                    self.functions.register_host(&module.name, name, meta, func);
1961                }
1962                HostRegistration::Pure { name, meta, func } => {
1963                    self.functions
1964                        .register_pure_host(&module.name, name, meta, func);
1965                }
1966            }
1967        }
1968        for descriptor in module.types {
1969            self.register_type(descriptor);
1970        }
1971        for schema in module.record_schemas {
1972            self.register_record_schema(schema.name, schema.fields);
1973        }
1974        for state in module.states {
1975            self.module_states
1976                .insert((module.name.clone(), state.id), state.state);
1977        }
1978    }
1979
1980    /// All visible functions: natives plus hosts plus current DSL definitions.
1981    pub fn list_functions(&self) -> Vec<FuncMeta> {
1982        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
1983        // TODO: Make a "virtual function" and don't hardcode
1984        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
1985            out.push(FuncMeta {
1986                name: KEYWORD_INSPECT.to_string(),
1987                module: STD_MODULE_NAME.to_string(),
1988                kind: FuncKind::HostCtx,
1989                params: None,
1990                returns: Some(TypeTag::Map),
1991                rpn: false,
1992                summary: "Inspect a variable binding.",
1993                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
1994                examples: &[],
1995            });
1996        }
1997        out.sort_by(|a, b| a.name.cmp(&b.name));
1998        out
1999    }
2000
2001    /// Describe one function by name, or `None` when unknown.
2002    pub fn describe_function(&self, name: &str) -> Option<Value> {
2003        if let Some(meta) = self.functions.meta(name) {
2004            return Some(meta_to_value(&meta));
2005        }
2006        // TODO: Make a "virtual function" and don't hardcode
2007        if name == KEYWORD_INSPECT {
2008            return Some(meta_to_value(&FuncMeta {
2009                name: KEYWORD_INSPECT.to_string(),
2010                module: STD_MODULE_NAME.to_string(),
2011                kind: FuncKind::HostCtx,
2012                params: None,
2013                returns: Some(TypeTag::Map),
2014                rpn: false,
2015                summary: "Inspect a variable binding.",
2016                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
2017                examples: &[],
2018            }));
2019        }
2020        None
2021    }
2022
2023    pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
2024        self.functions.clone_pure_fn(name)
2025    }
2026
2027    /// Shared snapshot of every registered pure function for
2028    /// placeholder and host driven expansion. Public so host crates
2029    /// resolve calls through the live registry instead of hardcoding
2030    /// module or function names. Cloning the `Arc` never copies the map.
2031    pub fn pure_function_table(&self) -> Arc<PureTable> {
2032        self.functions.pure_shared()
2033    }
2034
2035    pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
2036        self.functions.clone_ctx_fn(name)
2037    }
2038
2039    pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
2040        self.functions.meta(name)
2041    }
2042}
2043
2044#[cfg(test)]
2045mod tests {
2046    use super::*;
2047
2048    #[test]
2049    fn describe_entry_renders_union_spellings() {
2050        // Union params and returns render through the same structural
2051        // renderer every other tag uses: `DESCRIBE` (and the generated
2052        // reference built on it) names the admission set, never a
2053        // bare word or an empty string. Built by macro, so the
2054        // spelling cannot drift from the members.
2055        let union = oxdock_parser::union_tag!(String, Pipe);
2056        let meta = FuncMeta {
2057            name: "T::F".to_string(),
2058            module: "T".to_string(),
2059            kind: FuncKind::HostPure,
2060            params: Some(vec![FuncParam {
2061                name: "text".to_string(),
2062                param_type: Some(union.clone()),
2063                allowed: None,
2064                docs: "",
2065                options: None,
2066                optional: false,
2067            }]),
2068            returns: Some(union),
2069            rpn: false,
2070            summary: "test-only",
2071            docs: "test-only",
2072            examples: &[],
2073        };
2074        let value = meta_to_value(&meta);
2075        let map = value.as_map().expect("describe value is a map");
2076        let params = map
2077            .get("params")
2078            .expect("params key")
2079            .as_list()
2080            .expect("params is a list");
2081        let first = params[0].as_map().expect("entry is a map");
2082        assert_eq!(
2083            first.get("param_type").and_then(Value::as_str),
2084            Some("STRING|PIPE"),
2085            "param renders the set"
2086        );
2087        assert_eq!(
2088            map.get("returns").and_then(Value::as_str),
2089            Some("STRING|PIPE"),
2090            "returns render the set"
2091        );
2092    }
2093
2094    #[test]
2095    fn describe_entry_carries_optional_flag() {
2096        // The `optional` key on params entries is the machine-readable
2097        // half of the `?` rendering: pin both values through the same
2098        // builder the runtime serves, not through prose.
2099        let meta = FuncMeta {
2100            name: "T::F".to_string(),
2101            module: "T".to_string(),
2102            kind: FuncKind::HostPure,
2103            params: Some(vec![
2104                FuncParam {
2105                    name: "url".to_string(),
2106                    param_type: Some(TypeTag::String),
2107                    allowed: None,
2108                    docs: "",
2109                    options: None,
2110                    optional: false,
2111                },
2112                FuncParam {
2113                    name: "options".to_string(),
2114                    param_type: Some(TypeTag::Map),
2115                    allowed: None,
2116                    docs: "",
2117                    options: None,
2118                    optional: true,
2119                },
2120            ]),
2121            returns: Some(TypeTag::String),
2122            rpn: false,
2123            summary: "test-only",
2124            docs: "test-only",
2125            examples: &[],
2126        };
2127        let value = meta_to_value(&meta);
2128        let map = value.as_map().expect("describe value is a map");
2129        let params = map
2130            .get("params")
2131            .expect("params key")
2132            .as_list()
2133            .expect("params is a list");
2134        assert_eq!(params.len(), 2);
2135        let first = params[0].as_map().expect("entry is a map");
2136        let second = params[1].as_map().expect("entry is a map");
2137        assert_eq!(
2138            first.get("optional").and_then(Value::as_bool),
2139            Some(false),
2140            "required param must read false"
2141        );
2142        assert_eq!(
2143            second.get("optional").and_then(Value::as_bool),
2144            Some(true),
2145            "omittable param must read true"
2146        );
2147    }
2148}