Skip to main content

oxdock_core/exec/
native.rs

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