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(
1231        bytes.iter().map(|b| format!("{b:02x}")).collect(),
1232    ))
1233}
1234
1235/// Current working directory as a workspace-absolute path.
1236///
1237/// Returns `STRING` because the result is already resolved: a `PATH`
1238/// value is workspace-relative text awaiting guard checks at use time,
1239/// while this directory is already checked and concrete, or absent
1240/// entirely under a pending snapshot. Compare or display it as text.
1241///
1242/// Reports the snapshot-pending sentinel when no concrete directory
1243/// exists yet, so snapshot scripts keep working unchanged.
1244///
1245#[oxdock_func(rpn, returns = TypeTag::String)]
1246#[example(
1247    name = "cwd",
1248    code = r###"
1249    IMPORT [STD]
1250    WORKDIR sub
1251    LET $c: STRING = CWD()
1252    ASSERT_CONTAINS $c "sub"
1253    "###
1254)]
1255fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1256    if cx.state.fs.is_snapshot_pending() {
1257        return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
1258    }
1259    let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
1260    let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
1261    Ok(Value::string(real))
1262}
1263
1264/// Parse TOML text already held in memory.
1265///
1266/// Uses the same conversion as file loading, so fetch bodies, file
1267/// contents, and captured text share one JSON/TOML shape.
1268///
1269#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1270#[example(
1271    name = "parse",
1272    code = r###"
1273    IMPORT [STD]
1274    LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
1275    ASSERT_EQ $doc.title "demo"
1276    "###
1277)]
1278fn parse_toml(
1279    /// TOML text already held in memory.
1280    text: String,
1281) -> Result<Value> {
1282    super::args::parse_toml_from_value(Value::string(text))
1283}
1284
1285/// Parse JSON text already held in memory.
1286///
1287/// Uses the same conversion as file loading, so fetch bodies, file
1288/// contents, and captured text share one JSON value shape. Returns
1289/// `ANY` by design, matching `LOAD_JSON`: a top-level array or scalar
1290/// parses to `LIST` or a scalar word. `LET` coercion still checks the
1291/// actual value at assignment.
1292///
1293#[oxdock_func(pure, returns = TypeTag::Any)]
1294#[example(
1295    name = "parse",
1296    code = r###"
1297    # Parse in-memory JSON text with the same conversion as file loading.
1298    IMPORT [STD]
1299    LET $body: STRING = "{\"a\": 1}"
1300    LET $doc: ANY = PARSE_JSON($body)
1301    ASSERT_EQ $doc.a 1
1302
1303    # Top-level arrays parse to LIST, which is why the return is ANY.
1304    LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
1305    ASSERT_EQ $items.0 1
1306    ASSERT_EQ $items.1 2
1307    "###
1308)]
1309fn parse_json(
1310    /// JSON text already held in memory.
1311    text: String,
1312) -> Result<Value> {
1313    super::args::parse_json_from_value(Value::string(text))
1314}
1315
1316/// Describe a filesystem entry.
1317///
1318/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
1319/// there is no RPN arm for filesystem IO.
1320///
1321#[oxdock_func(returns = TypeTag::String)]
1322#[example(
1323    name = "describe",
1324    code = r###"
1325    IMPORT [STD]
1326    WRITE "entry.txt" "words"
1327    LET $kind: STRING = PATH_TYPE("entry.txt")
1328    ASSERT_EQ $kind "file"
1329    LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
1330    ASSERT_EQ $missing "absent"
1331    "###
1332)]
1333fn path_type<P: ProcessManager>(
1334    cx: &mut StepCtx<P>,
1335    /// Workspace path of the entry to describe.
1336    #[union(String, Path)]
1337    path: Value,
1338) -> Result<Value> {
1339    let text = super::args::string_or_path_text(&path)?;
1340    super::args::path_type_from_value(&[Value::string(text)], cx)
1341}
1342
1343/// Report whether an ordinary file can be created at a path.
1344///
1345/// Walks up to the nearest existing ancestor, requires it be a
1346/// directory, and probes writability by creating and deleting a probe
1347/// file, so retry loops never litter. The empty string is false.
1348/// AST-only by design, like `PATH_TYPE`: there is no RPN arm for
1349/// filesystem IO.
1350///
1351#[oxdock_func(returns = TypeTag::Bool)]
1352#[example(
1353    name = "probe",
1354    code = r###"
1355    # An absent nested path is writable when its ancestor is.
1356    IMPORT [STD]
1357    LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
1358    ASSERT_EQ $fresh true
1359
1360    # The empty string never aliases the working directory.
1361    LET $empty: BOOL = PATH_WRITABLE("")
1362    ASSERT_EQ $empty false
1363    "###
1364)]
1365fn path_writable<P: ProcessManager>(
1366    cx: &mut StepCtx<P>,
1367    /// Workspace path to probe for file creation.
1368    #[union(String, Path)]
1369    path: Value,
1370) -> Result<Value> {
1371    let text = super::args::string_or_path_text(&path)?;
1372    super::args::path_writable_from_value(&[Value::string(text)], cx)
1373}
1374
1375/// Report whether a name resolves to an executable file (#100).
1376///
1377/// Bare command names search `env:PATH` (`IS_EXEC("tar")` finds the
1378/// first executable `tar`, plus `tar.exe`, on `PATH`); spellings
1379/// containing a separator check that file directly. True means a real
1380/// file with an executable bit on Unix, or a `PATHEXT` extension on
1381/// Windows: each `env:PATHEXT` entry is probed in order (unset or empty
1382/// probes nothing). Absolute `PATH` entries resolve through the workspace as
1383/// usual, so host probing wants `WORKSPACE SYSTEM` and an inherited
1384/// `PATH`; anything unresolvable reads false, never errors. AST-only
1385/// by design, like `PATH_TYPE`: there is no RPN arm for filesystem IO.
1386///
1387#[oxdock_func(returns = TypeTag::Bool)]
1388#[example(
1389    name = "probe",
1390    code = r###"
1391    # Missing tools read false instead of failing the run.
1392    IMPORT [STD]
1393    LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
1394    ASSERT_EQ $missing false
1395
1396    # Plain files are not executable on any platform.
1397    WRITE tool.txt payload
1398    LET $plain: BOOL = IS_EXEC("tool.txt")
1399    ASSERT_EQ $plain false
1400    "###
1401)]
1402fn is_exec<P: ProcessManager>(
1403    cx: &mut StepCtx<P>,
1404    /// Command name or file path to probe.
1405    #[union(String, Path)]
1406    name: Value,
1407) -> Result<Value> {
1408    let text = super::args::string_or_path_text(&name)?;
1409    super::args::is_exec_from_value(&[Value::string(text)], cx)
1410}
1411
1412/// Report whether a map holds a key.
1413///
1414/// Pure MAP probe so scripts can branch on optional fields without
1415/// tripping the strict missing-key error.
1416///
1417#[oxdock_func(pure, returns = TypeTag::Bool)]
1418#[example(
1419    name = "probe",
1420    code = r###"
1421    IMPORT [STD]
1422    LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
1423    LET $hit: BOOL = HAS_KEY($m, "a")
1424    ASSERT_EQ $hit true
1425    LET $miss: BOOL = HAS_KEY($m, "b")
1426    ASSERT_EQ $miss false
1427    "###
1428)]
1429fn has_key(
1430    /// Map to probe.
1431    map: BTreeMap<String, Value>,
1432    /// Key to look up.
1433    key: String,
1434) -> Result<Value> {
1435    super::args::has_key_from_value(Value::map(map), &key)
1436}
1437
1438/// Insert one key into a map.
1439///
1440/// Fails on duplicates so two entries sharing a key fail the run
1441/// instead of silently shadowing each other.
1442///
1443#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1444#[example(
1445    name = "insert",
1446    code = r###"
1447    IMPORT [STD]
1448    LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
1449    ASSERT_EQ $m.a 1
1450    "###
1451)]
1452fn map_set(
1453    /// Map to insert into.
1454    map: BTreeMap<String, Value>,
1455    /// Key to insert; duplicates fail.
1456    key: String,
1457    /// Value to store.
1458    value: Value,
1459) -> Result<Value> {
1460    super::args::map_set_from_value(Value::map(map), key, value)
1461}
1462
1463/// Draw a random FLOAT uniformly from [0, 1), optionally seeded.
1464///
1465/// Impure by design: unseeded calls return different values, so this
1466/// runs on the AST script path only, never as a `{{ }}` placeholder
1467/// call. A seed draws the same value on every run, for deterministic
1468/// fixtures. Scale and shift the draw for wider ranges.
1469///
1470#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
1471#[example(
1472    name = "seeded draw",
1473    code = r###"
1474    # A seed draws the same value on every run.
1475    IMPORT [STD]
1476    LET $one: FLOAT = RAND({seed: 7})
1477    LET $two: FLOAT = RAND({seed: 7})
1478    ASSERT_EQ $one $two
1479    "###
1480)]
1481#[example(
1482    name = "unseeded draw",
1483    code = r###"
1484    # Scale a unit draw into a backoff delay between 1 and 11 seconds.
1485    IMPORT [STD]
1486    LET $draw: FLOAT = RAND()
1487    LET $delay: FLOAT = 1.0 + $draw * 10.0
1488    IF $delay < 1.0 {
1489        EXIT 1
1490    }
1491    IF $delay >= 11.0 {
1492        EXIT 1
1493    }
1494    ECHO "retrying in {{ $delay }}s"
1495    "###
1496)]
1497fn rand<P: ProcessManager>(
1498    cx: &mut StepCtx<P>,
1499    /// Draw settings: `seed`. Omittable: a missing options MAP fills `{}`.
1500    #[options("seed?: INT")]
1501    #[optional]
1502    options: BTreeMap<String, Value>,
1503) -> Result<Value> {
1504    let _ = cx;
1505    // `check_options` in the wrapper verified the shape above; the
1506    // read below narrows infallibly after.
1507    let seed = options
1508        .get("seed")
1509        .map(|value| value.as_i64().expect("check_options verified INT"));
1510    super::args::rand_float_from_value(seed)
1511}
1512
1513/// Encode a STRING as standard base64.
1514///
1515/// Padded RFC 4648 alphabet, so encoded output pastes into any
1516/// standard decoder. Pairs with `BASE64_DECODE` for the round trip.
1517///
1518#[oxdock_func(pure, returns = TypeTag::String)]
1519#[example(
1520    name = "encode",
1521    code = r###"
1522    # Encode text to standard base64.
1523    IMPORT [STD]
1524    LET $encoded: STRING = BASE64_ENCODE("hello")
1525    ASSERT_EQ $encoded "aGVsbG8="
1526    "###
1527)]
1528fn base64_encode(
1529    /// Text to encode.
1530    text: String,
1531) -> Result<Value> {
1532    super::args::base64_encode_from_value(Value::string(text))
1533}
1534
1535/// Decode standard base64 to a STRING.
1536///
1537/// Fails naming the input on invalid alphabet characters or
1538/// non-UTF-8 payloads instead of rendering a silent empty. Pairs
1539/// with `BASE64_ENCODE` for the round trip.
1540///
1541#[oxdock_func(pure, returns = TypeTag::String)]
1542#[example(
1543    name = "decode",
1544    code = r###"
1545    # Decode standard base64 back to text.
1546    IMPORT [STD]
1547    LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
1548    ASSERT_EQ $decoded "hello"
1549    "###
1550)]
1551fn base64_decode(
1552    /// Base64 text to decode.
1553    text: String,
1554) -> Result<Value> {
1555    super::args::base64_decode_from_value(Value::string(text))
1556}
1557
1558/// Encode a script value as JSON with one trailing newline.
1559///
1560/// Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT,
1561/// BOOL, LIST, MAP) survive, anything else fails here instead of
1562/// rendering as a silent empty.
1563///
1564#[oxdock_func(pure, returns = TypeTag::String)]
1565#[example(
1566    name = "encode",
1567    code = r###"
1568    IMPORT [STD]
1569    LET $json: STRING = TO_JSON({a: 1})
1570    ASSERT_EQ $json "{\"a\":1}\n"
1571    "###
1572)]
1573fn to_json(
1574    /// Value to encode as JSON.
1575    #[union(String, Int, Float, Bool, List, Map)]
1576    value: Value,
1577) -> Result<Value> {
1578    super::args::to_json_from_value(value)
1579}
1580
1581/// Name the word a value holds, for data-driven branching.
1582///
1583/// Returns the registered type word (`STRING`, `INT`, `FLOAT`, `BOOL`,
1584/// `LIST`, `MAP`, plus handle words like `PIPE`): the same name the
1585/// value prints in arity and coercion errors, so scripts can branch
1586/// on config shapes (a path string or a path list) without failing.
1587///
1588#[oxdock_func(pure, returns = TypeTag::String)]
1589#[example(
1590    name = "name the word",
1591    code = r###"
1592    IMPORT [STD]
1593    LET $word: STRING = TYPE_OF(42)
1594    ASSERT_EQ $word "INT"
1595    "###
1596)]
1597fn type_of(
1598    /// Value whose word to name.
1599    value: Value,
1600) -> Result<Value> {
1601    super::args::type_of_from_value(value)
1602}
1603
1604/// Merge a LIST of MAPs in order under one duplicate policy.
1605///
1606/// `fail_on_duplicate` fails naming the repeated key, so two files
1607/// claiming one placeholder fail the run instead of shadowing each
1608/// other. `overwrite` lets later files win, for environment overlays.
1609/// Non MAP elements fail naming their position.
1610///
1611#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
1612#[example(
1613    name = "merge",
1614    code = r###"
1615    IMPORT [STD]
1616    LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
1617    ASSERT_EQ $m.a 1
1618    ASSERT_EQ $m.b 2
1619    "###
1620)]
1621fn merge_maps(
1622    /// LIST of MAPs to merge in order.
1623    maps: Vec<BTreeMap<String, Value>>,
1624    /// Duplicate policy.
1625    #[values("fail_on_duplicate", "overwrite")]
1626    policy: String,
1627) -> Result<Value> {
1628    super::args::merge_maps_from_value(
1629        Value::list(maps.into_iter().map(Value::map).collect()),
1630        policy,
1631    )
1632}
1633
1634/// Report the running engine version.
1635///
1636/// Returns the workspace version baked in at compile time, so scripts
1637/// and agents can branch on engine behavior instead of probing it.
1638#[oxdock_func(pure, returns = TypeTag::String)]
1639#[example(
1640    name = "report",
1641    code = r###"
1642    # The engine reports its own build version as a dotted string.
1643    IMPORT [STD]
1644    LET $v: STRING = VERSION()
1645    ASSERT_CONTAINS $v "."
1646    "###
1647)]
1648fn version() -> Result<Value> {
1649    Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
1650}
1651
1652/// List all visible function names.
1653///
1654/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
1655/// plus host-registered names.
1656#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1657#[example(
1658    name = "list",
1659    code = r###"
1660    IMPORT [STD]
1661    LET $names: LIST<STRING> = FUNCTIONS()
1662    ASSERT_CONTAINS $names "STD::INT"
1663    "###
1664)]
1665fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1666    let mut names: Vec<String> = cx
1667        .state
1668        .list_functions()
1669        .into_iter()
1670        .map(|meta| meta.name)
1671        .collect();
1672    names.sort();
1673    names.dedup();
1674    Ok(Value::list(names.into_iter().map(Value::string).collect()))
1675}
1676
1677/// Describe one function by qualified name.
1678///
1679/// Returns a MAP with name, module, kind, params, returns, rpn, and
1680/// summary. `params` is always a LIST (empty for parameterless
1681/// functions) of entries carrying name, param_type, allowed, docs,
1682/// options, and optional flags, so the shape holds for every entry. Bare names
1683/// fail closed: `DESCRIBE` requires the qualified form (except
1684/// `INSPECT`, which is syntax rather than a registry entry). Errors
1685/// on unknown function.
1686///
1687/// Field table for the `DESCRIBE` result bundle: one source for the
1688/// shape the host mints, so introspection, enforcement, and
1689/// documentation cannot drift apart.
1690
1691#[oxdock_func(
1692    returns = TypeTag::Record(std::sync::Arc::from([Field {
1693        name: "name".to_string(),
1694        ty: TypeTag::String,
1695        docs: "Qualified function name.",
1696        optional: false,
1697    }, Field {
1698        name: "module".to_string(),
1699        ty: TypeTag::String,
1700        docs: "Owning module.",
1701        optional: false,
1702    }, Field {
1703        name: "kind".to_string(),
1704        ty: TypeTag::String,
1705        docs: "Origin label (`host` or `script`).",
1706        optional: false,
1707    }, Field {
1708        name: "params".to_string(),
1709        ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
1710            TypeTag::Any,
1711        )))),
1712        docs: "Parameter entries (empty for parameterless functions).",
1713        optional: false,
1714    }, Field {
1715        name: "returns".to_string(),
1716        ty: TypeTag::String,
1717        docs: "Structural return shape (empty when untagged).",
1718        optional: false,
1719    }, Field {
1720        name: "rpn".to_string(),
1721        ty: TypeTag::Bool,
1722        docs: "True when callable in RPN position.",
1723        optional: false,
1724    }, Field {
1725        name: "summary".to_string(),
1726        ty: TypeTag::String,
1727        docs: "One-line description.",
1728        optional: false,
1729    }]))
1730    summary = "Describe one function by qualified name."
1731)]
1732#[example(
1733    name = "describe",
1734    code = r###"
1735    IMPORT [STD]
1736    LET $info: MAP<ANY> = DESCRIBE("STD::INT")
1737    ASSERT_EQ $info.name "STD::INT"
1738    ASSERT_EQ $info.returns "INT"
1739    "###
1740)]
1741fn describe<P: ProcessManager>(
1742    cx: &mut StepCtx<P>,
1743    /// Qualified function name (`MODULE::NAME`).
1744    name: String,
1745) -> Result<Value> {
1746    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
1747        anyhow::bail!(
1748            "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
1749        );
1750    }
1751    cx.state
1752        .describe_function(&name)
1753        .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
1754}
1755
1756/// List all known type names.
1757///
1758/// Sorted LIST of startup plus host-registered type descriptors. Reads the
1759/// run's name directory, so it runs on the AST path like the other
1760/// introspection functions.
1761#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
1762#[example(
1763    name = "list",
1764    code = r###"
1765    IMPORT [STD]
1766    LET $names: LIST<STRING> = TYPES()
1767    ASSERT_CONTAINS $names "STRING"
1768    "###
1769)]
1770fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1771    Ok(Value::list(
1772        cx.state
1773            .type_names()
1774            .into_iter()
1775            .map(Value::string)
1776            .collect(),
1777    ))
1778}
1779
1780/// Describe one type by name.
1781///
1782/// Returns a MAP with name, summary, and docs. Errors on unknown type.
1783/// Reads the run's name directory, so it runs on the AST path.
1784///
1785#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
1786    name: "name".to_string(),
1787    ty: TypeTag::String,
1788    docs: "Queried type name.",
1789    optional: false,
1790}, Field {
1791    name: "summary".to_string(),
1792    ty: TypeTag::String,
1793    docs: "One-line description.",
1794    optional: false,
1795}, Field {
1796    name: "docs".to_string(),
1797    ty: TypeTag::String,
1798    docs: "Full documentation text.",
1799    optional: false,
1800}])))]
1801#[example(
1802    name = "describe",
1803    code = r###"
1804    IMPORT [STD]
1805    LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
1806    ASSERT_EQ $info.name "STRING"
1807    "###
1808)]
1809fn type_describe<P: ProcessManager>(
1810    cx: &mut StepCtx<P>,
1811    /// Type name to describe.
1812    name: String,
1813) -> Result<Value> {
1814    if let Some(descriptor) = cx.state.describe_type(&name) {
1815        let mut map = BTreeMap::new();
1816        map.insert(
1817            "name".to_string(),
1818            Value::string(descriptor.name.to_string()),
1819        );
1820        map.insert(
1821            "summary".to_string(),
1822            Value::string(descriptor.summary.to_string()),
1823        );
1824        map.insert(
1825            "docs".to_string(),
1826            Value::string(descriptor.docs.to_string()),
1827        );
1828        return Ok(Value::map(map));
1829    }
1830    // Script aliases have no descriptor but introspect the same way:
1831    // the entry names the alias and its canonical target spelling.
1832    if let Some(target) = cx.state.alias_target(&name) {
1833        let mut map = BTreeMap::new();
1834        map.insert("name".to_string(), Value::string(name.clone()));
1835        map.insert(
1836            "summary".to_string(),
1837            Value::string(format!("Script type alias for {target}.")),
1838        );
1839        map.insert(
1840            "docs".to_string(),
1841            Value::string(format!(
1842                "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
1843            )),
1844        );
1845        return Ok(Value::map(map));
1846    }
1847    Err(anyhow::anyhow!("unknown type {name}"))
1848}
1849
1850/// Path of the running interpreter binary.
1851///
1852/// Returns the executing binary as a `STRING`, so one script can
1853/// reinvoke the interpreter on another script without bridging an env
1854/// var. The child re-parses from bytes in a separate process: no
1855/// bindings cross back (only stdout and files), and each run pays
1856/// a spawn. Prefer modules for reuse (statically gated, in-process);
1857/// reach for reinvocation when the child must run isolated, or under
1858/// a different binary than the parent.
1859///
1860/// Unsupported under Miri isolation: the lookup itself fails there
1861/// instead of returning a path.
1862///
1863#[oxdock_func(returns = TypeTag::String)]
1864#[example(
1865    name = "self",
1866    code = r###"
1867    # The running interpreter resolves to a non-empty path.
1868    IMPORT [STD]
1869    LET $exe: STRING = INTERPRETER()
1870    LET $nonempty: BOOL = $exe != ""
1871    ASSERT_EQ $nonempty true
1872    "###
1873)]
1874#[example(
1875    name = "dynamic composition",
1876    code = r###"
1877    # Compose the child script dynamically: the parent interpolates
1878    # its own bindings into the pipe, then runs the interpreter on it.
1879    # Unescaped {{ }} bakes in at compose time; \{{ }} stays literal
1880    # so the child expands it with its own bindings.
1881    # The pipe delivers EOF when the producer step ends, so the child
1882    # reads exactly one script.
1883    IMPORT [STD]
1884    LET $exe: STRING = INTERPRETER()
1885    LET $who: STRING = "Ada"
1886    LET $child: PIPE
1887    WITH_IO [stdout=$child] ECHO """
1888        ECHO "hello {{ $who }}!"
1889        LET $who: STRING = "Grace"
1890        ECHO "child sees \{{ $who }}!"
1891        """
1892    LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
1893    ASSERT_CONTAINS $out "hello Ada!"
1894    ASSERT_CONTAINS $out "child sees Grace!"
1895    "###
1896)]
1897fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1898    if let Some(staged) = cx.state.io.interpreter_override() {
1899        return Ok(Value::string(staged));
1900    }
1901    Ok(Value::string(oxdock_process::interpreter_exe()?))
1902}
1903
1904/// Report whether the current context is the entry script.
1905///
1906/// True at entry top level and inside entry-owned functions; false
1907/// inside module-owned functions and module init bodies. Lets a
1908/// library file double as a runnable demo: guard the demo with
1909/// `IF IS_MAIN()` so importing it stays side-effect free.
1910///
1911#[oxdock_func(returns = TypeTag::Bool)]
1912#[example(
1913    name = "main",
1914    code = r###"
1915    # Entry top level runs as main.
1916    IMPORT [STD]
1917    LET $m: BOOL = IS_MAIN()
1918    ASSERT_EQ $m true
1919    "###
1920)]
1921#[example(
1922    name = "library doubles as demo",
1923    fence_meta = "roots:unified",
1924    code = r###"
1925    # A library doubles as a runnable demo: guard the demo with
1926    # IF IS_MAIN() so importing it stays side effect free. The
1927    # parent writes both files, then runs each in a fresh
1928    # interpreter: direct execution prints the demo, importing
1929    # it does not. Unified roots: the child inherits one
1930    # workspace, so parent and child see the same files. The
1931    # exact stdout match proves the demo line stays out of the
1932    # importing run.
1933    IMPORT [STD]
1934
1935    # The library under test: demo guarded by IS_MAIN.
1936    WRITE lib.oxfile """
1937        IMPORT [STD]
1938        FUNC GREET($x: STRING) { RETURN "hi \{{ $x }}" }
1939        EXPORT GREET
1940        IF IS_MAIN() {
1941            ECHO "demo: hi Ada"
1942        }
1943        """
1944
1945    # The importer: calls the library, prints only its own line.
1946    WRITE main.oxfile """
1947        IMPORT ["lib.oxfile" AS LIB]
1948        LET $g: STRING = LIB::GREET("Bo")
1949        ECHO "imported: \{{ $g }}"
1950        """
1951
1952    # Direct run executes the demo.
1953    LET $exe: STRING = INTERPRETER()
1954    LET $direct: STRING = RUN [$exe, "lib.oxfile"]
1955    ASSERT_CONTAINS $direct "demo: hi Ada"
1956
1957    # Importing run stays silent apart from its own line.
1958    LET $via: STRING = RUN [$exe, "main.oxfile"]
1959    ASSERT_EQ $via "imported: hi Bo\n"
1960    "###
1961)]
1962fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
1963    let main = match cx.state.module_stack.last() {
1964        None | Some(None) => true,
1965        Some(Some(_)) => false,
1966    };
1967    Ok(Value::bool(main))
1968}
1969
1970/// Report whether a standard stream is a terminal.
1971///
1972/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
1973/// answers for the step's stream as currently bound, so scripts can adapt
1974/// prompts, colors, and progress output. Anything diverted from the
1975/// terminal reports false without touching host handles: `WITH_IO` pipe
1976/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
1977/// runner sinks, and any materialized stdin stream (only a directly
1978/// inherited fd falls back to the process check). A transparent root tee
1979/// still answers the session question via the process check. The name
1980/// matches exactly (no case folding): anything else bails. AST-only:
1981/// reads the step context like the other introspection functions.
1982///
1983#[oxdock_func(returns = TypeTag::Bool)]
1984#[example(
1985    name = "null stdin",
1986    code = r###"
1987    # A null stdin is never a terminal, in every harness.
1988    IMPORT [STD]
1989    LET $term: BOOL = IS_TERMINAL("stdin")
1990    ASSERT_EQ $term false
1991    "###
1992)]
1993fn is_terminal<P: ProcessManager>(
1994    cx: &mut StepCtx<P>,
1995    /// Stream name: `stdin`, `stdout`, or `stderr` (exact match).
1996    #[values("stdin", "stdout", "stderr")]
1997    stream_name: String,
1998) -> Result<Value> {
1999    use std::io::IsTerminal;
2000    let terminal = match stream_name.as_str() {
2001        "stdin" => {
2002            // A script-pipe backend is definitive; Null is /dev/null.
2003            // Only a directly inherited fd answers the process check: a
2004            // materialized Stream is always a binding (staged input,
2005            // WITH_IO pipe, or OS half), never the raw fd.
2006            if cx.stdin_pipe.is_some() {
2007                false
2008            } else {
2009                match &cx.stdin {
2010                    CommandStdin::Null => false,
2011                    #[cfg(not(miri))]
2012                    CommandStdin::OsPipe(_) => false,
2013                    CommandStdin::Stream(_) => false,
2014                    CommandStdin::Inherit => std::io::stdin().is_terminal(),
2015                }
2016            }
2017        }
2018        "stdout" => {
2019            if cx.out_pipe.is_some() {
2020                // WITH_IO script-pipe binding: never a terminal.
2021                false
2022            } else if cx.state.io.stdout().is_some() {
2023                // Staged runner sink: the root tee diverts bytes to the
2024                // sink only, never to real stdout.
2025                false
2026            } else {
2027                match &cx.out {
2028                    // Unbound: inherited straight through.
2029                    None => std::io::stdout().is_terminal(),
2030                    // OS kernel pipe: never a terminal.
2031                    #[cfg(not(miri))]
2032                    Some(StreamHandle::Os(_)) => false,
2033                    // Root tee (transparent: forwards to real stdout when
2034                    // unstaged, so terminal-ness survives) versus a genuine
2035                    // diversion. WITH_IO bindings never reach here (script
2036                    // pipes trip out_pipe, OS pipes trip Os, staged sinks
2037                    // trip above). LET-capture cannot reach here either:
2038                    // assign_capture installs no sink for a bare NAME(...)
2039                    // call, so a direct query always observes the ambient
2040                    // routing. The process check answers the session
2041                    // question.
2042                    Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
2043                }
2044            }
2045        }
2046        "stderr" => {
2047            if cx.state.io.stderr().is_some() {
2048                // Staged runner sink: diverted, never a terminal.
2049                false
2050            } else {
2051                match &cx.err {
2052                    // Unbound: inherited straight through.
2053                    None => std::io::stderr().is_terminal(),
2054                    // OS kernel pipe: never a terminal.
2055                    #[cfg(not(miri))]
2056                    Some(StreamHandle::Os(_)) => false,
2057                    // Root never tees stderr and LET never captures it,
2058                    // so a bound handle here is always a WITH_IO binding.
2059                    Some(StreamHandle::Stream(_)) => false,
2060                }
2061            }
2062        }
2063        _ => anyhow::bail!(
2064            // Unreachable through the macro path: the generated
2065            // extractor rejects non-members before the body runs, and
2066            // the static pre-pass rejects bad literals earlier still.
2067            // Kept as a bail (never a panic) for hand-built callers.
2068            "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
2069        ),
2070    };
2071    Ok(Value::bool(terminal))
2072}
2073
2074/// Create a counting semaphore admitting at most `max` concurrent holders.
2075///
2076/// Non-positive maxima bail. The word names a shared backend: every clone
2077/// observes the same count, and admission runs through
2078/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
2079/// readout.
2080///
2081#[oxdock_func(returns = TypeTag::Semaphore)]
2082#[example(
2083    name = "mint",
2084    code = r###"
2085    # Mint a semaphore admitting at most two holders.
2086    IMPORT [STD]
2087    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2088
2089    # A fresh semaphore reports its full cap as available.
2090    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2091    ASSERT_EQ $free 2
2092    "###
2093)]
2094fn semaphore_new<P: ProcessManager>(
2095    cx: &mut StepCtx<P>,
2096    /// Maximum concurrent holders; must be positive.
2097    max: i64,
2098) -> Result<Value> {
2099    let _ = cx;
2100    if max <= 0 {
2101        return Err(anyhow::anyhow!(
2102            "SEMAPHORE_NEW() requires a positive max, got {max}"
2103        ));
2104    }
2105    Ok(Value::semaphore(max as usize))
2106}
2107
2108/// Attempt one non-blocking acquire, always answering a MAP.
2109///
2110/// `held` is `true` with the permit under the `permit` key, or `false`
2111/// with no `permit` key: branch on `$m.held` directly. The DSL has no
2112/// null, so the absent key is the miss shape. Do not read `$m.permit`
2113/// unless `held`: missing-key access bails strictly.
2114/// Never waits, so no wait can wedge.
2115///
2116#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
2117    name: "held".to_string(),
2118    ty: TypeTag::Bool,
2119    docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
2120    optional: false,
2121}, Field {
2122    name: "permit".to_string(),
2123    ty: TypeTag::Permit,
2124    docs: "Permit handle; read only when `held`.",
2125    optional: true,
2126}])))]
2127#[example(
2128    name = "acquire",
2129    code = r###"
2130    # First acquire holds with a permit to bind.
2131    IMPORT [STD]
2132    LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
2133    LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2134    ASSERT_EQ $first.held true
2135    LET $permit: PERMIT = $first.permit
2136
2137    # A capped semaphore answers held false with no permit key.
2138    LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2139    ASSERT_EQ $second.held false
2140    LET $has_permit: BOOL = HAS_KEY($second, "permit")
2141    ASSERT_EQ $has_permit false
2142    "###
2143)]
2144fn semaphore_try_acquire<P: ProcessManager>(
2145    cx: &mut StepCtx<P>,
2146    /// Semaphore handle from `SEMAPHORE_NEW`.
2147    sem: Arc<SemaphoreState>,
2148) -> Result<Value> {
2149    let _ = cx;
2150    let mut map = BTreeMap::new();
2151    if sem.try_acquire() {
2152        map.insert("held".to_string(), Value::bool(true));
2153        map.insert("permit".to_string(), Value::permit(&sem));
2154    } else {
2155        map.insert("held".to_string(), Value::bool(false));
2156    }
2157    Ok(Value::map(map))
2158}
2159
2160/// Read free permits under the lock, with no mutation.
2161///
2162/// Observability only (audit lines, healthchecks: `active = max - free`).
2163/// Exact at read time and stale the instant the caller acts on it, so it
2164/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
2165///
2166#[oxdock_func(pure, returns = TypeTag::Int)]
2167#[example(
2168    name = "readout",
2169    code = r###"
2170    # Hold one permit on a cap of two.
2171    IMPORT [STD]
2172    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
2173    LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
2174    ASSERT_EQ $acq.held true
2175
2176    # One held permit leaves exactly one free.
2177    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
2178    ASSERT_EQ $free 1
2179    "###
2180)]
2181fn semaphore_available(
2182    /// Semaphore handle from `SEMAPHORE_NEW`.
2183    sem: Arc<SemaphoreState>,
2184) -> Result<Value> {
2185    Ok(Value::int(sem.available() as i64))
2186}
2187
2188/// Trim Unicode whitespace from both ends of text.
2189///
2190/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
2191/// Pipes stream on a pump thread with O(chunk) memory: leading
2192/// whitespace falls at the stream head while trailing whitespace
2193/// holds in the spill substrate until the next segment proves it
2194/// interior, so unbounded streams never buffer unbounded memory.
2195///
2196#[oxdock_func(
2197    rpn,
2198    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2199    template = text_trim_string
2200)]
2201#[example(
2202    name = "trim",
2203    code = r###"
2204    # Leading and trailing whitespace falls away.
2205    IMPORT [STD]
2206    LET $clean: STRING = TEXT_TRIM("  hello  ")
2207    ASSERT_EQ $clean "hello"
2208    "###
2209)]
2210#[example(
2211    name = "trim pipe mirrors",
2212    code = r###"
2213    # Pipe input mints pipe output with the same transform.
2214    IMPORT [STD]
2215    LET $cap: PIPE
2216    WITH_IO [stdout=$cap] {
2217        ECHO "  hello  "
2218    }
2219    LET $out: PIPE = TEXT_TRIM($cap)
2220    WITH_IO [stdin=$out] READ_LINE $line
2221    ASSERT_EQ $line "hello"
2222    "###
2223)]
2224#[example(
2225    name = "trim template",
2226    code = r###"
2227    # String inputs run inside placeholders too.
2228    IMPORT [STD]
2229    LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM("  hello  ") }}'
2230    ASSERT_EQ $msg "clean:hello"
2231    "###
2232)]
2233#[example(
2234    name = "trim file template",
2235    code = r###"
2236    # EXPAND templates resolve the same registry.
2237    IMPORT [STD]
2238    WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\"  hello  \") }}"
2239    LET $out: STRING = EXPAND "tpl.txt"
2240    ASSERT_EQ $out "clean:hello"
2241    "###
2242)]
2243fn text_trim<P: ProcessManager>(
2244    cx: &mut StepCtx<P>,
2245    /// Text to trim.
2246    #[union(String, Pipe)]
2247    text: Value,
2248) -> Result<Value> {
2249    super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
2250}
2251
2252/// Template projection of `TEXT_TRIM`: the same trim for `{{ }}`
2253/// placeholders, which carry no step IO for pipes.
2254fn text_trim_string(text: Value) -> Result<Value> {
2255    super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
2256}
2257
2258/// Strip one leading prefix, returning the input unchanged when absent.
2259///
2260/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
2261/// Pipes decide on the first `prefix.len()` bytes and stream the rest
2262/// untouched. Matching is case-sensitive; there is no
2263/// case-insensitive mode.
2264/// Used for tag prefix strips such as `v1.2.3` to `1.2.3`.
2265///
2266#[oxdock_func(
2267    rpn,
2268    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2269    template = text_trim_prefix_string
2270)]
2271#[example(
2272    name = "strip prefix",
2273    code = r###"
2274    # A present prefix falls away; absence returns the input unchanged.
2275    IMPORT [STD]
2276    LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
2277    ASSERT_EQ $bare "1.2.3"
2278
2279    # Missing prefixes pass through untouched.
2280    LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
2281    ASSERT_EQ $same "1.2.3"
2282    "###
2283)]
2284#[example(
2285    name = "strip prefix pipe mirrors",
2286    code = r###"
2287    # Pipe input mints pipe output with the same strip.
2288    IMPORT [STD]
2289    LET $cap: PIPE
2290    WITH_IO [stdout=$cap] {
2291        ECHO "v1.2.3"
2292    }
2293    LET $trimmed: PIPE = TEXT_TRIM($cap)
2294    LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
2295    WITH_IO [stdin=$out] READ_LINE $line
2296    ASSERT_EQ $line "1.2.3"
2297    "###
2298)]
2299#[example(
2300    name = "strip prefix template",
2301    code = r###"
2302    # String inputs run inside placeholders too.
2303    IMPORT [STD]
2304    LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
2305    ASSERT_EQ $msg "bare:1.2.3"
2306    "###
2307)]
2308fn text_trim_prefix<P: ProcessManager>(
2309    cx: &mut StepCtx<P>,
2310    /// Text to strip.
2311    #[union(String, Pipe)]
2312    text: Value,
2313    /// Leading prefix to remove once.
2314    prefix: String,
2315) -> Result<Value> {
2316    super::args::mirror_stream(
2317        cx,
2318        "TEXT_TRIM_PREFIX",
2319        &text,
2320        super::args::TextPump::TrimPrefix(prefix),
2321    )
2322}
2323
2324/// Template projection of `TEXT_TRIM_PREFIX`: the same strip for
2325/// `{{ }}` placeholders, which carry no step IO for pipes.
2326fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
2327    super::args::mirror_string(
2328        "TEXT_TRIM_PREFIX",
2329        &text,
2330        super::args::TextPump::TrimPrefix(prefix),
2331    )
2332}
2333
2334/// Strip one trailing suffix, returning the input unchanged when absent.
2335///
2336/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
2337/// Pipes hold a `suffix.len()` trailing window and stream the rest.
2338/// Matching is case-sensitive; there is no case-insensitive mode.
2339///
2340#[oxdock_func(
2341    rpn,
2342    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2343    template = text_trim_suffix_string
2344)]
2345#[example(
2346    name = "strip suffix",
2347    code = r###"
2348    # A present suffix falls away; absence returns the input unchanged.
2349    IMPORT [STD]
2350    LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
2351    ASSERT_EQ $bare "archive.tar"
2352
2353    # Missing suffixes pass through untouched.
2354    LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
2355    ASSERT_EQ $same "archive.tar"
2356    "###
2357)]
2358#[example(
2359    name = "strip suffix pipe mirrors",
2360    code = r###"
2361    # Pipe input mints pipe output with the same strip.
2362    IMPORT [STD]
2363    LET $cap: PIPE
2364    WITH_IO [stdout=$cap] {
2365        ECHO "archive.tar.gz"
2366    }
2367    LET $trimmed: PIPE = TEXT_TRIM($cap)
2368    LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
2369    WITH_IO [stdin=$out] READ_LINE $line
2370    ASSERT_EQ $line "archive.tar"
2371    "###
2372)]
2373#[example(
2374    name = "strip suffix template",
2375    code = r###"
2376    # String inputs run inside placeholders too.
2377    IMPORT [STD]
2378    LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
2379    ASSERT_EQ $msg "bare:archive.tar"
2380    "###
2381)]
2382fn text_trim_suffix<P: ProcessManager>(
2383    cx: &mut StepCtx<P>,
2384    /// Text to strip.
2385    #[union(String, Pipe)]
2386    text: Value,
2387    /// Trailing suffix to remove once.
2388    suffix: String,
2389) -> Result<Value> {
2390    super::args::mirror_stream(
2391        cx,
2392        "TEXT_TRIM_SUFFIX",
2393        &text,
2394        super::args::TextPump::TrimSuffix(suffix),
2395    )
2396}
2397
2398/// Template projection of `TEXT_TRIM_SUFFIX`: the same strip for
2399/// `{{ }}` placeholders, which carry no step IO for pipes.
2400fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
2401    super::args::mirror_string(
2402        "TEXT_TRIM_SUFFIX",
2403        &text,
2404        super::args::TextPump::TrimSuffix(suffix),
2405    )
2406}
2407
2408/// Join a directory and a file name with the host-native separator.
2409///
2410/// Both inputs accept `STRING` or workspace `PATH` words; the result
2411/// is a `STRING` joined with the platform separator, so installers
2412/// never hand-roll separators in templates. No filesystem access:
2413/// missing parents fail later at the consumer. Stays `STRING` (not
2414/// `PATH`) on purpose: the joined value is a not-yet-validated
2415/// destination string like `$dir` itself, and `PATH` words
2416/// re-canonicalize to forward slashes on template expansion, which
2417/// would undo the native join.
2418#[oxdock_func(returns = TypeTag::String)]
2419#[example(
2420    name = "join path",
2421    code = r###"
2422    # Directory and file stem join with the native separator.
2423    # Source `\\` is one backslash at runtime; `/` works on Windows
2424    # too, native just reads better there.
2425    IMPORT [STD]
2426    LET $p: STRING = PATH_JOIN("some-dir", "some-file")
2427    [family:unix] ASSERT_EQ $p "some-dir/some-file"
2428    [family:windows] ASSERT_EQ $p "some-dir\\some-file"
2429    "###
2430)]
2431fn path_join<P: ProcessManager>(
2432    _cx: &mut StepCtx<P>,
2433    /// Directory half of the destination.
2434    #[union(String, Path)]
2435    dir: Value,
2436    /// File half of the destination.
2437    #[union(String, Path)]
2438    name: Value,
2439) -> Result<Value> {
2440    let d = super::args::string_or_path_text(&dir)?;
2441    let n = super::args::string_or_path_text(&name)?;
2442    Ok(Value::string(oxdock_fs::join_native(&d, &n)))
2443}
2444
2445/// Uppercase text with full Unicode mapping.
2446///
2447/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
2448/// Pipes map chunk by chunk across a char-boundary carry, so
2449/// multibyte characters split across reads still fold correctly.
2450///
2451#[oxdock_func(
2452    rpn,
2453    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2454    template = text_to_upper_string
2455)]
2456#[example(
2457    name = "uppercase",
2458    code = r###"
2459    # Text folds to uppercase.
2460    IMPORT [STD]
2461    LET $loud: STRING = TEXT_TO_UPPER("hello")
2462    ASSERT_EQ $loud "HELLO"
2463    "###
2464)]
2465#[example(
2466    name = "uppercase pipe mirrors",
2467    code = r###"
2468    # Pipe input mints pipe output with the same fold.
2469    IMPORT [STD]
2470    LET $cap: PIPE
2471    WITH_IO [stdout=$cap] {
2472        ECHO "hello"
2473    }
2474    LET $out: PIPE = TEXT_TO_UPPER($cap)
2475    WITH_IO [stdin=$out] READ_LINE $line
2476    ASSERT_EQ $line "HELLO"
2477    "###
2478)]
2479#[example(
2480    name = "uppercase template",
2481    code = r###"
2482    # String inputs run inside placeholders too.
2483    IMPORT [STD]
2484    LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
2485    ASSERT_EQ $msg "loud:HELLO"
2486    "###
2487)]
2488fn text_to_upper<P: ProcessManager>(
2489    cx: &mut StepCtx<P>,
2490    /// Text to uppercase.
2491    #[union(String, Pipe)]
2492    text: Value,
2493) -> Result<Value> {
2494    super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2495}
2496
2497/// Template projection of `TEXT_TO_UPPER`: the same fold for `{{ }}`
2498/// placeholders, which carry no step IO for pipes.
2499fn text_to_upper_string(text: Value) -> Result<Value> {
2500    super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
2501}
2502
2503/// Lowercase text with full Unicode mapping.
2504///
2505/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
2506/// Pipes map chunk by chunk across a char-boundary carry, like
2507/// `TEXT_TO_UPPER`.
2508///
2509#[oxdock_func(
2510    rpn,
2511    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2512    template = text_to_lower_string
2513)]
2514#[example(
2515    name = "lowercase",
2516    code = r###"
2517    # Text folds to lowercase.
2518    IMPORT [STD]
2519    LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
2520    ASSERT_EQ $quiet "hello"
2521    "###
2522)]
2523#[example(
2524    name = "lowercase pipe mirrors",
2525    code = r###"
2526    # Pipe input mints pipe output with the same fold.
2527    IMPORT [STD]
2528    LET $cap: PIPE
2529    WITH_IO [stdout=$cap] {
2530        ECHO "HELLO"
2531    }
2532    LET $out: PIPE = TEXT_TO_LOWER($cap)
2533    WITH_IO [stdin=$out] READ_LINE $line
2534    ASSERT_EQ $line "hello"
2535    "###
2536)]
2537#[example(
2538    name = "lowercase template",
2539    code = r###"
2540    # String inputs run inside placeholders too.
2541    IMPORT [STD]
2542    LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
2543    ASSERT_EQ $msg "quiet:hello"
2544    "###
2545)]
2546fn text_to_lower<P: ProcessManager>(
2547    cx: &mut StepCtx<P>,
2548    /// Text to lowercase.
2549    #[union(String, Pipe)]
2550    text: Value,
2551) -> Result<Value> {
2552    super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2553}
2554
2555/// Template projection of `TEXT_TO_LOWER`: the same fold for `{{ }}`
2556/// placeholders, which carry no step IO for pipes.
2557fn text_to_lower_string(text: Value) -> Result<Value> {
2558    super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
2559}
2560
2561/// Replace every literal occurrence of `from` with `to`.
2562///
2563/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
2564/// Pipes scan through a `from.len()` sliding window, so needles split
2565/// across chunk reads still rewrite.
2566/// Literal sliding search, not a pattern: an empty `from` fails
2567/// closed, and regex work with captures belongs to
2568/// `TEXT_REPLACE_REGEX`. Matching is case-sensitive; there is no
2569/// case-insensitive mode.
2570///
2571#[oxdock_func(
2572    rpn,
2573    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2574    template = text_replace_string
2575)]
2576#[example(
2577    name = "replace",
2578    code = r###"
2579    # Every literal occurrence rewrites in place.
2580    IMPORT [STD]
2581    LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
2582    ASSERT_EQ $fixed "hello there"
2583    "###
2584)]
2585#[example(
2586    name = "replace pipe mirrors",
2587    code = r###"
2588    # Pipe input mints pipe output with the same rewrite.
2589    IMPORT [STD]
2590    LET $cap: PIPE
2591    WITH_IO [stdout=$cap] {
2592        ECHO "hello world"
2593    }
2594    LET $trimmed: PIPE = TEXT_TRIM($cap)
2595    LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
2596    WITH_IO [stdin=$out] READ_LINE $line
2597    ASSERT_EQ $line "hello there"
2598    "###
2599)]
2600#[example(
2601    name = "replace template",
2602    code = r###"
2603    # String inputs run inside placeholders too.
2604    IMPORT [STD]
2605    LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
2606    ASSERT_EQ $msg "fixed:hello there"
2607    "###
2608)]
2609fn text_replace<P: ProcessManager>(
2610    cx: &mut StepCtx<P>,
2611    /// Text to rewrite.
2612    #[union(String, Pipe)]
2613    text: Value,
2614    /// Literal text to search for; empty fails closed.
2615    from: String,
2616    /// Literal replacement text.
2617    to: String,
2618) -> Result<Value> {
2619    super::args::mirror_stream(
2620        cx,
2621        "TEXT_REPLACE",
2622        &text,
2623        super::args::TextPump::ReplaceLiteral { from, to },
2624    )
2625}
2626
2627/// Template projection of `TEXT_REPLACE`: the same rewrite for `{{ }}`
2628/// placeholders, which carry no step IO for pipes.
2629fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
2630    super::args::mirror_string(
2631        "TEXT_REPLACE",
2632        &text,
2633        super::args::TextPump::ReplaceLiteral { from, to },
2634    )
2635}
2636
2637/// Replace every regex match, expanding `$1` and `$name` captures.
2638///
2639/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
2640/// Eager-only framing: matches span chunks, so pipe inputs stage
2641/// through the spill substrate instead of streaming.
2642/// Bad patterns fail closed naming the pattern and its position.
2643/// Matching is case-sensitive unless the pattern carries an inline
2644/// `(?i)` flag, which makes uppercase and lowercase letters match
2645/// each other.
2646/// The literal counterpart is `TEXT_REPLACE`.
2647///
2648#[oxdock_func(
2649    rpn,
2650    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
2651    template = text_replace_regex_string
2652)]
2653#[example(
2654    name = "replace with captures",
2655    code = r###"
2656    # Capture groups expand in the replacement.
2657    IMPORT [STD]
2658    LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2659    ASSERT_EQ $swapped "13/10/2026"
2660    "###
2661)]
2662#[example(
2663    name = "replace regex pipe mirrors",
2664    code = r###"
2665    # Pipe input mints pipe output with the same rewrite.
2666    IMPORT [STD]
2667    LET $cap: PIPE
2668    WITH_IO [stdout=$cap] {
2669        ECHO "2026-10-13"
2670    }
2671    LET $trimmed: PIPE = TEXT_TRIM($cap)
2672    LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
2673    WITH_IO [stdin=$out] READ_LINE $line
2674    ASSERT_EQ $line "13/10/2026"
2675    "###
2676)]
2677#[example(
2678    name = "replace regex template",
2679    code = r###"
2680    # String inputs run inside placeholders too.
2681    IMPORT [STD]
2682    LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
2683    ASSERT_EQ $msg "swapped:13/10/2026"
2684    "###
2685)]
2686fn text_replace_regex<P: ProcessManager>(
2687    cx: &mut StepCtx<P>,
2688    /// Text to rewrite.
2689    #[union(String, Pipe)]
2690    text: Value,
2691    /// Regex pattern to match.
2692    pattern: String,
2693    /// Replacement with `$1` and `$name` capture expansion.
2694    replacement: String,
2695) -> Result<Value> {
2696    if let Some(s) = text.as_str() {
2697        let out =
2698            super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2699        return Ok(Value::string(out));
2700    }
2701    let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
2702    let out = super::args::text_replace_regex_str(
2703        &content,
2704        &pattern,
2705        &replacement,
2706        "TEXT_REPLACE_REGEX",
2707    )?;
2708    super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
2709}
2710
2711/// Template projection of `TEXT_REPLACE_REGEX`: the same rewrite for
2712/// `{{ }}` placeholders, which carry no step IO for pipes.
2713fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
2714    let Some(s) = text.as_str() else {
2715        return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
2716    };
2717    let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
2718    Ok(Value::string(out))
2719}
2720
2721/// Split text on a literal delimiter into a `LIST<STRING>`.
2722///
2723/// An empty delimiter splits into single characters. Eager-only by
2724/// design: splitting into a list has no line framing to stream.
2725/// Delimiters match case-sensitively; there is no
2726/// case-insensitive mode.
2727///
2728#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2729#[example(
2730    name = "split",
2731    code = r###"
2732    # Delimiters split into list items.
2733    IMPORT [STD]
2734    LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
2735    ASSERT_EQ $parts.0 "a"
2736    ASSERT_EQ $parts.1 "b"
2737    ASSERT_EQ $parts.2 "c"
2738    "###
2739)]
2740fn text_split(
2741    /// Text to split.
2742    text: String,
2743    /// Literal delimiter; empty splits into characters.
2744    delimiter: String,
2745) -> Result<Value> {
2746    Ok(super::args::text_list_value(super::args::text_split_str(
2747        &text, &delimiter,
2748    )))
2749}
2750
2751/// Join a `LIST<STRING>` with a literal separator into a `STRING`.
2752///
2753#[oxdock_func(pure, returns = TypeTag::String)]
2754#[example(
2755    name = "join",
2756    code = r###"
2757    # List items join with the separator between them.
2758    IMPORT [STD]
2759    LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
2760    ASSERT_EQ $joined "a,b,c"
2761    "###
2762)]
2763fn text_join(
2764    /// List elements to join.
2765    elements: Vec<String>,
2766    /// Literal delimiter placed between elements.
2767    delimiter: String,
2768) -> Result<Value> {
2769    Ok(Value::string(elements.join(delimiter.as_str())))
2770}
2771
2772/// Split a shell command string into argv words.
2773///
2774/// Parses POSIX shell word syntax (single and double quotes, backslash
2775/// escapes) with the `shell-words` crate, the same splitter the remote
2776/// plugins use. Returns a `LIST<STRING>`. Unbalanced quotes fail.
2777/// Inverse of `SHELL_JOIN_ARGS`: joining the result re-splits
2778/// to the same words.
2779///
2780/// Shell syntax only: plain prose with no quoting splits on
2781/// whitespace like any shell would, which is rarely what prose wants.
2782///
2783#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2784#[example(
2785    name = "split args",
2786    code = r###"
2787    # Quoted segments stay one word.
2788    IMPORT [STD]
2789    LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
2790    ASSERT_EQ $argv.0 "gh"
2791    ASSERT_EQ $argv.3 "153"
2792    ASSERT_EQ $argv.5 "notes.md"
2793
2794    # Quotes and escapes parse the shell way.
2795    LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
2796    ASSERT_EQ $quoted.0 "say"
2797    ASSERT_EQ $quoted.1 "hi there"
2798    ASSERT_EQ $quoted.2 "a b"
2799    "###
2800)]
2801fn shell_split_args(
2802    /// Shell command string to split into words.
2803    command: String,
2804) -> Result<Value> {
2805    match shell_words::split(&command) {
2806        Ok(words) => Ok(super::args::text_list_value(words)),
2807        Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
2808    }
2809}
2810
2811/// Join argv words into one shell-parseable string.
2812///
2813/// Quotes each word with POSIX single-quote escaping through the
2814/// `shell-words` crate, so the result re-splits to the same words.
2815/// Inverse of `SHELL_SPLIT_ARGS` on the word side: splitting the
2816/// result returns the input list unchanged.
2817///
2818#[oxdock_func(pure, returns = TypeTag::String)]
2819#[example(
2820    name = "join args",
2821    code = r###"
2822    # Plain words join with spaces and no quoting.
2823    IMPORT [STD]
2824    LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
2825    ASSERT_EQ $plain "gh issue list"
2826
2827    # Words with spaces quote, and the round trip is exact.
2828    LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
2829    LET $joined: STRING = SHELL_JOIN_ARGS($words)
2830    LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
2831    ASSERT_EQ $back.0 "say"
2832    ASSERT_EQ $back.1 "hi there"
2833    ASSERT_EQ $back.2 "a'b"
2834    "###
2835)]
2836fn shell_join_args(
2837    /// Words to join into a shell command string.
2838    words: Vec<String>,
2839) -> Result<Value> {
2840    Ok(Value::string(shell_words::join(&words)))
2841}
2842
2843/// Split text into lines with universal newline handling.
2844///
2845/// Normalizes through the line-ending crate first so LF, CRLF, CR,
2846/// and mixed endings all split, then delegates the split itself to
2847/// `LineEnding::split` instead of hand-rolled scanning.
2848/// Returns a `LIST<STRING>`; eager-only like `TEXT_SPLIT`.
2849///
2850#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2851#[example(
2852    name = "lines",
2853    code = r###"
2854    # Newlines split into line items.
2855    IMPORT [STD]
2856    LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
2857    ASSERT_EQ $lines.0 "one"
2858    ASSERT_EQ $lines.1 "two"
2859    ASSERT_EQ $lines.2 "three"
2860
2861    # Windows endings split the same way after normalization.
2862    LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
2863    ASSERT_EQ $crlf.0 "one"
2864    ASSERT_EQ $crlf.1 "two"
2865    ASSERT_EQ $crlf.2 "three"
2866
2867    # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
2868    LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
2869    ASSERT_EQ $mixed.0 "a"
2870    ASSERT_EQ $mixed.1 "b"
2871    ASSERT_EQ $mixed.2 "c"
2872    ASSERT_EQ $mixed.3 "d"
2873    "###
2874)]
2875fn text_lines(
2876    /// Text to split into lines.
2877    text: String,
2878) -> Result<Value> {
2879    Ok(super::args::text_list_value(super::args::text_lines_str(
2880        &text,
2881    )))
2882}
2883
2884/// Split text into whitespace-separated fields, ignoring empties.
2885///
2886/// Returns a `LIST<STRING>`; the checksum-line parser that replaces
2887/// `cut -d' ' -f1` in CI legs.
2888///
2889#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2890#[example(
2891    name = "fields",
2892    code = r###"
2893    # Runs of whitespace separate fields; empties never appear.
2894    IMPORT [STD]
2895    LET $fields: LIST<STRING> = TEXT_FIELDS("  abc  def ")
2896    ASSERT_EQ $fields.0 "abc"
2897    ASSERT_EQ $fields.1 "def"
2898    "###
2899)]
2900fn text_fields(
2901    /// Text to split into fields.
2902    text: String,
2903) -> Result<Value> {
2904    Ok(super::args::text_list_value(super::args::text_fields_str(
2905        &text,
2906    )))
2907}
2908
2909/// Read lines `from` through `to` as a `LIST<STRING>`: the `sed -n
2910/// 'A,Bp'` window over universal newlines, for reading one file
2911/// section without holding the surrounding text.
2912///
2913/// Lines are 1-based and inclusive on both ends. Ranges past the end
2914/// clamp like sed instead of failing; a start before line 1 or past
2915/// `to` fails closed, since no line reading satisfies it.
2916///
2917#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2918#[example(
2919    name = "line range",
2920    code = r###"
2921    # Lines 2 through 3 come back as a list, 1-based inclusive.
2922    IMPORT [STD]
2923    LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
2924    ASSERT_EQ $window.0 "two"
2925    ASSERT_EQ $window.1 "three"
2926
2927    # Ranges past the end clamp instead of failing.
2928    LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
2929    ASSERT_EQ $tail.0 "two"
2930    "###
2931)]
2932fn text_lines_range(
2933    /// Text whose lines to window.
2934    text: String,
2935    /// First line, 1-based inclusive.
2936    from: i64,
2937    /// Last line, inclusive; past the end clamps.
2938    to: i64,
2939) -> Result<Value> {
2940    Ok(super::args::text_list_value(
2941        super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
2942    ))
2943}
2944
2945/// Report whether text matches a regex pattern.
2946///
2947/// Returns `BOOL`. Bad patterns fail closed naming the pattern and
2948/// its position. Matching is case-sensitive unless the pattern
2949/// carries an inline `(?i)` flag, which makes uppercase and lowercase
2950/// letters match each other.
2951///
2952#[oxdock_func(pure, returns = TypeTag::Bool)]
2953#[example(
2954    name = "match",
2955    code = r###"
2956    # Regex matches report true; misses report false.
2957    IMPORT [STD]
2958    LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
2959    ASSERT_EQ $hit true
2960
2961    # A miss is false, not a failure.
2962    LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
2963    ASSERT_EQ $miss false
2964    "###
2965)]
2966fn text_match(
2967    /// Text to test.
2968    text: String,
2969    /// Regex pattern to match.
2970    pattern: String,
2971) -> Result<Value> {
2972    let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
2973    Ok(Value::bool(re.is_match(&text)))
2974}
2975
2976/// Convert a value to BOOL.
2977///
2978/// Trims ASCII whitespace; accepts `true`/`false`, `1`/`0`,
2979/// `yes`/`no`, `on`/`off` in any case. Passes Bool through. Empty
2980/// and anything else fail: an empty string is not a boolean, so
2981/// absent env names (which read empty) must go through `BOOL_OR`
2982/// with a stated default instead of converting here.
2983///
2984#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
2985#[example(
2986    name = "convert",
2987    code = r###"
2988    IMPORT [STD]
2989    LET $n: BOOL = BOOL("yes")
2990    ASSERT_EQ $n true
2991    LET $f: BOOL = BOOL("0")
2992    ASSERT_EQ $f false
2993    "###
2994)]
2995fn bool_convert(
2996    /// Value to convert to `BOOL`.
2997    #[union(Bool, String)]
2998    val: Value,
2999) -> Result<Value> {
3000    if let Some(b) = val.as_bool() {
3001        return Ok(Value::bool(b));
3002    }
3003    let Some(s) = val.as_str() else {
3004        return Err(anyhow::anyhow!(
3005            "BOOL needs a Bool or String, found {val:?}"
3006        ));
3007    };
3008    match super::args::parse_bool_str(s) {
3009        Some(b) => Ok(Value::bool(b)),
3010        None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
3011    }
3012}
3013
3014/// Coerce text to `BOOL`, substituting a default for empty.
3015///
3016/// Returns `BOOL`. Blank input (a declared-but-absent env name, which
3017/// reads empty) resolves to `default` instead of failing, so each flag
3018/// site states its own absent polarity explicitly: negative-polarity
3019/// flags (`dry_run`) default true, positive ones default false. No
3020/// implicit polarity lives in the coercion. Non-blank garbage still
3021/// fails naming the input, exactly like `LET $x: BOOL` coercion.
3022///
3023#[oxdock_func(pure, returns = TypeTag::Bool)]
3024#[example(
3025    name = "absent-default",
3026    code = r###"
3027    # Absent names read empty; the default settles the polarity.
3028    IMPORT [STD]
3029    INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
3030    LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
3031    ASSERT_EQ $dry true
3032
3033    # Present values coerce strictly, ignoring the default.
3034    LET $off: BOOL = BOOL_OR("false", true)
3035    ASSERT_EQ $off false
3036    "###
3037)]
3038fn bool_or(
3039    /// Text to coerce (`true`/`false`, `1`/`0`, `yes`/`no`/`on`/`off`, any case).
3040    text: String,
3041    /// Absent-value default, used when the text is blank.
3042    default: bool,
3043) -> Result<Value> {
3044    if text.trim().is_empty() {
3045        return Ok(Value::bool(default));
3046    }
3047    match super::args::parse_bool_str(&text) {
3048        Some(b) => Ok(Value::bool(b)),
3049        None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
3050    }
3051}
3052
3053/// Extract capture groups for the first regex match.
3054///
3055/// Returns a `LIST<STRING>` where index 0 is the full match and the
3056/// rest are groups in order; non-participating groups bind empty so
3057/// indexes stay stable. No match binds an empty list. Matching is
3058/// case-sensitive unless the pattern carries an inline `(?i)` flag,
3059/// which makes uppercase and lowercase letters match each other.
3060///
3061#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3062#[example(
3063    name = "extract",
3064    code = r###"
3065    # Index zero is the full match; groups follow in order.
3066    IMPORT [STD]
3067    LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
3068    ASSERT_EQ $caps.0 "abc123"
3069    ASSERT_EQ $caps.1 "abc"
3070    ASSERT_EQ $caps.2 "123"
3071    "###
3072)]
3073fn text_extract(
3074    /// Text to search.
3075    text: String,
3076    /// Regex pattern with capture groups.
3077    pattern: String,
3078) -> Result<Value> {
3079    let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
3080    Ok(super::args::text_list_value(groups))
3081}
3082
3083/// Report whether text starts with a literal prefix.
3084///
3085/// Returns `BOOL`; the literal check behind tag and target branching
3086/// such as `matrix.target` suffix and prefix tests. Matching is
3087/// case-sensitive; there is no case-insensitive mode.
3088///
3089#[oxdock_func(pure, returns = TypeTag::Bool)]
3090#[example(
3091    name = "starts with",
3092    code = r###"
3093    # Present prefixes report true; misses report false.
3094    IMPORT [STD]
3095    LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
3096    ASSERT_EQ $hit true
3097
3098    # A miss is false, not a failure.
3099    LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
3100    ASSERT_EQ $miss false
3101    "###
3102)]
3103fn text_starts_with(
3104    /// Text to test.
3105    text: String,
3106    /// Literal prefix to look for.
3107    prefix: String,
3108) -> Result<Value> {
3109    Ok(Value::bool(text.starts_with(prefix.as_str())))
3110}
3111
3112/// Report whether text ends with a literal suffix.
3113///
3114/// Returns `BOOL`; the `endsWith(matrix.target, 'linux-musl')`
3115/// check in CI legs. Matching is case-sensitive; there is no
3116/// case-insensitive mode.
3117///
3118#[oxdock_func(pure, returns = TypeTag::Bool)]
3119#[example(
3120    name = "ends with",
3121    code = r###"
3122    # Present suffixes report true; misses report false.
3123    IMPORT [STD]
3124    LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
3125    ASSERT_EQ $hit true
3126
3127    # A miss is false, not a failure.
3128    LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
3129    ASSERT_EQ $miss false
3130    "###
3131)]
3132fn text_ends_with(
3133    /// Text to test.
3134    text: String,
3135    /// Literal suffix to look for.
3136    suffix: String,
3137) -> Result<Value> {
3138    Ok(Value::bool(text.ends_with(suffix.as_str())))
3139}
3140
3141/// Report whether text holds a literal substring.
3142///
3143/// Returns `BOOL`; the substring search behind target filtering
3144/// alongside the prefix and suffix tests. Matching is
3145/// case-sensitive; there is no case-insensitive mode.
3146///
3147#[oxdock_func(pure, returns = TypeTag::Bool)]
3148#[example(
3149    name = "contains",
3150    code = r###"
3151    # Present needles report true; misses report false.
3152    IMPORT [STD]
3153    LET $hit: BOOL = TEXT_CONTAINS("x86_64-linux-musl", "musl")
3154    ASSERT_EQ $hit true
3155
3156    # A miss is false, not a failure.
3157    LET $miss: BOOL = TEXT_CONTAINS("x86_64-linux-gnu", "musl")
3158    ASSERT_EQ $miss false
3159    "###
3160)]
3161fn text_contains(
3162    /// Text to search.
3163    text: String,
3164    /// Literal substring to look for.
3165    needle: String,
3166) -> Result<Value> {
3167    Ok(Value::bool(text.contains(needle.as_str())))
3168}
3169
3170/// Count the characters in text as Unicode scalars.
3171///
3172/// Multibyte characters count once each, so this is not the byte
3173/// length: `"héllo"` binds 5, not 6. The `${#var}` and `wc -m`
3174/// counterpart for scripts that size tags and digests.
3175///
3176#[oxdock_func(pure, returns = TypeTag::Int)]
3177#[example(
3178    name = "length",
3179    code = r###"
3180    # Plain text counts one per character.
3181    IMPORT [STD]
3182    LET $n: INT = TEXT_LENGTH("hello")
3183    ASSERT_EQ $n 5
3184
3185    # Multibyte characters count once each, not per byte.
3186    LET $wide: INT = TEXT_LENGTH("héllo")
3187    ASSERT_EQ $wide 5
3188    "###
3189)]
3190fn text_length(
3191    /// Text to measure.
3192    text: String,
3193) -> Result<Value> {
3194    Ok(Value::int(text.chars().count() as i64))
3195}
3196
3197/// Count non-overlapping literal occurrences of a needle.
3198///
3199/// Matches never share bytes, so `"aaa"` holds one `"aa"`, matching
3200/// `grep -o 'aa' | wc -l`. An empty needle fails closed instead of
3201/// binding every character boundary. Matching is case-sensitive;
3202/// there is no case-insensitive mode.
3203///
3204#[oxdock_func(pure, returns = TypeTag::Int)]
3205#[example(
3206    name = "count",
3207    code = r###"
3208    # Every non-overlapping occurrence counts once.
3209    IMPORT [STD]
3210    LET $n: INT = TEXT_COUNT("hello world", "o")
3211    ASSERT_EQ $n 2
3212
3213    # Overlapping candidates never double count.
3214    LET $once: INT = TEXT_COUNT("aaa", "aa")
3215    ASSERT_EQ $once 1
3216    "###
3217)]
3218fn text_count(
3219    /// Text to search.
3220    text: String,
3221    /// Literal needle to count; empty fails closed.
3222    needle: String,
3223) -> Result<Value> {
3224    let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
3225    Ok(Value::int(n))
3226}
3227
3228/// Count lines matching a regex pattern.
3229///
3230/// Lines split with universal newline handling, like `TEXT_LINES`,
3231/// and each line reports independently: this is `grep -c`, so a line
3232/// with two matches still counts once. Bad patterns fail closed
3233/// naming the pattern and its position. Matching is case-sensitive
3234/// unless the pattern carries an inline `(?i)` flag, which makes
3235/// uppercase and lowercase letters match each other.
3236///
3237#[oxdock_func(pure, returns = TypeTag::Int)]
3238#[example(
3239    name = "count matches",
3240    code = r###"
3241    # One line matches once no matter how many times it hits.
3242    IMPORT [STD]
3243    LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
3244    ASSERT_EQ $n 2
3245
3246    # A miss binds zero, never an error.
3247    LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
3248    ASSERT_EQ $none 0
3249    "###
3250)]
3251fn text_count_matches(
3252    /// Text whose lines to test.
3253    text: String,
3254    /// Regex pattern tested per line.
3255    pattern: String,
3256) -> Result<Value> {
3257    let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
3258    Ok(Value::int(n))
3259}
3260
3261/// Keep the lines matching a regex pattern.
3262///
3263/// Splits with universal newline handling, like `TEXT_LINES`, and
3264/// returns every matching line in order: plain `grep`, so a miss
3265/// binds an empty list instead of failing. A trailing options MAP
3266/// carries `invert`: `TEXT_GREP($text, $pattern, {invert: true})`
3267/// keeps every non-matching line instead, the `grep -v` shape. The
3268/// MAP omits freely; a missing MAP keeps matches. Matching is
3269/// case-sensitive unless the pattern carries an inline `(?i)` flag,
3270/// which makes uppercase and lowercase letters match each other. Bad
3271/// patterns fail closed naming the pattern and its position.
3272///
3273#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3274#[example(
3275    name = "grep",
3276    code = r###"
3277    # Matching lines come back as a list, in order.
3278    IMPORT [STD]
3279    LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
3280    ASSERT_EQ $hits.0 "one"
3281    ASSERT_EQ $hits.1 "one more"
3282
3283    # A miss binds an empty list, never an error.
3284    LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
3285    LET $joined: STRING = TEXT_JOIN($miss, ",")
3286    ASSERT_EQ $joined ""
3287
3288    # The (?i) flag ignores case, so uppercase lines match too.
3289    LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
3290    ASSERT_EQ $folded.0 "One"
3291    ASSERT_EQ $folded.1 "ONE more"
3292    "###
3293)]
3294#[example(
3295    name = "grep invert",
3296    code = r###"
3297    # The invert option keeps every non-matching line instead.
3298    IMPORT [STD]
3299    LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
3300    ASSERT_EQ $kept.0 "two"
3301
3302    # A pattern matching every line binds an empty list, never an error.
3303    LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
3304    LET $joined: STRING = TEXT_JOIN($none, ",")
3305    ASSERT_EQ $joined ""
3306
3307    # Options ride into placeholders as MAP literals. Placeholder
3308    # strings unescape only backslash and quote, so multiline text
3309    # arrives through a variable.
3310    LET $two_lines: STRING = "one\ntwo"
3311    LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
3312    ASSERT_EQ $msg "kept:two"
3313    "###
3314)]
3315fn text_grep(
3316    /// Text whose lines to filter.
3317    text: String,
3318    /// Regex pattern keeping a line.
3319    pattern: String,
3320    /// Filter settings: `invert`. Omittable: a missing options MAP fills `{}`.
3321    #[options("invert?: BOOL")]
3322    #[optional]
3323    options: BTreeMap<String, Value>,
3324) -> Result<Value> {
3325    // `check_options` in the wrapper verified the shape above (keys
3326    // and value types); the read below narrows infallibly after.
3327    let invert = super::args::text_invert_flag(&options);
3328    Ok(super::args::text_list_value(super::args::text_grep_str(
3329        &text,
3330        &pattern,
3331        invert,
3332        "TEXT_GREP",
3333    )?))
3334}
3335
3336/// True when a pipe sits at end of stream: closed with nothing buffered,
3337/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
3338/// Live writers, pinned keepers, and buffered bytes all answer false.
3339/// Never blocks: a reader already blocked stays blocked, so branch on
3340/// `EOF` before reading, not after. OS pairs and unbound handles answer
3341/// best-effort (kernel bytes are invisible there; see `INSPECT`).
3342/// Non-pipe arguments bail at the boundary: the parameter declares
3343/// `PIPE`, so the extractor and the static pass reject them before
3344/// the body runs.
3345///
3346#[oxdock_func(returns = TypeTag::Bool)]
3347#[example(
3348    name = "drain to end",
3349    code = r###"
3350    # Capture two lines, then drain to end of stream with no sentinel line.
3351    IMPORT [STD]
3352    LET $cap: PIPE
3353    WITH_IO [stdout=$cap] {
3354        ECHO "one"
3355        ECHO "two"
3356    }
3357
3358    # The loop exits on close, and the count proves both lines drained.
3359    LET $n: INT = 0
3360    WHILE !EOF($cap) {
3361        WITH_IO [stdin=$cap] READ_LINE $line
3362        $n = $n + 1
3363    }
3364    ASSERT_EQ $n 2
3365    "###
3366)]
3367fn eof<P: ProcessManager>(
3368    cx: &mut StepCtx<P>,
3369    /// Pipe handle to query for end of stream.
3370    pipe: PipeHandle,
3371) -> Result<Value> {
3372    let info = cx.state.io.inspect_pipe(&pipe);
3373    Ok(Value::bool(info.closed && info.buffered == 0))
3374}
3375
3376/// Field table for the `TASK_POLL` result map. Shared by the declared
3377/// return tag and the generated schema and reference docs, so the
3378/// shape agents see is the shape the builtin builds.
3379fn task_poll_result_fields() -> Arc<[Field]> {
3380    Arc::from(vec![
3381        Field {
3382            name: "state".to_string(),
3383            ty: TypeTag::String,
3384            docs: "Task phase: `running` or `finished`.",
3385            optional: false,
3386        },
3387        Field {
3388            name: "ok".to_string(),
3389            ty: TypeTag::Bool,
3390            docs: "True unless the task failed.",
3391            optional: false,
3392        },
3393        Field {
3394            name: "stdout_tail".to_string(),
3395            ty: TypeTag::String,
3396            docs: "Bounded stdout tail, live while running.",
3397            optional: false,
3398        },
3399        Field {
3400            name: "stderr_tail".to_string(),
3401            ty: TypeTag::String,
3402            docs: "Bounded stderr tail, live while running.",
3403            optional: false,
3404        },
3405        Field {
3406            name: "truncated_bytes".to_string(),
3407            ty: TypeTag::Int,
3408            docs: "Dropped head bytes past the per-stream cap.",
3409            optional: false,
3410        },
3411        Field {
3412            name: "exit_code".to_string(),
3413            ty: TypeTag::Int,
3414            docs: "Process exit code, present once finished.",
3415            optional: true,
3416        },
3417        Field {
3418            name: "result".to_string(),
3419            ty: TypeTag::Any,
3420            docs: "Task `RETURN` value, present on clean finish.",
3421            optional: true,
3422        },
3423        Field {
3424            name: "error".to_string(),
3425            ty: TypeTag::String,
3426            docs: "Failure text, present on failed finish.",
3427            optional: true,
3428        },
3429    ])
3430}
3431
3432/// Poll a background task without consuming it.
3433///
3434/// Reports the running state, the output tails accumulated so far,
3435/// and the final outcome once finished. Repeated polls are safe, and
3436/// a later `AWAIT` still joins normally. Polling after `AWAIT` fails
3437/// like double-await: the handle is spent.
3438///
3439/// Map keys: `state` always names the phase (`"running"` or
3440/// `"finished"`); `ok` is true unless the task failed; `stdout_tail`
3441/// and `stderr_tail` carry bounded output with `truncated_bytes`
3442/// counting dropped head bytes. Finished tasks add `exit_code`;
3443/// clean finishes add `result`, failed ones add `error` instead.
3444#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
3445#[example(
3446    name = "running poll",
3447    code = r###"
3448    # A sleeping task is still running on the first poll.
3449    IMPORT [STD]
3450    LET $t: HANDLE = ASYNC { SLEEP 30s }
3451    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)
3452    ASSERT_EQ $m.state "running"
3453    ASSERT_EQ $m.ok true
3454    # Clean up the sleeper so the run ends promptly.
3455    CANCEL $t
3456    "###
3457)]
3458#[example(
3459    name = "finished poll",
3460    code = r###"
3461    # A finished task reports its value and final tails, then still awaits.
3462    IMPORT [STD]
3463    LET $t: HANDLE = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
3464    # Do other work while the task runs; poll once it should be done.
3465    SLEEP 2s
3466    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)
3467    ASSERT_EQ $m.state "finished"
3468    ASSERT_EQ $m.result "done"
3469    LET $o: STRING = AWAIT $t
3470    ASSERT_EQ $o "done"
3471    "###
3472)]
3473fn task_poll<P: ProcessManager>(
3474    cx: &mut StepCtx<P>,
3475    /// Task handle from ASYNC.
3476    task: HandleValue,
3477) -> Result<Value> {
3478    let entry =
3479        super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
3480    let obs = entry.observe_completion();
3481    let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
3482    let mut out = BTreeMap::new();
3483    out.insert(
3484        "state".to_string(),
3485        Value::string(if obs.running { "running" } else { "finished" }.to_string()),
3486    );
3487    out.insert("ok".to_string(), Value::bool(obs.ok));
3488    if !obs.running {
3489        out.insert("exit_code".to_string(), Value::int(obs.exit_code));
3490    }
3491    if let Some(result) = obs.result {
3492        out.insert("result".to_string(), result);
3493    }
3494    if !obs.error.is_empty() {
3495        out.insert("error".to_string(), Value::string(obs.error));
3496    }
3497    out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
3498    out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
3499    out.insert(
3500        "truncated_bytes".to_string(),
3501        Value::int(dropped.min(i64::MAX as u64) as i64),
3502    );
3503    Ok(Value::map(out))
3504}
3505
3506fn meta_to_value(meta: &FuncMeta) -> Value {
3507    let mut map = BTreeMap::new();
3508    map.insert("name".to_string(), Value::string(meta.name.clone()));
3509    map.insert("module".to_string(), Value::string(meta.module.clone()));
3510    map.insert(
3511        "kind".to_string(),
3512        Value::string(meta.kind.label().to_string()),
3513    );
3514    let params = match &meta.params {
3515        Some(params) => Value::list(
3516            params
3517                .iter()
3518                .map(|p| {
3519                    let mut entry = BTreeMap::new();
3520                    entry.insert("name".to_string(), Value::string(p.name.clone()));
3521                    entry.insert(
3522                        "param_type".to_string(),
3523                        Value::string(
3524                            p.param_type
3525                                .as_ref()
3526                                .map(render_structural)
3527                                .unwrap_or_default(),
3528                        ),
3529                    );
3530                    entry.insert(
3531                        "allowed".to_string(),
3532                        Value::string(
3533                            p.allowed
3534                                .map(|values| values.join(", "))
3535                                .unwrap_or_default(),
3536                        ),
3537                    );
3538                    entry.insert("docs".to_string(), Value::string(String::new()));
3539                    entry.insert("optional".to_string(), Value::bool(p.optional));
3540                    entry.insert(
3541                        "options".to_string(),
3542                        match p.options {
3543                            Some(keys) => Value::list(
3544                                keys.iter()
3545                                    .map(|key| {
3546                                        let mut option = BTreeMap::new();
3547                                        option.insert(
3548                                            "name".to_string(),
3549                                            Value::string(key.name.to_string()),
3550                                        );
3551                                        option.insert(
3552                                            "value_type".to_string(),
3553                                            Value::string(render_structural(&key.value)),
3554                                        );
3555                                        option.insert(
3556                                            "required".to_string(),
3557                                            Value::bool(key.required),
3558                                        );
3559                                        option.insert(
3560                                            "default".to_string(),
3561                                            Value::string(
3562                                                key.default.unwrap_or_default().to_string(),
3563                                            ),
3564                                        );
3565                                        Value::map(option)
3566                                    })
3567                                    .collect(),
3568                            ),
3569                            None => Value::string(String::new()),
3570                        },
3571                    );
3572                    Value::map(entry)
3573                })
3574                .collect(),
3575        ),
3576        // Parameterless functions mint an empty LIST, never an empty
3577        // STRING: the `DESCRIBE` return tag promises `LIST<MAP<ANY>>`
3578        // for every entry, and the boundary enforces it.
3579        None => Value::list(Vec::new()),
3580    };
3581    map.insert("params".to_string(), params);
3582    map.insert(
3583        "returns".to_string(),
3584        Value::string(
3585            meta.returns
3586                .as_ref()
3587                .map(render_structural)
3588                .unwrap_or_default(),
3589        ),
3590    );
3591    map.insert("rpn".to_string(), Value::bool(meta.rpn));
3592    map.insert(
3593        "summary".to_string(),
3594        Value::string(meta.summary.to_string()),
3595    );
3596    Value::map(map)
3597}
3598
3599/// One named record schema: a shape host functions produce and scripts
3600/// bind by name (`LET $s: SSH_SESSION_INFO`). Travels with its module
3601/// so schemas register exactly when their producer does.
3602#[derive(Debug, Clone)]
3603pub struct RecordSchema {
3604    pub name: &'static str,
3605    pub fields: std::sync::Arc<[Field]>,
3606}
3607
3608/// One host library: functions and types registered under a single module
3609/// name. `Engine::register_module` stages these; runs expose them as
3610/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
3611#[derive(Clone)]
3612pub struct HostModule<P: ProcessManager> {
3613    pub name: String,
3614    pub funcs: Vec<HostRegistration<P>>,
3615    pub types: Vec<&'static TypeDescriptor>,
3616    pub record_schemas: Vec<RecordSchema>,
3617    /// Shared module state (endpoint registries and the like), stashed
3618    /// at registration and reachable from bodies through
3619    /// `StepCtx::module_state`. Lets every entry stay `#[oxdock_func]`:
3620    /// the macro only generates closers-over-nothing, so state that
3621    /// cannot ride in a value travels here instead of a hand-built
3622    /// closure. Prefer `.with_state(...)` over spelling this field.
3623    pub states: Vec<ModuleState>,
3624}
3625
3626/// One shared state object traveling with its module. Keyed by the
3627/// owning module name plus the value type at registration, so two
3628/// modules sharing one state type never collide.
3629#[derive(Clone)]
3630pub struct ModuleState {
3631    id: std::any::TypeId,
3632    state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
3633}
3634
3635/// A pre-run steps inspection: pure function of the parsed steps,
3636///
3637/// shared so the struct field stays under the complexity lint.
3638pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
3639
3640/// A pre-run check riding in a module's `states`: the runner executes
3641/// every staged check against the parsed steps before the first step
3642/// runs, so unmapped services fail fast with zero side effects. Modules
3643/// attach one with `.with_state(Arc::new(check))`; the runner discovers
3644/// them by type, so no struct field or plugin knowledge is needed here.
3645#[derive(Clone)]
3646pub struct PreRunCheck {
3647    check: Arc<PreRunInspector>,
3648}
3649
3650impl PreRunCheck {
3651    /// Wrap a steps inspector as a pre-run check.
3652    pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
3653        Self {
3654            check: Arc::new(check),
3655        }
3656    }
3657
3658    /// Run the inspection: `Ok` lets execution start.
3659    pub fn run(&self, steps: &[Step]) -> Result<()> {
3660        (self.check)(steps)
3661    }
3662}
3663
3664impl<P: ProcessManager> HostModule<P> {
3665    /// Attach shared state for bodies to fetch with
3666    /// `cx.module_state::<T>("MODULE")`. Chainable, like registration.
3667    pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
3668        self.states.push(ModuleState {
3669            id: std::any::TypeId::of::<T>(),
3670            state,
3671        });
3672        self
3673    }
3674
3675    /// Run every staged [`PreRunCheck`] against already-parsed steps.
3676    /// The runner calls this before the first step executes; the first
3677    /// failing check aborts the run with no side effects.
3678    pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
3679        for state in &self.states {
3680            if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
3681                check.run(steps)?;
3682            }
3683        }
3684        Ok(())
3685    }
3686}
3687
3688impl<P: ProcessManager> ExecState<P> {
3689    /// Register one [`HostModule`]: every function becomes callable as
3690    /// `MODULE::NAME`, every type joins the run's name directory.
3691    pub fn register_module(&mut self, module: HostModule<P>) {
3692        for registration in module.funcs {
3693            match registration {
3694                HostRegistration::Stateful { name, meta, func } => {
3695                    self.functions.register_host(&module.name, name, meta, func);
3696                }
3697                HostRegistration::Pure { name, meta, func } => {
3698                    self.functions
3699                        .register_pure_host(&module.name, name, meta, func);
3700                }
3701                HostRegistration::Both {
3702                    name,
3703                    meta,
3704                    func,
3705                    template,
3706                } => {
3707                    self.functions
3708                        .register_both_host(&module.name, name, meta, func, template);
3709                }
3710            }
3711        }
3712        for descriptor in module.types {
3713            self.register_type(descriptor);
3714        }
3715        for schema in module.record_schemas {
3716            self.register_record_schema(schema.name, schema.fields);
3717        }
3718        for state in module.states {
3719            self.module_states
3720                .insert((module.name.clone(), state.id), state.state);
3721        }
3722    }
3723
3724    /// All visible functions: natives plus hosts plus current DSL definitions.
3725    pub fn list_functions(&self) -> Vec<FuncMeta> {
3726        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
3727        // TODO: Make a "virtual function" and don't hardcode
3728        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
3729            out.push(FuncMeta {
3730                name: KEYWORD_INSPECT.to_string(),
3731                module: STD_MODULE_NAME.to_string(),
3732                kind: FuncKind::HostCtx,
3733                params: None,
3734                returns: Some(TypeTag::Map),
3735                rpn: false,
3736                summary: "Inspect a variable binding.",
3737                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3738                examples: &[],
3739            });
3740        }
3741        out.sort_by(|a, b| a.name.cmp(&b.name));
3742        out
3743    }
3744
3745    /// Describe one function by name, or `None` when unknown.
3746    pub fn describe_function(&self, name: &str) -> Option<Value> {
3747        if let Some(meta) = self.functions.meta(name) {
3748            return Some(meta_to_value(&meta));
3749        }
3750        // TODO: Make a "virtual function" and don't hardcode
3751        if name == KEYWORD_INSPECT {
3752            return Some(meta_to_value(&FuncMeta {
3753                name: KEYWORD_INSPECT.to_string(),
3754                module: STD_MODULE_NAME.to_string(),
3755                kind: FuncKind::HostCtx,
3756                params: None,
3757                returns: Some(TypeTag::Map),
3758                rpn: false,
3759                summary: "Inspect a variable binding.",
3760                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
3761                examples: &[],
3762            }));
3763        }
3764        None
3765    }
3766
3767    pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
3768        self.functions.clone_pure_fn(name)
3769    }
3770
3771    /// Shared snapshot of every registered pure function for
3772    /// placeholder and host driven expansion. Public so host crates
3773    /// resolve calls through the live registry instead of hardcoding
3774    /// module or function names. Cloning the `Arc` never copies the map.
3775    pub fn pure_function_table(&self) -> Arc<PureTable> {
3776        self.functions.pure_shared()
3777    }
3778
3779    pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
3780        self.functions.clone_ctx_fn(name)
3781    }
3782
3783    pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
3784        self.functions.meta(name)
3785    }
3786}
3787
3788#[cfg(test)]
3789mod tests {
3790    use super::*;
3791
3792    #[test]
3793    fn describe_entry_renders_union_spellings() {
3794        // Union params and returns render through the same structural
3795        // renderer every other tag uses: `DESCRIBE` (and the generated
3796        // reference built on it) names the admission set, never a
3797        // bare word or an empty string. Built by macro, so the
3798        // spelling cannot drift from the members.
3799        let union = oxdock_parser::union_tag!(String, Pipe);
3800        let meta = FuncMeta {
3801            name: "T::F".to_string(),
3802            module: "T".to_string(),
3803            kind: FuncKind::HostPure,
3804            params: Some(vec![FuncParam {
3805                name: "text".to_string(),
3806                param_type: Some(union.clone()),
3807                allowed: None,
3808                docs: "",
3809                options: None,
3810                optional: false,
3811            }]),
3812            returns: Some(union),
3813            rpn: false,
3814            summary: "test-only",
3815            docs: "test-only",
3816            examples: &[],
3817        };
3818        let value = meta_to_value(&meta);
3819        let map = value.as_map().expect("describe value is a map");
3820        let params = map
3821            .get("params")
3822            .expect("params key")
3823            .as_list()
3824            .expect("params is a list");
3825        let first = params[0].as_map().expect("entry is a map");
3826        assert_eq!(
3827            first.get("param_type").and_then(Value::as_str),
3828            Some("STRING|PIPE"),
3829            "param renders the set"
3830        );
3831        assert_eq!(
3832            map.get("returns").and_then(Value::as_str),
3833            Some("STRING|PIPE"),
3834            "returns render the set"
3835        );
3836    }
3837
3838    #[test]
3839    fn describe_entry_carries_optional_flag() {
3840        // The `optional` key on params entries is the machine-readable
3841        // half of the `?` rendering: pin both values through the same
3842        // builder the runtime serves, not through prose.
3843        let meta = FuncMeta {
3844            name: "T::F".to_string(),
3845            module: "T".to_string(),
3846            kind: FuncKind::HostPure,
3847            params: Some(vec![
3848                FuncParam {
3849                    name: "url".to_string(),
3850                    param_type: Some(TypeTag::String),
3851                    allowed: None,
3852                    docs: "",
3853                    options: None,
3854                    optional: false,
3855                },
3856                FuncParam {
3857                    name: "options".to_string(),
3858                    param_type: Some(TypeTag::Map),
3859                    allowed: None,
3860                    docs: "",
3861                    options: None,
3862                    optional: true,
3863                },
3864            ]),
3865            returns: Some(TypeTag::String),
3866            rpn: false,
3867            summary: "test-only",
3868            docs: "test-only",
3869            examples: &[],
3870        };
3871        let value = meta_to_value(&meta);
3872        let map = value.as_map().expect("describe value is a map");
3873        let params = map
3874            .get("params")
3875            .expect("params key")
3876            .as_list()
3877            .expect("params is a list");
3878        assert_eq!(params.len(), 2);
3879        let first = params[0].as_map().expect("entry is a map");
3880        let second = params[1].as_map().expect("entry is a map");
3881        assert_eq!(
3882            first.get("optional").and_then(Value::as_bool),
3883            Some(false),
3884            "required param must read false"
3885        );
3886        assert_eq!(
3887            second.get("optional").and_then(Value::as_bool),
3888            Some(true),
3889            "omittable param must read true"
3890        );
3891    }
3892
3893    #[test]
3894    fn template_twins_mirror_string_paths_and_refuse_pipes() {
3895        // Every template twin answers strings through the shared pump
3896        // semantics and refuses pipes naming the step IO they need:
3897        // placeholder evaluation carries no step context to pump
3898        // through. Table-driven so a twinless mirror op fails here
3899        // naming it.
3900        let pipe = Value::pipe_fresh();
3901        type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
3902        let cases: Vec<TwinCase> = vec![
3903            (
3904                "TEXT_TRIM",
3905                Box::new(|| text_trim_string(Value::string("  hello  ".to_string()))),
3906            ),
3907            (
3908                "TEXT_TRIM_PREFIX",
3909                Box::new(|| {
3910                    text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
3911                }),
3912            ),
3913            (
3914                "TEXT_TRIM_SUFFIX",
3915                Box::new(|| {
3916                    text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
3917                }),
3918            ),
3919            (
3920                "TEXT_TO_UPPER",
3921                Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
3922            ),
3923            (
3924                "TEXT_TO_LOWER",
3925                Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
3926            ),
3927            (
3928                "TEXT_REPLACE",
3929                Box::new(|| {
3930                    text_replace_string(
3931                        Value::string("ab".to_string()),
3932                        "b".to_string(),
3933                        "c".to_string(),
3934                    )
3935                }),
3936            ),
3937            (
3938                "TEXT_REPLACE_REGEX",
3939                Box::new(|| {
3940                    text_replace_regex_string(
3941                        Value::string("ab".to_string()),
3942                        "b".to_string(),
3943                        "c".to_string(),
3944                    )
3945                }),
3946            ),
3947        ];
3948        assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
3949        for (name, run) in &cases {
3950            let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
3951            assert!(
3952                value.as_str().is_some(),
3953                "{name} twin must answer STRING, got {}",
3954                value.type_name()
3955            );
3956        }
3957        assert_eq!(
3958            text_trim_string(Value::string("  hello  ".to_string()))
3959                .expect("trim twin")
3960                .as_str(),
3961            Some("hello")
3962        );
3963        // Pipes refuse through the shared message on every twin.
3964        let pipe_cases: Vec<(&str, Result<Value>)> = vec![
3965            ("TEXT_TRIM", text_trim_string(pipe.clone())),
3966            (
3967                "TEXT_TRIM_PREFIX",
3968                text_trim_prefix_string(pipe.clone(), "v".to_string()),
3969            ),
3970            (
3971                "TEXT_TRIM_SUFFIX",
3972                text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
3973            ),
3974            ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
3975            ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
3976            (
3977                "TEXT_REPLACE",
3978                text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
3979            ),
3980            (
3981                "TEXT_REPLACE_REGEX",
3982                text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
3983            ),
3984        ];
3985        for (name, result) in pipe_cases {
3986            let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
3987            assert!(
3988                format!("{err:#}").contains("step IO"),
3989                "{name} refusal names the missing context: {err:#}"
3990            );
3991        }
3992    }
3993
3994    #[test]
3995    fn shell_words_join_split_round_trip() {
3996        // Join and split are absolute inverses on the word side: the
3997        // joiner quotes through `shell-words`, the splitter parses the
3998        // same syntax, so every adversarial word survives the round trip.
3999        let words = vec![
4000            "gh".to_string(),
4001            "issue".to_string(),
4002            "comment".to_string(),
4003            "with spaces".to_string(),
4004            "it's".to_string(),
4005            "say \"hi\"".to_string(),
4006            "$HOME".to_string(),
4007            "$(whoami)".to_string(),
4008            "C:\\path\\to".to_string(),
4009            "naïve café".to_string(),
4010            "".to_string(),
4011        ];
4012        let joined = shell_words::join(&words);
4013        let back = shell_words::split(&joined).expect("join output must parse");
4014        assert_eq!(back, words);
4015        assert!(shell_words::split("unbalanced \"quote").is_err());
4016    }
4017}