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