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