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