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