Skip to main content

oxdock_core/exec/
native.rs

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