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_fs::to_forward_slashes;
6use oxdock_fs::{GuardedPath, WorkspaceSelection};
7use oxdock_func_macro::oxdock_func;
8use oxdock_parser::value::HandleValue;
9use oxdock_parser::{
10    Field, GuardExpr, KEYWORD_INSPECT, MODULE_SEPARATOR, SCRIPT_MODULE_NAME, STD_MODULE_NAME,
11    SemaphoreState, Step, TypeTag, Value, base_name, guards_overlap, qualify, render_structural,
12    split_qualified,
13};
14use oxdock_pipe::PipeHandle;
15use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};
16
17use super::io::StreamHandle;
18use super::state::ExecState;
19use super::steps::StepCtx;
20use super::typing::TypeDescriptor;
21
22/// Origin of a callable in the unified function registry. `Script` is an
23/// interpreted `FUNC` body; `HostCtx` and `HostPure` are compiled Rust
24/// functions (the `#[oxdock_func]` host export macro). Builtins and
25/// runtime-registered hosts share the host kinds; only `DESCRIBE` output
26/// shows the label, and both host kinds keep rendering as `host`.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum FuncKind {
29    Script,
30    HostCtx,
31    HostPure,
32}
33
34/// Canonical registry key for a file-imported script function:
35/// defining file plus base name, through the shared [`qualify`]
36/// owner. Importer aliases never appear here.
37pub(super) fn file_func_key(defining_file: &str, name: &str) -> String {
38    qualify(defining_file, name)
39}
40
41/// Loud ambiguity error for one unit importing the same alias from
42/// several files. `files` sorts for deterministic rendering.
43pub(super) fn ambiguous_alias_message(alias: &str, name: &str, files: &HashSet<String>) -> String {
44    let mut files: Vec<&str> = files.iter().map(|file| file.as_str()).collect();
45    files.sort();
46    format!(
47        "function `{alias}::{name}` is ambiguous: alias `{alias}` is imported from multiple files ({})",
48        files.join(", ")
49    )
50}
51
52/// One `ALIAS::FUNC` spelling's fate under a unit's alias targets.
53/// Single owner for alias-target matching: every resolution path
54/// (static calls, template gates, runtime dispatch, placeholder
55/// misses, snapshots, re-exports) classifies here and acts on the
56/// result, never restating the singleton/ambiguity branches.
57pub(super) enum AliasResolution {
58    /// Resolve as spelled (bare, `SCRIPT::`, hosts, unknown-to-unit).
59    Global,
60    /// Canonical defining-file key.
61    Canonical(String),
62    /// Known alias with no usable target: the caller reports unknown.
63    Unknown,
64    /// One alias, several files with the name in overlapping guards:
65    /// fail loud, naming the colliding spelling.
66    Ambiguous {
67        alias: String,
68        base: String,
69        files: HashSet<String>,
70    },
71    /// Several files hold the name under disjoint guards: the caller
72    /// validates every target instead of failing outright
73    /// (platform-conditional imports). `has_host` marks a disjoint
74    /// host-harvest branch (a `(None, guard)` target) alongside the
75    /// files: that branch holds no file functions, so any file-backed
76    /// call misses there.
77    Any {
78        base: String,
79        files: HashSet<String>,
80        has_host: bool,
81    },
82}
83
84/// One unit's alias targets: defining file plus the import's guard.
85/// Single owner for the target-set shape; static and runtime tables
86/// share it. Guards decide ambiguity (overlapping guards importing
87/// different files under one alias are ambiguous); unguarded imports
88/// overlap everything. Runtime records `None` (its imports execute
89/// once taken).
90pub(super) type AliasTargets = HashMap<String, Vec<(Option<String>, Option<GuardExpr>)>>;
91
92/// Shared frame-walk precedence for script resolution (#322):
93/// innermost nested frames, then the owning file top-level, then
94/// per-unit harvests. Static checking and runtime dispatch implement
95/// this trait over their own stores and share [`FuncFrameView::walk`],
96/// so precedence lives once and the twins cannot drift.
97pub(super) trait FuncFrameView {
98    /// Resolution hit for this layer (entry, info+key, etc.).
99    type Hit;
100    /// Innermost nested frames outward.
101    fn find_nested(&self, base: &str) -> Option<Self::Hit>;
102    /// Owning file top-level (entry included via its unit key).
103    fn find_home(&self, unit: &str, base: &str) -> Option<Self::Hit>;
104    /// Per-unit bare harvests.
105    fn find_harvest(&self, unit: &str, base: &str) -> Option<Self::Hit>;
106    /// Precedence owner: nested, home, harvest.
107    fn walk(&self, unit: &str, base: &str) -> Option<Self::Hit> {
108        self.find_nested(base)
109            .or_else(|| self.find_home(unit, base))
110            .or_else(|| self.find_harvest(unit, base))
111    }
112}
113
114/// Classify one call spelling under a unit's alias targets. Single
115/// entry point for alias-target matching: splits the spelling,
116/// resolves `SCRIPT::` and bare names globally, and maps file aliases
117/// through the unit's recorded targets. `exists` probes the caller's
118/// function map for a canonical key.
119pub(super) fn classify_alias_call(
120    unit_targets: &AliasTargets,
121    name: &str,
122    exists: &dyn Fn(&str) -> bool,
123) -> AliasResolution {
124    let Some((alias, base)) = split_qualified(name) else {
125        return AliasResolution::Global;
126    };
127    if alias == SCRIPT_MODULE_NAME {
128        return AliasResolution::Global;
129    }
130    let Some(entries) = unit_targets.get(alias) else {
131        return AliasResolution::Global;
132    };
133    if entries.is_empty() {
134        return AliasResolution::Unknown;
135    }
136    // Distinct defining files in first-seen order; `(None, guard)`
137    // entries are host-harvest branches holding no file functions.
138    let mut files: Vec<(&str, Vec<Option<&GuardExpr>>)> = Vec::new();
139    let mut host_guards: Vec<Option<&GuardExpr>> = Vec::new();
140    for (file, guard) in entries {
141        match file {
142            Some(path) => match files.iter_mut().find(|(known, _)| *known == path) {
143                Some((_, guards)) => guards.push(guard.as_ref()),
144                None => files.push((path, vec![guard.as_ref()])),
145            },
146            None => host_guards.push(guard.as_ref()),
147        }
148    }
149    if files.is_empty() {
150        return AliasResolution::Unknown;
151    }
152    let overlaps = |left: &[Option<&GuardExpr>], right: &[Option<&GuardExpr>]| {
153        left.iter()
154            .any(|a| right.iter().any(|b| guards_overlap(*a, *b)))
155    };
156    if files.len() == 1 {
157        // A lone file target stays canonical unless a host-harvest
158        // branch is disjoint from it: on that platform the alias
159        // holds no file function, so the call misses there.
160        let disjoint_host = host_guards
161            .iter()
162            .any(|host| !overlaps(&files[0].1, &[*host]));
163        if !disjoint_host {
164            return AliasResolution::Canonical(file_func_key(files[0].0, base));
165        }
166        let mut all = HashSet::new();
167        all.insert(files[0].0.to_string());
168        return AliasResolution::Any {
169            base: base.to_string(),
170            files: all,
171            has_host: true,
172        };
173    }
174    let mut ambiguous = HashSet::new();
175    for (i, (file, guards)) in files.iter().enumerate() {
176        for (other, other_guards) in files.iter().skip(i + 1) {
177            if overlaps(guards, other_guards)
178                && (exists(&file_func_key(file, base)) || exists(&file_func_key(other, base)))
179            {
180                ambiguous.insert((*file).to_string());
181                ambiguous.insert((*other).to_string());
182            }
183        }
184    }
185    if !ambiguous.is_empty() {
186        return AliasResolution::Ambiguous {
187            alias: alias.to_string(),
188            base: base.to_string(),
189            files: ambiguous,
190        };
191    }
192    let all: HashSet<String> = files.iter().map(|(file, _)| (*file).to_string()).collect();
193    if all.iter().any(|file| exists(&file_func_key(file, base))) {
194        return AliasResolution::Any {
195            base: base.to_string(),
196            files: all,
197            has_host: !host_guards.is_empty(),
198        };
199    }
200    AliasResolution::Unknown
201}
202
203/// Missing-import hint for an unknown function (#319): when `base`
204/// is `EXPORT`ed by already-loaded files, name them so the error
205/// directs the author to the fix instead of dead-ending. `files`
206/// pairs each loaded file's key with its exported func names (only
207/// exported names suggest: privates would fail the `EXPORT` gate);
208/// `unit_targets` is the failing unit's alias map for `did you mean
209/// ALIAS::BASE` suggestions. Bare and `SCRIPT::` spellings search
210/// the same way. Labels sort for determinism. Only unknown-function
211/// errors append this; nothing else restates the exporter search.
212pub(super) fn missing_import_hint<'a>(
213    files: impl IntoIterator<Item = (&'a str, &'a [String])>,
214    unit_targets: &AliasTargets,
215    name: &str,
216) -> Option<String> {
217    let base = match split_qualified(name) {
218        Some((_, base)) => base,
219        None => name,
220    };
221    if base.is_empty() {
222        return None;
223    }
224    let mut exporters: Vec<&str> = files
225        .into_iter()
226        .filter(|(_, exports)| exports.iter().any(|exported| exported == base))
227        .map(|(file, _)| file)
228        .collect();
229    exporters.sort();
230    exporters.dedup();
231    if exporters.is_empty() {
232        return None;
233    }
234    // Aliases the failing unit already imports each exporter under.
235    let imported_as = |file: &str| {
236        let mut aliases: Vec<&str> = unit_targets
237            .iter()
238            .filter(|(_, targets)| {
239                targets
240                    .iter()
241                    .any(|(target, _)| target.as_deref() == Some(file))
242            })
243            .map(|(alias, _)| alias.as_str())
244            .collect();
245        aliases.sort();
246        aliases
247    };
248    if exporters.len() == 1 {
249        let file = exporters[0];
250        let aliases = imported_as(file);
251        // Prefer a working spelling: when the file is imported under
252        // several aliases, an alias spelling the failed call
253        // differently resolves, so suggest it before falling back to
254        // the self-view diagnostic.
255        let import_alias = aliases
256            .iter()
257            .find(|alias| qualify(alias, base) != name)
258            .or(aliases.first())
259            .copied();
260        let suggestion = match import_alias {
261            Some(import_alias) => {
262                let spelling = qualify(import_alias, base);
263                if spelling == name {
264                    // Disjoint-guard view: the file exports the name
265                    // but this alias resolves it elsewhere here.
266                    format!(
267                        "file \"{file}\" exports `{base}` but the `{import_alias}` view does not resolve it here"
268                    )
269                } else {
270                    format!("did you mean `{spelling}`? (file \"{file}\" exports `{base}`)")
271                }
272            }
273            None => {
274                // Forward slashes: a raw Windows path would emit
275                // invalid escapes inside the quoted suggestion.
276                let path = to_forward_slashes(file);
277                format!(
278                    "file \"{file}\" exports `{base}`: add `[FUNC {base} FROM \"{path}\"]` to an IMPORT"
279                )
280            }
281        };
282        return Some(format!("; {suggestion}"));
283    }
284    let mut files = exporters.join("\", \"");
285    files.insert(0, '"');
286    files.push('"');
287    Some(format!(
288        "; files {files} export `{base}`: qualify the call with the importing alias"
289    ))
290}
291
292/// Whether one `EXPORT CONST` entry serves reads of stored `name`
293/// (the sigil-stripped binding key): the entry itself, or a
294/// qualified `ALIAS::NAME` forward of the same base. Single owner
295/// for the cover rule every qualified-`CONST` path matches on.
296pub(super) fn const_export_covers(entry: &str, name: &str) -> bool {
297    base_name(entry) == name
298}
299
300/// How a module holds a top-level binding, for broken-forward
301/// diagnostics: a `CONST`, a never-exportable `LET`, or nothing.
302pub(super) enum BindingPresence {
303    Const,
304    Let,
305    Absent,
306}
307
308/// Missing-`CONST` hint from the queried alias's own files: an
309/// unexported `CONST` or a private `LET` with the same base names the
310/// real fault instead of a bare unknown-name miss. Single owner for
311/// the hint every qualified-`CONST` miss renders, so static and
312/// runtime agree word for word. Reads only `view.binding`, never a
313/// twin-local store scan.
314pub(super) fn missing_const_hint<S: ModuleGraphView>(
315    view: &S,
316    targets: &AliasTargets,
317    alias: &str,
318    name: &str,
319) -> Option<String> {
320    targets
321        .get(alias)
322        .map(|entries| {
323            entries
324                .iter()
325                .filter_map(|(file, _)| file.as_ref())
326                .collect::<Vec<_>>()
327        })
328        .unwrap_or_default()
329        .iter()
330        .find_map(|file| match view.binding(file, name) {
331            BindingPresence::Const => Some(format!(
332                "module holds `{name}` as CONST but does not export it: add `EXPORT CONST ${name}`"
333            )),
334            BindingPresence::Let => Some(format!(
335                "`{name}` is a LET binding and cannot be exported: only CONST bindings cross the module boundary"
336            )),
337            BindingPresence::Absent => None,
338        })
339}
340
341/// Read-only view of the module graph one qualified-`CONST`
342/// resolution needs. Implemented once for live runtime stores and
343/// once for static closure tables, so the walk below runs
344/// identically on both and the twins cannot drift: static
345/// validation, eager closure checks, and serving all chase through
346/// this one owner.
347pub(super) trait ModuleGraphView {
348    /// Raw `EXPORT CONST` entries (stored bare names and qualified forwards).
349    fn const_exports(&self, file: &str) -> Option<&[String]>;
350    /// Outbound alias targets for `file`'s own unit: the namespace
351    /// each forward hop resolves in.
352    fn alias_targets(&self, file: &str) -> AliasTargets;
353    /// How `file` holds top-level `name`, for broken-link detail.
354    fn binding(&self, file: &str, name: &str) -> BindingPresence;
355}
356
357/// One `ALIAS::NAME` read's holder files: the unit's alias targets
358/// classified through the shared matcher, kept only when the file
359/// covers the base. Single owner for the holder half of
360/// qualified-`CONST` resolution; the chase half is
361/// [`chase_const_forward`].
362#[derive(Debug)]
363pub(super) enum ConstHolders {
364    /// Covering files, sorted, possibly empty (callers run their
365    /// own missing-name hints then).
366    Found(Vec<String>),
367    /// The alias is unknown to this unit.
368    NoAlias,
369    /// Several overlapping files hold the base: fail loud.
370    Ambiguous {
371        alias: String,
372        base: String,
373        files: HashSet<String>,
374    },
375}
376
377/// Suffix probe for the matcher's canonical keys (`file::base`):
378/// the base is ours, so stripping it recovers the file exactly,
379/// and only a covering file counts as a holder. Single owner for
380/// the suffix shape, so call sites never restate the separator.
381fn const_canonical_suffix(name: &str) -> String {
382    format!("{MODULE_SEPARATOR}{name}")
383}
384
385/// Classify one qualified-`CONST` read to its holder files.
386pub(super) fn const_holder_files<S: ModuleGraphView>(
387    view: &S,
388    unit_targets: &AliasTargets,
389    alias: &str,
390    name: &str,
391) -> ConstHolders {
392    let qualified = qualify(alias, name);
393    let suffix = const_canonical_suffix(name);
394    // Suffix probe for the matcher's canonical keys
395    // (`file::base`): the base is ours, so stripping it recovers the
396    // file exactly, and only a covering file counts as a holder.
397    let exports = |canonical: &str| {
398        canonical
399            .strip_suffix(suffix.as_str())
400            .and_then(|file| view.const_exports(file))
401            .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
402    };
403    let mut holders = match classify_alias_call(unit_targets, &qualified, &exports) {
404        AliasResolution::Global | AliasResolution::Unknown => return ConstHolders::NoAlias,
405        AliasResolution::Ambiguous { alias, base, files } => {
406            return ConstHolders::Ambiguous { alias, base, files };
407        }
408        AliasResolution::Canonical(canonical) => {
409            let Some(file) = canonical.strip_suffix(suffix.as_str()) else {
410                return ConstHolders::NoAlias;
411            };
412            vec![file.to_string()]
413        }
414        AliasResolution::Any { mut files, .. } => {
415            let mut files: Vec<String> = files.drain().collect();
416            files.sort();
417            files
418        }
419    };
420    holders.retain(|file| {
421        view.const_exports(file)
422            .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
423    });
424    ConstHolders::Found(holders)
425}
426
427/// Failure modes of [`chase_const_forward`], rendered by each caller
428/// with its own position context (static line/col, runtime none,
429/// eager file attribution). Wording lives here once, on [`std::fmt::Display`],
430/// so diagnostics cannot drift between the twins.
431#[derive(Debug)]
432pub(super) enum ForwardError {
433    /// The holder file itself is gone from the view.
434    Unknown { original: String },
435    /// A forward hop lands where the base is missing.
436    Broken {
437        original: String,
438        hop: String,
439        detail: BrokenDetail,
440    },
441    /// One file forwards the same base from several aliases.
442    Split { original: String, hops: Vec<String> },
443    /// Hops revisit a spelling. Import cycles are rejected before
444    /// resolution, so this is defense in depth.
445    Cycle { chain: Vec<String> },
446    /// One hop resolves to several overlapping files.
447    HopAmbiguous {
448        alias: String,
449        base: String,
450        files: HashSet<String>,
451    },
452}
453
454/// Why a forward hop lands nowhere.
455#[derive(Debug)]
456pub(super) enum BrokenDetail {
457    /// The terminal file holds the base as an unexported `CONST`.
458    UnexportedConst,
459    /// The terminal file holds the base as a `LET`.
460    Let,
461    /// Nothing there answers to the base.
462    Absent,
463}
464
465impl std::fmt::Display for ForwardError {
466    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
467        match self {
468            ForwardError::Unknown { original } => write!(f, "unknown CONST `{original}`"),
469            ForwardError::Broken {
470                original,
471                hop,
472                detail,
473            } => {
474                let base = base_name(hop);
475                let detail = match detail {
476                    BrokenDetail::UnexportedConst => format!(
477                        "module holds `{base}` as CONST but does not export it: add `EXPORT CONST ${base}`"
478                    ),
479                    BrokenDetail::Let => format!(
480                        "`{base}` is a LET binding and cannot be exported: only CONST bindings cross the module boundary"
481                    ),
482                    BrokenDetail::Absent => {
483                        let (forward, _) = split_qualified(hop).unwrap_or(("", base));
484                        format!("no import alias `{forward}` exports `{base}`")
485                    }
486                };
487                write!(
488                    f,
489                    "unknown CONST `{original}`: re-export `{hop}` does not resolve: {detail}"
490                )
491            }
492            ForwardError::Split { original, hops } => write!(
493                f,
494                "ambiguous CONST `{original}`: re-exported from {}; export exactly one source",
495                hops.join(" and ")
496            ),
497            ForwardError::Cycle { chain } => {
498                write!(f, "CONST re-export cycle detected: {}", chain.join(" -> "))
499            }
500            ForwardError::HopAmbiguous { alias, base, files } => write!(
501                f,
502                "{}",
503                ambiguous_alias_message(alias, base, files).replacen("function", "CONST", 1)
504            ),
505        }
506    }
507}
508
509impl std::error::Error for ForwardError {}
510
511/// Follow qualified `EXPORT CONST $ALIAS::NAME` forwards from `file`
512/// to the files holding the stored bare binding, resolving each hop
513/// in the exporting file's own unit. A local bare definition shadows
514/// forwards; disjoint-guard branches each chase to their own
515/// terminal, so all terminals return (callers apply their own
516/// multi-holder policy). Each hop preserves the base name.
517pub(super) fn chase_const_forward<S: ModuleGraphView>(
518    view: &S,
519    file: &str,
520    name: &str,
521    original: &str,
522) -> Result<Vec<String>, ForwardError> {
523    let mut terminals: Vec<String> = Vec::new();
524    chase_from(view, file, name, original, &mut Vec::new(), &mut terminals)?;
525    terminals.sort();
526    terminals.dedup();
527    Ok(terminals)
528}
529
530fn chase_from<S: ModuleGraphView>(
531    view: &S,
532    current: &str,
533    name: &str,
534    original: &str,
535    chain: &mut Vec<String>,
536    terminals: &mut Vec<String>,
537) -> Result<(), ForwardError> {
538    let suffix = const_canonical_suffix(name);
539    let covering = |canonical: &str| {
540        canonical
541            .strip_suffix(suffix.as_str())
542            .and_then(|file| view.const_exports(file))
543            .is_some_and(|names| names.iter().any(|entry| const_export_covers(entry, name)))
544    };
545    let mut current = current.to_string();
546    loop {
547        let Some(names) = view.const_exports(current.as_str()) else {
548            return Err(ForwardError::Unknown {
549                original: original.to_string(),
550            });
551        };
552        if names.iter().any(|entry| entry == name) {
553            terminals.push(current);
554            return Ok(());
555        }
556        let mut aliases: Vec<&str> = Vec::new();
557        for entry in names {
558            if let Some((alias, base)) = split_qualified(entry)
559                && base == name
560                && !aliases.contains(&alias)
561            {
562                aliases.push(alias);
563            }
564        }
565        if aliases.is_empty() {
566            if chain.is_empty() {
567                return Err(ForwardError::Unknown {
568                    original: original.to_string(),
569                });
570            }
571            let hop = chain.last().expect("chain never empty").clone();
572            let detail = match view.binding(current.as_str(), name) {
573                BindingPresence::Const => BrokenDetail::UnexportedConst,
574                BindingPresence::Let => BrokenDetail::Let,
575                BindingPresence::Absent => BrokenDetail::Absent,
576            };
577            return Err(ForwardError::Broken {
578                original: original.to_string(),
579                hop,
580                detail,
581            });
582        }
583        if aliases.len() > 1 {
584            let mut hops: Vec<String> = aliases.iter().map(|alias| qualify(alias, name)).collect();
585            hops.sort();
586            return Err(ForwardError::Split {
587                original: original.to_string(),
588                hops,
589            });
590        }
591        let forward = aliases[0];
592        let hop = qualify(forward, name);
593        if chain.contains(&hop) {
594            chain.push(hop);
595            return Err(ForwardError::Cycle {
596                chain: chain.clone(),
597            });
598        }
599        chain.push(hop.clone());
600        let targets = view.alias_targets(current.as_str());
601        match classify_alias_call(&targets, &hop, &covering) {
602            AliasResolution::Global | AliasResolution::Unknown => {
603                return Err(ForwardError::Broken {
604                    original: original.to_string(),
605                    hop,
606                    detail: BrokenDetail::Absent,
607                });
608            }
609            AliasResolution::Ambiguous { alias, base, files } => {
610                return Err(ForwardError::HopAmbiguous { alias, base, files });
611            }
612            AliasResolution::Canonical(canonical) => {
613                let Some(next) = canonical.strip_suffix(suffix.as_str()) else {
614                    return Err(ForwardError::Unknown {
615                        original: original.to_string(),
616                    });
617                };
618                current = next.to_string();
619            }
620            AliasResolution::Any { mut files, .. } => {
621                let mut covering: Vec<String> = files
622                    .drain()
623                    .filter(|file| {
624                        view.const_exports(file).is_some_and(|names| {
625                            names.iter().any(|entry| const_export_covers(entry, name))
626                        })
627                    })
628                    .collect();
629                covering.sort();
630                match covering.len() {
631                    0 => {
632                        return Err(ForwardError::Broken {
633                            original: original.to_string(),
634                            hop,
635                            detail: BrokenDetail::Absent,
636                        });
637                    }
638                    1 => {
639                        current = covering.into_iter().next().expect("len checked");
640                    }
641                    _ => {
642                        for branch in covering {
643                            let mut branch_chain = chain.clone();
644                            chase_from(
645                                view,
646                                branch.as_str(),
647                                name,
648                                original,
649                                &mut branch_chain,
650                                terminals,
651                            )?;
652                        }
653                        return Ok(());
654                    }
655                }
656            }
657        }
658    }
659}
660/// Whether a disjoint-alias template call names a script function,
661/// owned here so every placeholder path agrees with `resolve_call`:
662/// visible only when no host-harvest branch competes (`!has_host`)
663/// and **every** candidate file defines `base` (universal, not
664/// existential: a missing branch fails the `LET` path, so the
665/// template must not suggest it). `exists` probes canonical
666/// file-function keys for script definitions.
667pub(super) fn disjoint_template_script_visible(
668    base: &str,
669    files: &HashSet<String>,
670    has_host: bool,
671    exists: &dyn Fn(&str) -> bool,
672) -> bool {
673    !has_host && !files.is_empty() && files.iter().all(|file| exists(&file_func_key(file, base)))
674}
675
676/// Miss wording for a disjoint-alias placeholder call, shared by the
677/// static gate, the lazy runtime path, and (via the script set) the
678/// EXPAND snapshot. Script-visible branches read as script misses
679/// (the `LET` path); otherwise the alias is known but holds no
680/// callable function here. Always renders: `Any` only arises for a
681/// known alias, so the generic unknown wording never applies.
682pub(super) fn disjoint_alias_placeholder_miss(
683    module: &str,
684    name: &str,
685    base: &str,
686    files: &HashSet<String>,
687    has_host: bool,
688    is_script: &dyn Fn(&str) -> bool,
689) -> String {
690    let script = disjoint_template_script_visible(base, files, has_host, is_script);
691    describe_placeholder_miss(module, name, script, false, !script)
692        .expect("disjoint miss always renders")
693}
694
695/// Every local spelling of one defining file's function in a unit.
696/// Inverted direction of [`classify_alias_call`]; shares its matcher.
697/// `is_script` probes the caller's registry for script bodies, so
698/// disjoint platform aliases covering every branch with a script
699/// definition read as direct spellings (matching the static gate and
700/// the lazy path through [`disjoint_alias_placeholder_miss`]).
701pub(super) fn spellings_for_defining_file(
702    unit_targets: &AliasTargets,
703    defining: &str,
704    base: &str,
705    is_script: &dyn Fn(&str) -> bool,
706) -> (Vec<String>, Vec<(String, HashSet<String>)>) {
707    let mut direct = Vec::new();
708    let mut ambiguous = Vec::new();
709    for (alias, files) in unit_targets {
710        if !files
711            .iter()
712            .any(|(file, _)| file.as_deref() == Some(defining))
713        {
714            continue;
715        }
716        let spelling = qualify(alias, base);
717        match classify_alias_call(unit_targets, &spelling, &|key| {
718            key == file_func_key(defining, base)
719        }) {
720            AliasResolution::Canonical(_) => direct.push(spelling),
721            AliasResolution::Ambiguous { files, .. } => {
722                ambiguous.push((spelling, files));
723            }
724            AliasResolution::Any {
725                base,
726                files,
727                has_host,
728            } => {
729                if disjoint_template_script_visible(&base, &files, has_host, is_script) {
730                    direct.push(spelling);
731                }
732            }
733            AliasResolution::Global | AliasResolution::Unknown => {}
734        }
735    }
736    (direct, ambiguous)
737}
738
739impl FuncKind {
740    pub fn label(&self) -> &'static str {
741        match self {
742            FuncKind::Script => "script",
743            FuncKind::HostCtx | FuncKind::HostPure => "host",
744        }
745    }
746}
747
748/// One declared parameter of a registered function. `param_type` is `None`
749/// for unconstrained `Value` parameters (the macro accepts any value).
750/// `allowed` names the closed value set for constrained `STRING`
751/// parameters, declared once via `#[values(...)]`: the generated
752/// extractor enforces membership and the reference renders the set,
753/// so the list cannot rot apart from the check. `docs` carries the
754/// parameter's description (parsed from the `# Arguments` doc section
755/// for macro functions, written inline for hand-built entries) and
756/// renders into every reference surface. `options` declares the known
757/// keys of a `MAP` options parameter: same single-source rule as
758/// `allowed`, with per-key types, required flags, defaults, and docs.
759/// `optional` marks a trailing `MAP` parameter callers may omit: the
760/// runtime fills an empty MAP, and signatures render `= {}`. Only
761/// trailing `MAP` params may be optional (run-start validation
762/// rejects anything else), so omission always means "no options".
763/// The macro never emits optional params: only hand-built entries
764/// use them, and only for options MAPs.
765#[derive(Debug, Clone)]
766pub struct FuncParam {
767    pub name: String,
768    pub param_type: Option<TypeTag>,
769    pub allowed: Option<&'static [&'static str]>,
770    pub docs: &'static str,
771    pub options: Option<&'static [ParamOption]>,
772    pub optional: bool,
773}
774
775/// Required argument count: total params minus trailing optionals.
776/// Callers may pass any count in `required..=total`; omitted trailing
777/// MAPs fill with an empty MAP. Shared by the static arity gate and
778/// the runtime gate so the two can never disagree.
779pub fn required_arity(params: &[FuncParam]) -> usize {
780    params
781        .iter()
782        .rev()
783        .take_while(|param| param.optional)
784        .fold(params.len(), |count, _| count - 1)
785}
786
787/// Fill omitted trailing optional MAP params with empty MAPs. The
788/// caller guarantees `values.len()` is within
789/// `required_arity(params)..=params.len()`; anything else is a bug,
790/// not a user error, so over- and under-counts panic loudly.
791pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
792    assert!(
793        values.len() <= params.len(),
794        "arity gate must run before fill_optional_args"
795    );
796    assert!(
797        values.len() >= required_arity(params),
798        "arity gate must run before fill_optional_args"
799    );
800    while values.len() < params.len() {
801        values.push(Value::map(BTreeMap::new()));
802    }
803    values
804}
805
806/// One known key of a `MAP` options parameter: name, value type,
807/// whether callers must pass it, the rendered default for optional
808/// keys, and what it controls. Declared once per options parameter
809/// (macro `#[options(...)]` plus the `# Options` doc section, or
810/// inline for hand-built entries) and rendered into signatures,
811/// `DESCRIBE` output, and generated references alike.
812#[derive(Debug, Clone)]
813pub struct ParamOption {
814    pub name: &'static str,
815    pub value: TypeTag,
816    pub required: bool,
817    pub default: Option<&'static str>,
818}
819
820/// Introspectable metadata for one function. Single source for
821/// `DESCRIBE(name)` output and the static function reference. `rpn` names
822/// whether the function also runs on the compiled math path (`true` for
823/// pure functions and opted-in stateful ones); everything runs on the AST
824/// path.
825#[derive(Debug, Clone)]
826pub struct FuncMeta {
827    pub name: String,
828    /// Owning module (`STD` for builtins, `SCRIPT` for DSL definitions,
829    /// the host module name otherwise). `name` is always the qualified
830    /// `MODULE::BASE` form, so listings and `DESCRIBE` never lose origin.
831    pub module: String,
832    pub kind: FuncKind,
833    pub params: Option<Vec<FuncParam>>,
834    pub returns: Option<TypeTag>,
835    pub rpn: bool,
836    pub summary: &'static str,
837    pub docs: &'static str,
838    /// Executable examples, rendered as ```oxdock fences into the
839    /// generated reference and executed by docs_conformance like
840    /// command examples. The single precondition mechanism: the
841    /// returns gate executes these blocks to cover functions blind
842    /// sampling cannot reach.
843    pub examples: &'static [crate::Example],
844}
845
846/// Pure scalar function: no filesystem, no scope, no process access.
847/// Usable from both AST evaluation and compiled RPN math.
848pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;
849
850/// Stateful/IO function with full step context (fs, cwd, envs, vars, pipes).
851pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;
852
853/// Export hook for a DSL function, implemented by `#[oxdock_func]` on a
854/// registration marker. The engine calls `registration()` and never names
855/// a generated symbol.
856pub trait OxDockFn<P: ProcessManager> {
857    /// The registry entry deriving from the Rust signature plus doc
858    /// comments: name, metadata, and entry point, rendered.
859    fn registration() -> HostRegistration<P>;
860}
861
862/// One host-registered function, grouped into a [`HostModule`] and passed
863/// to `Engine::register_module`. Build the entry with the `#[oxdock_func]`-
864/// generated registration marker, or by hand. `Pure` entries run
865/// on both the AST and the compiled RPN math paths; `Stateful` entries run
866/// on the AST path with full step context. `Both` entries carry a stateful
867/// body plus a pure string projection: every context with step IO runs
868/// the body, while `{{ }}` placeholder expansion (which has no step
869/// context) runs the projection.
870pub enum HostRegistration<P: ProcessManager> {
871    Stateful {
872        name: String,
873        meta: FuncMeta,
874        func: NativeFn<P>,
875    },
876    Pure {
877        name: String,
878        meta: FuncMeta,
879        func: PureFn,
880    },
881    Both {
882        name: String,
883        meta: FuncMeta,
884        func: NativeFn<P>,
885        template: PureFn,
886    },
887}
888
889// Manual `Clone` (a derive would demand `P: Clone`): entries share their
890// function pointers through the `Arc`s and deep-copy the metadata.
891impl<P: ProcessManager> Clone for HostRegistration<P> {
892    fn clone(&self) -> Self {
893        match self {
894            HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
895                name: name.clone(),
896                meta: meta.clone(),
897                func: Arc::clone(func),
898            },
899            HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
900                name: name.clone(),
901                meta: meta.clone(),
902                func: Arc::clone(func),
903            },
904            HostRegistration::Both {
905                name,
906                meta,
907                func,
908                template,
909            } => HostRegistration::Both {
910                name: name.clone(),
911                meta: meta.clone(),
912                func: Arc::clone(func),
913                template: Arc::clone(template),
914            },
915        }
916    }
917}
918
919impl<P: ProcessManager> HostRegistration<P> {
920    /// Introspectable metadata for this entry, for documentation tooling
921    /// that reads modules without registering them.
922    pub fn meta(&self) -> &FuncMeta {
923        match self {
924            HostRegistration::Stateful { meta, .. } => meta,
925            HostRegistration::Pure { meta, .. } => meta,
926            HostRegistration::Both { meta, .. } => meta,
927        }
928    }
929}
930
931/// One user-defined function body (`FUNC NAME($p: TYPE, ...): RET { ... }`).
932/// Param and return types resolve to tags at definition time, where the type
933/// directory is in scope; the registry never holds raw type strings.
934/// The flag marks trailing `?` params the caller may omit (filled with
935/// [`optional_zero_value`] at call time).
936#[derive(Debug, Clone)]
937pub(super) struct FuncDefData {
938    pub(super) params: Vec<(String, TypeTag, bool)>,
939    pub(super) return_type: TypeTag,
940    pub(super) return_spelling: String,
941    pub(super) is_async: bool,
942    pub(super) body: Vec<Step>,
943    /// Owning file module (#115, resolved display path): module-owned
944    /// `FUNC`s resolve names against the module's shared store after
945    /// lexical frames miss. `None` for entry/REPL definitions, which
946    /// stay params-only.
947    pub(super) module: Option<String>,
948    /// Definition-site jail (#322): the workspace selection and cwd
949    /// as they stood when this `FUNC` was defined. `Some` for
950    /// definitions executed at file top level (entry or module init);
951    /// `None` for call-time materializations and bodies, which must
952    /// never capture caller ambient (the file fallback applies).
953    pub(super) def_jail: Option<(WorkspaceSelection, GuardedPath)>,
954}
955
956/// Zero value for an omitted trailing optional script param, by
957/// resolved tag. Scalars take falsy empties and collections empty
958/// shapes (mirroring the host optional-`MAP` fill); records qualify
959/// when every field is optional or defaulted (binding fills the
960/// defaults). Handles, pipes, custom types, unions, and the
961/// remaining words have no zero: omitting those fails at definition,
962/// so the caller passes explicitly.
963pub fn optional_zero_value(tag: &TypeTag) -> Result<Value> {
964    match tag {
965        TypeTag::Bool => Ok(Value::bool(false)),
966        TypeTag::String | TypeTag::Any => Ok(Value::string(String::new())),
967        TypeTag::Int => Ok(Value::int(0)),
968        TypeTag::Float => Ok(Value::float(0.0)),
969        TypeTag::List | TypeTag::ListOf(_) => Ok(Value::list(Vec::new())),
970        TypeTag::Map | TypeTag::MapOf(_) => Ok(Value::map(BTreeMap::new())),
971        TypeTag::Record(fields)
972            if fields
973                .iter()
974                .all(|field| field.optional || field.default.is_some()) =>
975        {
976            Ok(Value::map(BTreeMap::new()))
977        }
978        other => anyhow::bail!(
979            "no zero value for {}; omit the `?` or pass the argument explicitly",
980            oxdock_parser::render_structural(other)
981        ),
982    }
983}
984
985/// Resolve script `FUNC` param spellings to tags in one place: tag
986/// resolution, declaration checks, and optional zero-value validation.
987/// All definition paths (direct, static check, file import) funnel
988/// here, so a required-after-optional or zero-less optional fails
989/// identically everywhere instead of drifting by call site.
990pub fn resolve_script_params<P: ProcessManager>(
991    state: &ExecState<P>,
992    func_name: &str,
993    params: &[(String, String, bool)],
994) -> Result<Vec<(String, TypeTag, bool)>> {
995    let mut resolved = Vec::with_capacity(params.len());
996    for (pname, ptype, optional) in params {
997        let clean = pname.trim_start_matches('$').to_string();
998        let tag = state
999            .resolve_tag(ptype)
1000            .map_err(|err| anyhow::anyhow!("function `{func_name}`: {err:#}"))?;
1001        state.check_declaration_tag(&format!("function `{func_name}` param `${clean}`"), &tag)?;
1002        if *optional {
1003            optional_zero_value(&tag).map(|_| ()).map_err(|err| {
1004                anyhow::anyhow!("function `{func_name}` optional param `${clean}`: {err:#}")
1005            })?;
1006        }
1007        resolved.push((clean, tag, *optional));
1008    }
1009    Ok(resolved)
1010}
1011
1012/// Validate already-resolved script param tags: the zero-value gate
1013/// for registry insertion paths that never see spellings.
1014pub fn check_script_param_tags(func_name: &str, params: &[(String, TypeTag, bool)]) -> Result<()> {
1015    for (pname, tag, optional) in params {
1016        if *optional {
1017            optional_zero_value(tag).map(|_| ()).map_err(|err| {
1018                anyhow::anyhow!("function `{func_name}` optional param `${pname}`: {err:#}")
1019            })?;
1020        }
1021    }
1022    Ok(())
1023}
1024
1025/// Executable body behind one registry entry: an interpreted script, a
1026/// pure scalar function, a stateful function with step context, or a
1027/// dual entry whose pure arm serves `{{ }}` placeholders while the ctx
1028/// arm serves every context that carries step IO.
1029pub(super) enum FuncBody<P: ProcessManager> {
1030    Script(FuncDefData),
1031    Pure(PureFn),
1032    Ctx(NativeFn<P>),
1033    Both { pure: PureFn, ctx: NativeFn<P> },
1034}
1035
1036// Manual `Clone` (a derive would demand `P: Clone`).
1037impl<P: ProcessManager> Clone for FuncBody<P> {
1038    fn clone(&self) -> Self {
1039        match self {
1040            FuncBody::Script(def) => FuncBody::Script(def.clone()),
1041            FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
1042            FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
1043            FuncBody::Both { pure, ctx } => FuncBody::Both {
1044                pure: Arc::clone(pure),
1045                ctx: Arc::clone(ctx),
1046            },
1047        }
1048    }
1049}
1050
1051/// One entry in the unified function registry: introspectable metadata
1052/// (mandatory for every entry, backing the pre-evaluation arity gate)
1053/// plus the executable body.
1054pub(super) struct FuncEntry<P: ProcessManager> {
1055    pub(super) meta: FuncMeta,
1056    pub(super) body: FuncBody<P>,
1057}
1058
1059// Manual `Clone` (a derive would demand `P: Clone`).
1060impl<P: ProcessManager> Clone for FuncEntry<P> {
1061    fn clone(&self) -> Self {
1062        Self {
1063            meta: self.meta.clone(),
1064            body: self.body.clone(),
1065        }
1066    }
1067}
1068
1069/// Names defined in one lexical scope frame: `defined` rejects duplicates
1070/// in the same scope, `shadowed` restores outer definitions on exit.
1071struct ScopeFrame<P: ProcessManager> {
1072    defined: HashSet<String>,
1073    shadowed: Vec<(String, FuncEntry<P>)>,
1074}
1075
1076// Manual `Clone` (a derive would demand `P: Clone`).
1077impl<P: ProcessManager> Clone for ScopeFrame<P> {
1078    fn clone(&self) -> Self {
1079        Self {
1080            defined: self.defined.clone(),
1081            shadowed: self.shadowed.clone(),
1082        }
1083    }
1084}
1085
1086/// The single function registry: DSL `FUNC` definitions, builtins, and
1087/// host extensions share one lookup table, one metadata path, and one
1088/// dispatch order. Script entries scope lexically (defined names revert on
1089/// scope exit, shadowing an outer definition restores it); native entries
1090/// persist for the run. Shared across `fork()` via clone; the entry maps
1091/// clone while scope frames stay per state.
1092/// Module to function-name table of pure entries, shared by reference.
1093/// Nested so placeholder dispatch looks up `table[module][func]` with
1094/// zero allocation; rebuilt only when native entries register.
1095pub type PureTable = HashMap<String, HashMap<String, PureFn>>;
1096
1097/// Shared `{{ MODULE::FUNC(args) }}` dispatch over a pure-function table.
1098///
1099/// Single implementation for every expansion path (script `EXPAND`,
1100/// string interpolation, host-driven fragment expansion): nested
1101/// module then function lookup with zero allocation, unknown names
1102/// failing with the sorted known-functions listing. Callers keep
1103/// their own arg resolution and output handling; only dispatch and
1104/// its error shape live here.
1105pub fn placeholder_resolver(table: Arc<PureTable>) -> oxdock_process::PlaceholderCall {
1106    Arc::new(move |module, func, args| {
1107        let callee = table
1108            .get(module)
1109            .and_then(|entries| entries.get(func))
1110            .ok_or_else(|| {
1111                let mut known: Vec<String> = table
1112                    .iter()
1113                    .flat_map(|(m, entries)| entries.keys().map(move |f| format!("{m}::{f}")))
1114                    .collect();
1115                known.sort();
1116                anyhow::anyhow!(
1117                    "unknown placeholder function '{module}::{func}'; known functions: {}",
1118                    known.join(", ")
1119                )
1120            })?;
1121        callee(args)
1122    })
1123}
1124
1125/// Descriptive `{{ MODULE::FUNC }}` miss wording, shared by the static
1126/// gate and the runtime fallbacks: known callees are never called
1127/// "unknown". Returns `None` when the callee is genuinely unknown
1128/// everywhere (callers keep the unknown-function diagnostic with its
1129/// known-functions listing). `{{ }}` runs without step context, so
1130/// the fix always routes through a prior `LET` binding.
1131pub(super) fn describe_placeholder_miss(
1132    module: &str,
1133    name: &str,
1134    is_script: bool,
1135    is_stateful: bool,
1136    alias_known: bool,
1137) -> Option<String> {
1138    let qualified = qualify(module, name);
1139    if is_script {
1140        let call = if module == SCRIPT_MODULE_NAME {
1141            format!("{name}(...)")
1142        } else {
1143            format!("{qualified}(...)")
1144        };
1145        return Some(format!(
1146            "placeholder function '{qualified}' is a script function and cannot run in {{{{ }}}}; bind the result first with LET $v = {call} then interpolate {{{{ $v }}}}"
1147        ));
1148    }
1149    if is_stateful {
1150        return Some(format!(
1151            "placeholder function '{qualified}' is stateful and cannot run in {{{{ }}}}; capture it first with LET then interpolate {{{{ $v }}}}"
1152        ));
1153    }
1154    if alias_known {
1155        return Some(format!(
1156            "placeholder function '{qualified}': no function '{name}' under file alias '{module}'; check the file's EXPORT list and the IMPORT harvest, or bind a known function first with LET then interpolate {{{{ $v }}}}"
1157        ));
1158    }
1159    None
1160}
1161
1162/// Owned placeholder classes for `'static` closures (notably
1163/// `EXPAND` streaming), which cannot borrow the registry.
1164pub(super) struct PlaceholderClasses {
1165    pub script: HashSet<String>,
1166    pub stateful: HashSet<String>,
1167    pub aliases: HashSet<String>,
1168    /// Ambiguous spellings: alias resolves to several files.
1169    pub ambiguous: HashMap<String, HashSet<String>>,
1170}
1171
1172impl PlaceholderClasses {
1173    pub(super) fn describe(&self, module: &str, name: &str) -> Option<String> {
1174        let qualified = qualify(module, name);
1175        if let Some(files) = self.ambiguous.get(&qualified) {
1176            return Some(ambiguous_alias_message(module, name, files));
1177        }
1178        describe_placeholder_miss(
1179            module,
1180            name,
1181            self.script.contains(&qualified),
1182            self.stateful.contains(&qualified),
1183            self.aliases.contains(module),
1184        )
1185    }
1186}
1187
1188pub struct FunctionRegistry<P: ProcessManager> {
1189    entries: HashMap<String, FuncEntry<P>>,
1190    scopes: Vec<ScopeFrame<P>>,
1191    pure_shared: Arc<PureTable>,
1192    /// Script `#` doc comments keyed by qualified `SCRIPT::NAME`.
1193    /// Populated by the MCP host after linear execution; the tool
1194    /// table reads these with fallback to `FuncMeta` summary.
1195    script_docs: HashMap<String, (String, String)>,
1196}
1197
1198impl<P: ProcessManager> FunctionRegistry<P> {
1199    pub(super) fn with_builtins() -> Self {
1200        let mut reg = Self {
1201            entries: HashMap::new(),
1202            pure_shared: Arc::new(HashMap::new()),
1203            script_docs: HashMap::new(),
1204            scopes: vec![ScopeFrame {
1205                defined: HashSet::new(),
1206                shadowed: Vec::new(),
1207            }],
1208        };
1209        // Every builtin registers through the same `HostRegistration`
1210        // entries hosts use: no separate authoring path for engine natives.
1211        // Builtins land in the `STD` module, exactly like a host module.
1212        for host in Self::builtin_registrations() {
1213            match host {
1214                HostRegistration::Stateful { name, meta, func } => {
1215                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
1216                }
1217                HostRegistration::Pure { name, meta, func } => {
1218                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
1219                }
1220                HostRegistration::Both {
1221                    name,
1222                    meta,
1223                    func,
1224                    template,
1225                } => {
1226                    reg.insert_qualified(
1227                        STD_MODULE_NAME,
1228                        name,
1229                        meta,
1230                        FuncBody::Both {
1231                            pure: template,
1232                            ctx: func,
1233                        },
1234                    );
1235                }
1236            }
1237        }
1238        reg
1239    }
1240
1241    /// All builtins as host-style registrations, built from the same
1242    /// `#[oxdock_func]`-generated markers hosts use. `with_builtins`
1243    /// consumes this list, so builtins and hosts share one registration
1244    /// pathway instead of two authoring models.
1245    pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
1246        vec![
1247            Int::registration(),
1248            Float::registration(),
1249            BoolConvert::registration(),
1250            BoolOr::registration(),
1251            FormatByteCount::registration(),
1252            ParseByteCount::registration(),
1253            FormatDuration::registration(),
1254            ParseDuration::registration(),
1255            Types::registration(),
1256            TypeDescribe::registration(),
1257            Glob::registration(),
1258            LoadToml::registration(),
1259            LoadJson::registration(),
1260            HashSha256::registration(),
1261            Cwd::registration(),
1262            ParseToml::registration(),
1263            ParseJson::registration(),
1264            PathType::registration(),
1265            PathWritable::registration(),
1266            IsExec::registration(),
1267            IsFile::registration(),
1268            IsDir::registration(),
1269            Exists::registration(),
1270            HasKey::registration(),
1271            Get::registration(),
1272            MapSet::registration(),
1273            MergeMaps::registration(),
1274            Base64Encode::registration(),
1275            Base64Decode::registration(),
1276            Rand::registration(),
1277            ToJson::registration(),
1278            TypeOf::registration(),
1279            Functions::registration(),
1280            Describe::registration(),
1281            IsMain::registration(),
1282            IsTerminal::registration(),
1283            Eof::registration(),
1284            TaskPoll::registration(),
1285            Version::registration(),
1286            Interpreter::registration(),
1287            Argv::registration(),
1288            ParseArgs::registration(),
1289            ParseFlags::registration(),
1290            ParsePositionals::registration(),
1291            TextTrim::registration(),
1292            TextTrimPrefix::registration(),
1293            TextTrimSuffix::registration(),
1294            PathJoin::registration(),
1295            PathBase::registration(),
1296            PathRel::registration(),
1297            TextToUpper::registration(),
1298            TextToLower::registration(),
1299            TextReplace::registration(),
1300            TextReplaceRegex::registration(),
1301            TextSplit::registration(),
1302            TextJoin::registration(),
1303            TextLines::registration(),
1304            TextFields::registration(),
1305            TextMatch::registration(),
1306            TextExtract::registration(),
1307            TextStartsWith::registration(),
1308            TextEndsWith::registration(),
1309            Contains::registration(),
1310            Unique::registration(),
1311            Len::registration(),
1312            TextCount::registration(),
1313            TextCountMatches::registration(),
1314            TextGrep::registration(),
1315            TextLinesRange::registration(),
1316            SemaphoreNew::registration(),
1317            SemaphoreTryAcquire::registration(),
1318            SemaphoreAvailable::registration(),
1319            ShellSplitArgs::registration(),
1320            ShellJoinArgs::registration(),
1321        ]
1322    }
1323
1324    /// Every name the registry answers to. Backs parse-time shadow
1325    /// validation through `builtin_function_names`.
1326    pub(super) fn keys(&self) -> HashSet<String> {
1327        self.entries.keys().cloned().collect()
1328    }
1329
1330    /// Single lookup for every callable: script, pure, or stateful.
1331    pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
1332        self.entries.get(name).cloned()
1333    }
1334
1335    /// Number of live function scope frames. Callers record this as
1336    /// their frame floor so nested lookup stays within the current
1337    /// call (or init), never reaching caller frames.
1338    pub(super) fn scope_depth(&self) -> usize {
1339        self.scopes.len()
1340    }
1341
1342    /// Frame-2..N lookup (#322): innermost scope frame at or above
1343    /// `floor` defining `SCRIPT::BASE`, innermost first. The live
1344    /// slot always holds the innermost defining frame's value
1345    /// (save/restore discipline), so a hit here is definitionally
1346    /// lexical: nested defs shadow everything below them with no
1347    /// owner tags consulted. Cross-unit exclusion comes from the
1348    /// caller choosing `floor` (call/init boundary), never from
1349    /// inspecting whose definition was found.
1350    pub(super) fn get_scoped(&self, base: &str, floor: usize) -> Option<FuncEntry<P>> {
1351        let qualified = qualify(SCRIPT_MODULE_NAME, base);
1352        let len = self.scopes.len();
1353        let start = floor.min(len);
1354        for frame in self.scopes[start..].iter().rev() {
1355            if frame.defined.contains(&qualified) {
1356                return self.entries.get(&qualified).cloned();
1357            }
1358        }
1359        None
1360    }
1361
1362    /// Single lazy miss classifier for runtime placeholder paths with
1363    /// registry access: one borrow, no `FuncEntry` clones, invoked only
1364    /// on resolver failure. Classification runs first (matching
1365    /// `exported_metas`); the shared body helper below owns the
1366    /// `Script`/`Ctx` wording, so the match appears once.
1367    pub(super) fn describe_unit_placeholder_miss(
1368        &self,
1369        unit_targets: &AliasTargets,
1370        module: &str,
1371        name: &str,
1372    ) -> Option<String> {
1373        let qualified = qualify(module, name);
1374        // File-aliased spellings classify through the shared matcher.
1375        // A canonical miss means the alias is known but holds no such
1376        // function; disjoint aliases share the static owner's verdict
1377        // (script-visible branches read as script misses).
1378        match classify_alias_call(unit_targets, &qualified, &|key| {
1379            self.entries.contains_key(key)
1380        }) {
1381            AliasResolution::Canonical(canonical) => {
1382                if let Some(entry) = self.entries.get(&canonical) {
1383                    if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1384                        return Some(miss);
1385                    }
1386                    None
1387                } else {
1388                    describe_placeholder_miss(module, name, false, false, true)
1389                }
1390            }
1391            AliasResolution::Global => {
1392                if let Some(entry) = self.entries.get(&qualified) {
1393                    // `SCRIPT` and host spellings resolve globally;
1394                    // canonical file keys never match a call-site
1395                    // spelling.
1396                    if let Some(miss) = Self::placeholder_miss_for_body(module, name, &entry.body) {
1397                        return Some(miss);
1398                    }
1399                }
1400                None
1401            }
1402            AliasResolution::Ambiguous { files, .. } => {
1403                Some(ambiguous_alias_message(module, name, &files))
1404            }
1405            AliasResolution::Unknown => describe_placeholder_miss(module, name, false, false, true),
1406            // Disjoint aliases share the static owner's verdict through
1407            // the single miss helper, so lazy inline expansion agrees
1408            // with the static gate word for word (script-visible
1409            // branches read as script misses, the rest as known-alias
1410            // misses, never the generic unknown wording).
1411            AliasResolution::Any {
1412                base,
1413                files,
1414                has_host,
1415            } => Some(disjoint_alias_placeholder_miss(
1416                module,
1417                name,
1418                &base,
1419                &files,
1420                has_host,
1421                &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1422            )),
1423        }
1424    }
1425
1426    /// Single owner for the `FuncBody` miss wording: script and
1427    /// stateful bodies report their kind, template-capable bodies
1428    /// (`Pure`/`Both`) report no miss.
1429    fn placeholder_miss_for_body(module: &str, name: &str, body: &FuncBody<P>) -> Option<String> {
1430        match body {
1431            FuncBody::Script(_) => describe_placeholder_miss(module, name, true, false, false),
1432            FuncBody::Ctx(_) => describe_placeholder_miss(module, name, false, true, false),
1433            FuncBody::Pure(_) | FuncBody::Both { .. } => None,
1434        }
1435    }
1436
1437    /// Owned snapshot for `'static` placeholder closures (notably
1438    /// `EXPAND` streaming): the resolver closure cannot borrow the
1439    /// registry, so these name sets are the minimal owned form.
1440    pub(super) fn placeholder_snapshot(&self, unit_targets: &AliasTargets) -> PlaceholderClasses {
1441        let mut script = HashSet::new();
1442        let mut stateful = HashSet::new();
1443        let mut ambiguous: HashMap<String, HashSet<String>> = HashMap::new();
1444        for (key, entry) in self.entries.iter() {
1445            let Some((module, base)) = split_qualified(key) else {
1446                continue;
1447            };
1448            match &entry.body {
1449                FuncBody::Script(def) => {
1450                    if module == SCRIPT_MODULE_NAME {
1451                        // `SCRIPT` and bare-harvest spellings stay global.
1452                        script.insert(key.clone());
1453                        continue;
1454                    }
1455                    // Canonical file key: every local spelling in this
1456                    // unit, singletons (plus disjoint platform branches
1457                    // covered everywhere by script definitions) into
1458                    // the script set and several files into the
1459                    // ambiguity map, through the shared matcher so
1460                    // `describe` matches call sites exactly like the
1461                    // static gate and lazy path.
1462                    let defining = def.module.as_deref().unwrap_or(module);
1463                    let (direct, ambiguous_here) = spellings_for_defining_file(
1464                        unit_targets,
1465                        defining,
1466                        base,
1467                        &|key| matches!(self.entries.get(key), Some(entry) if matches!(entry.body, FuncBody::Script(_))),
1468                    );
1469                    script.extend(direct);
1470                    for (spelling, files) in ambiguous_here {
1471                        ambiguous.entry(spelling).or_default().extend(files);
1472                    }
1473                }
1474                FuncBody::Ctx(_) => {
1475                    stateful.insert(key.clone());
1476                }
1477                FuncBody::Pure(_) | FuncBody::Both { .. } => {}
1478            }
1479        }
1480        let aliases = unit_targets.keys().cloned().collect();
1481        PlaceholderClasses {
1482            script,
1483            stateful,
1484            aliases,
1485            ambiguous,
1486        }
1487    }
1488
1489    fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
1490        self.entries.insert(name, FuncEntry { meta, body });
1491        self.rebuild_pure_shared();
1492    }
1493
1494    /// Rebuild the shared pure table. Runs only on native insertion:
1495    /// script definitions insert `Script` bodies directly and never
1496    /// affect the pure set, so this stays correct between rebuilds.
1497    /// Dual entries contribute their template arm, which is what
1498    /// `{{ }}` placeholder expansion resolves.
1499    fn rebuild_pure_shared(&mut self) {
1500        let mut table: PureTable = HashMap::new();
1501        for (name, entry) in &self.entries {
1502            let func = match &entry.body {
1503                FuncBody::Pure(func) => func,
1504                FuncBody::Both { pure, .. } => pure,
1505                FuncBody::Script(_) | FuncBody::Ctx(_) => continue,
1506            };
1507            if let Some((module, base)) = split_qualified(name) {
1508                table
1509                    .entry(module.to_string())
1510                    .or_default()
1511                    .insert(base.to_string(), Arc::clone(func));
1512            }
1513        }
1514        self.pure_shared = Arc::new(table);
1515    }
1516
1517    /// Insert under `MODULE::BASE`, stamping provenance on the metadata.
1518    /// The single choke point for every registry entry: builtins pass
1519    /// `STD`, hosts pass their module, scripts pass `SCRIPT`.
1520    fn insert_qualified(
1521        &mut self,
1522        module: &str,
1523        base: String,
1524        mut meta: FuncMeta,
1525        body: FuncBody<P>,
1526    ) {
1527        meta.name = qualify(module, &base);
1528        meta.module = module.to_string();
1529        // Last-write-wins would silently reroute calls, so a repeated
1530        // qualified name is a programmer error, never a shadow: panic like
1531        // conflicting type registrations do. `SCRIPT` definitions bypass
1532        // this path (`define_script` owns their scoped shadowing).
1533        if self.entries.contains_key(&meta.name) {
1534            panic!("duplicate function registration `{}`", meta.name);
1535        }
1536        self.insert_native(meta.name.clone(), meta, body);
1537    }
1538
1539    pub(super) fn register_host(
1540        &mut self,
1541        module: &str,
1542        name: String,
1543        mut meta: FuncMeta,
1544        func: NativeFn<P>,
1545    ) {
1546        meta.kind = FuncKind::HostCtx;
1547        self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
1548    }
1549
1550    pub(super) fn register_pure_host(
1551        &mut self,
1552        module: &str,
1553        name: String,
1554        mut meta: FuncMeta,
1555        func: PureFn,
1556    ) {
1557        meta.kind = FuncKind::HostPure;
1558        self.insert_qualified(module, name, meta, FuncBody::Pure(func));
1559    }
1560
1561    pub(super) fn register_both_host(
1562        &mut self,
1563        module: &str,
1564        name: String,
1565        mut meta: FuncMeta,
1566        func: NativeFn<P>,
1567        template: PureFn,
1568    ) {
1569        meta.kind = FuncKind::HostCtx;
1570        self.insert_qualified(
1571            module,
1572            name,
1573            meta,
1574            FuncBody::Both {
1575                pure: template,
1576                ctx: func,
1577            },
1578        );
1579    }
1580
1581    /// Define a DSL `FUNC`: names colliding with any known base name cannot
1582    /// shadow, same-scope duplicates cannot redefine, and nested shadowing
1583    /// of an outer script definition restores on scope exit. Stored as
1584    /// `SCRIPT::NAME`, exactly like every other qualified entry.
1585    #[allow(clippy::too_many_arguments)]
1586    pub(super) fn define_script(
1587        &mut self,
1588        name: &str,
1589        params: &[(String, TypeTag, bool)],
1590        return_type: TypeTag,
1591        return_spelling: &str,
1592        is_async: bool,
1593        body: &[Step],
1594        module: Option<&str>,
1595        def_jail: Option<(WorkspaceSelection, GuardedPath)>,
1596    ) -> Result<()> {
1597        let qualified = qualify(SCRIPT_MODULE_NAME, name);
1598        let shadowable = matches!(
1599            self.entries.get(&qualified).map(|entry| &entry.body),
1600            Some(FuncBody::Script(_))
1601        );
1602        // Reserved spans every module: compare base names so the message
1603        // keeps naming the bare script identifier. Script-defined entries
1604        // (including `ALIAS::NAME` file imports, #115) never reserve: only
1605        // native/host bodies are unshadowable.
1606        let reserved = self.entries.iter().any(|(key, entry)| {
1607            split_qualified(key).is_some_and(|(_, base)| base == name)
1608                && !matches!(entry.body, FuncBody::Script(_))
1609        });
1610        if reserved && !shadowable {
1611            anyhow::bail!("cannot shadow reserved function `{name}`");
1612        }
1613        if self
1614            .scopes
1615            .last()
1616            .is_some_and(|frame| frame.defined.contains(&qualified))
1617        {
1618            anyhow::bail!("duplicate function `{name}` in same scope");
1619        }
1620        check_script_param_tags(name, params)?;
1621        let old = self.entries.insert(
1622            qualified.clone(),
1623            FuncEntry {
1624                meta: FuncMeta {
1625                    name: qualified.clone(),
1626                    module: SCRIPT_MODULE_NAME.to_string(),
1627                    kind: FuncKind::Script,
1628                    params: Some(
1629                        params
1630                            .iter()
1631                            .map(|(pname, param_type, optional)| {
1632                                Ok(FuncParam {
1633                                    name: pname.clone(),
1634                                    param_type: Some(param_type.clone()),
1635                                    allowed: None,
1636                                    // Script `FUNC` params carry no prose:
1637                                    // declarations have no doc syntax.
1638                                    docs: "",
1639                                    options: None,
1640                                    optional: *optional,
1641                                })
1642                            })
1643                            .collect::<Result<_>>()?,
1644                    ),
1645                    returns: Some(return_type.clone()),
1646                    rpn: false,
1647                    summary: "DSL-defined function.",
1648                    docs: "Defined via FUNC in script.",
1649                    examples: &[],
1650                },
1651                body: FuncBody::Script(FuncDefData {
1652                    params: params.to_vec(),
1653                    return_type,
1654                    return_spelling: return_spelling.to_string(),
1655                    is_async,
1656                    body: body.to_vec(),
1657                    module: module.map(|m| m.to_string()),
1658                    def_jail,
1659                }),
1660            },
1661        );
1662        if let Some(frame) = self.scopes.last_mut() {
1663            frame.defined.insert(qualified.clone());
1664            if let Some(old) = old {
1665                frame.shadowed.push((qualified, old));
1666            }
1667        }
1668        Ok(())
1669    }
1670
1671    /// Define a file-imported DSL `FUNC` under its canonical key
1672    /// ([`file_func_key`]: defining file plus base name, never the
1673    /// importer alias) in the global registry frame (index 0, never
1674    /// popped): eviction on scope exit would strand the module cache
1675    /// and alias targets that still reference it.
1676    #[allow(clippy::too_many_arguments)]
1677    pub(super) fn define_file_func(
1678        &mut self,
1679        name: &str,
1680        params: &[(String, TypeTag, bool)],
1681        return_type: TypeTag,
1682        return_spelling: &str,
1683        is_async: bool,
1684        body: &[Step],
1685        defining: &str,
1686    ) -> Result<()> {
1687        // The importer alias selects the defining file at dispatch;
1688        // the key itself names the defining file so units never share
1689        // entries.
1690        let qualified = file_func_key(defining, name);
1691        let shadowable = matches!(
1692            self.entries.get(&qualified).map(|entry| &entry.body),
1693            Some(FuncBody::Script(_))
1694        );
1695        // Reserved spans every module: compare base names so the message
1696        // keeps naming the bare script identifier. Script-defined entries
1697        // never reserve: only native/host bodies are unshadowable.
1698        let reserved = self.entries.iter().any(|(key, entry)| {
1699            split_qualified(key).is_some_and(|(_, base)| base == name)
1700                && !matches!(entry.body, FuncBody::Script(_))
1701        });
1702        if reserved && !shadowable {
1703            anyhow::bail!("cannot shadow reserved function `{name}`");
1704        }
1705        // File entries live in the global frame (index 0, never
1706        // popped): eviction on scope exit would strand the module
1707        // cache and alias targets that still reference them.
1708        let frame_idx = 0;
1709        if self
1710            .scopes
1711            .get(frame_idx)
1712            .is_some_and(|frame| frame.defined.contains(&qualified))
1713        {
1714            anyhow::bail!("duplicate function `{name}` in same scope");
1715        }
1716        check_script_param_tags(name, params)?;
1717        let old = self.entries.insert(
1718            qualified.clone(),
1719            FuncEntry {
1720                meta: FuncMeta {
1721                    name: qualified.clone(),
1722                    module: defining.to_string(),
1723                    kind: FuncKind::Script,
1724                    params: Some(
1725                        params
1726                            .iter()
1727                            .map(|(pname, param_type, optional)| {
1728                                Ok(FuncParam {
1729                                    name: pname.clone(),
1730                                    param_type: Some(param_type.clone()),
1731                                    allowed: None,
1732                                    docs: "",
1733                                    options: None,
1734                                    optional: *optional,
1735                                })
1736                            })
1737                            .collect::<Result<_>>()?,
1738                    ),
1739                    returns: Some(return_type.clone()),
1740                    rpn: false,
1741                    summary: "DSL-defined function.",
1742                    docs: "Defined via FUNC in an imported script.",
1743                    examples: &[],
1744                },
1745                body: FuncBody::Script(FuncDefData {
1746                    params: params.to_vec(),
1747                    return_type,
1748                    return_spelling: return_spelling.to_string(),
1749                    is_async,
1750                    body: body.to_vec(),
1751                    module: Some(defining.to_string()),
1752                    // Harvest registration never captures a jail: it
1753                    // runs in the importer context, so capturing here
1754                    // would leak caller ambient into the defining
1755                    // file. The file fallback applies at call time.
1756                    def_jail: None,
1757                }),
1758            },
1759        );
1760        if let Some(frame) = self.scopes.get_mut(frame_idx) {
1761            frame.defined.insert(qualified.clone());
1762            if let Some(old) = old {
1763                frame.shadowed.push((qualified, old));
1764            }
1765        }
1766        Ok(())
1767    }
1768
1769    /// Backfill a definition-site jail onto an import-registered
1770    /// canonical entry (#322). Imports register canonical slots
1771    /// before init runs, so they start jail-less; the first
1772    /// top-level definition seals them exactly once, mirroring the
1773    /// file frame. Later definitions never overwrite. Harvest-only
1774    /// registrations stay `None`: without init there is no
1775    /// definition site to seal.
1776    pub(super) fn seal_canonical_jail(
1777        &mut self,
1778        canonical: &str,
1779        jail: (WorkspaceSelection, GuardedPath),
1780    ) {
1781        if let Some(entry) = self.entries.get_mut(canonical)
1782            && let FuncBody::Script(def) = &mut entry.body
1783            && def.def_jail.is_none()
1784        {
1785            def.def_jail = Some(jail);
1786        }
1787    }
1788
1789    /// Open a lexical scope frame for script definitions. Native entries
1790    /// persist; only script names track here.
1791    pub(super) fn push_scope(&mut self) {
1792        self.scopes.push(ScopeFrame {
1793            defined: HashSet::new(),
1794            shadowed: Vec::new(),
1795        });
1796    }
1797
1798    /// Close a lexical scope frame: names defined inside revert, and any
1799    /// outer definition they shadowed is restored.
1800    pub(super) fn pop_scope(&mut self) {
1801        let Some(frame) = self.scopes.pop() else {
1802            return;
1803        };
1804        for name in frame.defined {
1805            self.entries.remove(&name);
1806        }
1807        for (name, old) in frame.shadowed {
1808            self.entries.insert(name, old);
1809        }
1810    }
1811
1812    /// Registry lookup key for a runtime call-site spelling, through
1813    /// the shared alias-target matcher.
1814    pub(super) fn resolve_file_call_key(
1815        &self,
1816        unit_targets: &AliasTargets,
1817        name: &str,
1818    ) -> Result<Option<String>> {
1819        match classify_alias_call(unit_targets, name, &|key| self.entries.contains_key(key)) {
1820            AliasResolution::Global | AliasResolution::Unknown | AliasResolution::Any { .. } => {
1821                Ok(None)
1822            }
1823            AliasResolution::Canonical(key) => Ok(Some(key)),
1824            AliasResolution::Ambiguous { alias, base, files } => Err(anyhow::anyhow!(
1825                "{}",
1826                ambiguous_alias_message(&alias, &base, &files)
1827            )),
1828        }
1829    }
1830
1831    /// Shared snapshot of every pure entry, nested by module and base
1832    /// name. Cloning the `Arc` is refcount-only: placeholder dispatch
1833    /// borrows this per expansion with no map copies.
1834    pub(super) fn pure_shared(&self) -> Arc<PureTable> {
1835        Arc::clone(&self.pure_shared)
1836    }
1837
1838    /// Every entry's metadata, scripts included, sorted by name. Backs
1839    /// run-start type tag validation.
1840    pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
1841        self.entries_metas()
1842    }
1843
1844    fn meta(&self, name: &str) -> Option<FuncMeta> {
1845        self.entries.get(name).map(|entry| entry.meta.clone())
1846    }
1847
1848    fn native_metas(&self) -> Vec<FuncMeta> {
1849        let mut out: Vec<FuncMeta> = Vec::new();
1850        for entry in self.entries.values() {
1851            if !matches!(entry.body, FuncBody::Script(_)) {
1852                out.push(entry.meta.clone());
1853            }
1854        }
1855        out.sort_by(|a, b| a.name.cmp(&b.name));
1856        out
1857    }
1858
1859    /// Metadata for template-capable entries only: `Pure` plus `Both`
1860    /// (dual entries contribute their template arm to `{{ }}`).
1861    /// `Ctx` and `Script` never resolve in placeholder expansion, so
1862    /// the static template gate reads this instead of `all_metas`.
1863    pub(super) fn pure_metas(&self) -> Vec<FuncMeta> {
1864        let mut out: Vec<FuncMeta> = Vec::new();
1865        for entry in self.entries.values() {
1866            if matches!(entry.body, FuncBody::Pure(_) | FuncBody::Both { .. }) {
1867                out.push(entry.meta.clone());
1868            }
1869        }
1870        out.sort_by(|a, b| a.name.cmp(&b.name));
1871        out
1872    }
1873
1874    /// Every entry's metadata, scripts included, sorted by name. Backs
1875    /// runtime `FUNCTIONS()` listings.
1876    fn entries_metas(&self) -> Vec<FuncMeta> {
1877        let mut out: Vec<FuncMeta> = self
1878            .entries
1879            .values()
1880            .map(|entry| entry.meta.clone())
1881            .collect();
1882        out.sort_by(|a, b| a.name.cmp(&b.name));
1883        out
1884    }
1885
1886    /// Install script `#` docs keyed by bare base name. Stored under
1887    /// qualified `SCRIPT::NAME` keys.
1888    pub fn set_script_docs(&mut self, docs: &HashMap<String, (String, String)>) {
1889        for (base, pair) in docs {
1890            self.script_docs
1891                .insert(qualify(SCRIPT_MODULE_NAME, base), pair.clone());
1892        }
1893    }
1894
1895    /// Script doc pair for a qualified name, if the parser collected one.
1896    pub fn script_doc_for(&self, qualified: &str) -> Option<(String, String)> {
1897        self.script_docs.get(qualified).cloned()
1898    }
1899
1900    /// Metadata for single-file `EXPORT` names in source order. Errors
1901    /// name the first missing export; callers fail fast before serving.
1902    /// Qualified names resolve through `resolve_file_call_key`, so
1903    /// re-exported file functions serve under the export spelling.
1904    pub fn exported_metas(
1905        &self,
1906        func_exports: &[String],
1907        unit_targets: &AliasTargets,
1908    ) -> anyhow::Result<Vec<FuncMeta>> {
1909        let mut out = Vec::with_capacity(func_exports.len());
1910        for name in func_exports {
1911            // Bare names are script FUNCs; qualified names resolve
1912            // through the unit's alias targets first, falling back to
1913            // the global spelling for hosts and entry-owned scripts.
1914            let qualified = match split_qualified(name) {
1915                None => qualify(SCRIPT_MODULE_NAME, name),
1916                Some(_) => name.clone(),
1917            };
1918            let lookup = self
1919                .resolve_file_call_key(unit_targets, &qualified)?
1920                .unwrap_or_else(|| qualified.clone());
1921            if let Some(entry) = self.entries.get(&lookup) {
1922                let mut meta = entry.meta.clone();
1923                if lookup != qualified {
1924                    meta.name = name.clone();
1925                }
1926                out.push(meta);
1927                continue;
1928            }
1929            anyhow::bail!(
1930                "EXPORT `{name}` matches no defined script function or known host function"
1931            );
1932        }
1933        Ok(out)
1934    }
1935}
1936
1937impl<P: ProcessManager> Clone for FunctionRegistry<P> {
1938    fn clone(&self) -> Self {
1939        Self {
1940            entries: self.entries.clone(),
1941            scopes: self.scopes.clone(),
1942            pure_shared: Arc::clone(&self.pure_shared),
1943            script_docs: self.script_docs.clone(),
1944        }
1945    }
1946}
1947
1948/// Names of all compiled-in builtins plus `INSPECT` (a dedicated AST/RPN
1949/// node, not a registry entry). Read straight off a stock registry, so the
1950/// `#[oxdock_func]` annotations stay the single source of truth: adding a
1951/// builtin extends this set with no parallel list to update. Seeds
1952/// parse-time shadow validation, so the parser crate keeps zero
1953/// compile-time knowledge of builtin names.
1954pub fn builtin_function_names() -> HashSet<String> {
1955    let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
1956    names.insert(KEYWORD_INSPECT.to_string());
1957    names
1958}
1959
1960/// Metadata of every builtin function, sorted by name, for static
1961/// rendering (oxdock-render). Same single source as `builtin_function_names`:
1962/// the `#[oxdock_func]` annotations, never a parallel list.
1963pub fn builtin_function_metas() -> Vec<FuncMeta> {
1964    FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
1965}
1966
1967/// Stock `STD` module table derived from the `#[oxdock_func]` builtins:
1968/// the single source of truth for builtin membership and RPN eligibility.
1969/// Seeds parse-time module resolution, so the parser crate keeps zero
1970/// compile-time knowledge of builtin names.
1971pub fn std_module_table() -> oxdock_parser::ModuleTable {
1972    // Registry names are qualified (`STD::GLOB`); the table holds bases.
1973    let func_names: HashSet<String> = builtin_function_metas()
1974        .into_iter()
1975        .map(|meta| base_name(&meta.name).to_string())
1976        .collect();
1977    oxdock_parser::ModuleTable {
1978        modules: HashMap::from([(
1979            STD_MODULE_NAME.to_string(),
1980            Some(oxdock_parser::ModuleFuncs { func_names }),
1981        )]),
1982    }
1983}
1984
1985// Builtins below use the `#[oxdock_func]` host export macro, the exact same authoring
1986// model as host-registered functions: metadata, arity checks, and argument
1987// unpacking derive from the signature plus doc comments, so adding a native
1988// means writing one small typed function plus one line each in
1989// `builtin_registrations` (consumed by `with_builtins`) and the
1990// `FUNCTIONS`/`DESCRIBE`/`TYPES` surface, which all read the same symbols.
1991
1992/// Convert a value to INT.
1993///
1994/// Trims ASCII whitespace and parses i64. Passes Int through; Float only
1995/// when integral and finite; Bool as 1/0.
1996///
1997#[oxdock_func(pure, returns = TypeTag::Int)]
1998#[example(
1999    name = "convert",
2000    code = r###"
2001    IMPORT [STD]
2002    LET $n: INT = INT("42")
2003    ASSERT_EQ $n 42
2004    LET $flag: INT = INT(true)
2005    ASSERT_EQ $flag 1
2006    "###
2007)]
2008fn int(
2009    /// Value to convert to `INT`.
2010    #[union(Int, Float, String, Bool)]
2011    val: Value,
2012) -> Result<Value> {
2013    super::args::int_from_value(val)
2014}
2015
2016/// Convert a value to FLOAT.
2017///
2018/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
2019///
2020#[oxdock_func(pure, returns = TypeTag::Float)]
2021#[example(
2022    name = "convert",
2023    code = r###"
2024    IMPORT [STD]
2025    LET $f: FLOAT = FLOAT("1.5")
2026    ASSERT_EQ $f 1.5
2027    LET $whole: FLOAT = FLOAT(2)
2028    ASSERT_EQ $whole 2.0
2029    "###
2030)]
2031fn float(
2032    /// Value to convert to `FLOAT`.
2033    #[union(Float, Int, String)]
2034    val: Value,
2035) -> Result<Value> {
2036    super::args::float_from_value(val)
2037}
2038
2039/// Format a byte count canonically (`500B`, `10KB`, `2MB`, `1GB`,
2040/// binary `10KIB` and friends): the inverse of `PARSE_BYTE_COUNT`, so
2041/// formatted values reparse exactly. Negative inputs fail.
2042///
2043#[oxdock_func(pure, returns = TypeTag::String)]
2044#[example(
2045    name = "format and round-trip",
2046    code = r###"
2047    # Byte counts render in the largest exact unit.
2048    IMPORT [STD]
2049    LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
2050    ASSERT_EQ $pretty "1MiB"
2051
2052    # The pair round-trips through the parser.
2053    LET $back: INT = PARSE_BYTE_COUNT($pretty)
2054    ASSERT_EQ $back 1_048_576
2055    "###
2056)]
2057fn format_byte_count(
2058    /// Byte count to format; negatives fail.
2059    bytes: i64,
2060) -> Result<Value> {
2061    if bytes < 0 {
2062        return Err(anyhow::anyhow!(
2063            "FORMAT_BYTE_COUNT needs a non-negative byte count, got {bytes}"
2064        ));
2065    }
2066    Ok(Value::string(oxdock_parser::command::format_byte_count(
2067        bytes as u64,
2068    )))
2069}
2070
2071/// Parse a byte-count token to `INT` bytes.
2072///
2073/// Bare digits are bytes; suffixes `B`/`KB`/`MB`/`GB`/`TB` scale
2074/// decimal and `KIB`/`MIB`/`GIB`/`TIB` binary, in any case. Plain
2075/// `INT` values pass through (already bytes); integral finite `FLOAT`
2076/// values convert. Pairs with `FORMAT_BYTE_COUNT` for the round trip.
2077///
2078/// ```oxdock
2079/// # Units parse case-insensitively; bare digits are bytes.
2080/// IMPORT [STD]
2081/// LET $bytes: INT = PARSE_BYTE_COUNT("1Gb")
2082/// ASSERT_EQ $bytes 1_000_000_000
2083///
2084/// # Binary suffixes scale by powers of two.
2085/// LET $mebi: INT = PARSE_BYTE_COUNT("2mib")
2086/// ASSERT_EQ $mebi 2_097_152
2087///
2088/// # Digit runs group Rust-literal style.
2089/// LET $grouped: INT = PARSE_BYTE_COUNT("1_000_000")
2090/// ASSERT_EQ $grouped 1_000_000
2091///
2092/// # Plain numbers pass through as bytes already.
2093/// LET $plain: INT = PARSE_BYTE_COUNT(1_048_576)
2094/// ASSERT_EQ $plain 1_048_576
2095///
2096/// # Bare literals group too.
2097/// LET $bare: INT = PARSE_BYTE_COUNT(1_000_000)
2098/// ASSERT_EQ $bare 1_000_000
2099///
2100/// # One optional space separates number from unit.
2101/// LET $spaced: INT = PARSE_BYTE_COUNT("1 GB")
2102/// ASSERT_EQ $spaced 1_000_000_000
2103/// ```
2104///
2105#[oxdock_func(pure, returns = TypeTag::Int)]
2106#[example(
2107    name = "parse",
2108    code = r###"
2109    IMPORT [STD]
2110    LET $n: INT = PARSE_BYTE_COUNT("10KB")
2111    ASSERT_EQ $n 10_000
2112    LET $identity: INT = PARSE_BYTE_COUNT(512)
2113    ASSERT_EQ $identity 512
2114    "###
2115)]
2116fn parse_byte_count(
2117    /// Byte-count token to parse, or bytes already.
2118    #[union(Int, Float, String)]
2119    text: Value,
2120) -> Result<Value> {
2121    if let Some(n) = text.as_i64() {
2122        if n < 0 {
2123            return Err(anyhow::anyhow!(
2124                "PARSE_BYTE_COUNT needs a non-negative byte count, got {n}"
2125            ));
2126        }
2127        return Ok(Value::int(n));
2128    }
2129    if let Some(f) = text.as_f64() {
2130        if f.is_finite() && f.fract() == 0.0 && f >= 0.0 && f <= i64::MAX as f64 {
2131            return Ok(Value::int(f as i64));
2132        }
2133        return Err(anyhow::anyhow!(
2134            "PARSE_BYTE_COUNT needs an integral byte count, got {f:?}"
2135        ));
2136    }
2137    let Some(s) = text.as_str() else {
2138        return Err(anyhow::anyhow!(
2139            "PARSE_BYTE_COUNT needs a token or number, found {text:?}"
2140        ));
2141    };
2142    let n = oxdock_parser::command::parse_byte_count(s)?;
2143    let n = i64::try_from(n)
2144        .map_err(|_| anyhow::anyhow!("PARSE_BYTE_COUNT out of INT range: {s:?}"))?;
2145    Ok(Value::int(n))
2146}
2147
2148/// Format millisecond durations canonically (`500ms`, `10s`, `2m`,
2149/// `1h`): the inverse of `PARSE_DURATION`, so formatted values
2150/// reparse exactly. Negative inputs fail.
2151///
2152#[oxdock_func(pure, returns = TypeTag::String)]
2153#[example(
2154    name = "format and round-trip",
2155    code = r###"
2156    # Durations render in the largest exact unit.
2157    IMPORT [STD]
2158    LET $pretty: STRING = FORMAT_DURATION(90_000)
2159    ASSERT_EQ $pretty "90s"
2160
2161    # The pair round-trips through the parser.
2162    LET $back: INT = PARSE_DURATION($pretty)
2163    ASSERT_EQ $back 90_000
2164    "###
2165)]
2166fn format_duration(
2167    /// Milliseconds to format; negatives fail.
2168    millis: i64,
2169) -> Result<Value> {
2170    if millis < 0 {
2171        return Err(anyhow::anyhow!(
2172            "FORMAT_DURATION needs non-negative milliseconds, got {millis}"
2173        ));
2174    }
2175    Ok(Value::string(oxdock_parser::command::format_duration(
2176        &std::time::Duration::from_millis(millis as u64),
2177    )))
2178}
2179
2180/// Parse a duration token to `INT` milliseconds.
2181///
2182/// Suffixes `ms`/`s`/`m`/`h`; a bare number means seconds. Pairs with
2183/// `FORMAT_DURATION` for the round trip.
2184///
2185#[oxdock_func(pure, returns = TypeTag::Int)]
2186#[example(
2187    name = "parse",
2188    code = r###"
2189    # A bare number means seconds, like TIMEOUT.
2190    IMPORT [STD]
2191    LET $ms: INT = PARSE_DURATION("2m")
2192    ASSERT_EQ $ms 120_000
2193
2194    # Milliseconds stay exact.
2195    LET $exact: INT = PARSE_DURATION("1500ms")
2196    ASSERT_EQ $exact 1_500
2197
2198    # One optional space separates number from unit.
2199    LET $spaced: INT = PARSE_DURATION("1 h")
2200    ASSERT_EQ $spaced 3_600_000
2201    "###
2202)]
2203fn parse_duration(
2204    /// Duration token to parse.
2205    text: String,
2206) -> Result<Value> {
2207    let duration = oxdock_parser::command::parse_duration(&text)?;
2208    let millis = i64::try_from(duration.as_millis())
2209        .map_err(|_| anyhow::anyhow!("PARSE_DURATION out of INT range: {text:?}"))?;
2210    Ok(Value::int(millis))
2211}
2212
2213/// List workspace paths matching a glob pattern.
2214///
2215/// Sorted, root-relative LIST; empty on no match or `..` escape.
2216///
2217#[oxdock_func(rpn, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2218#[example(
2219    name = "match",
2220    code = r###"
2221    IMPORT [STD]
2222    WRITE "notes-a.md" "a"
2223    WRITE "notes-b.md" "b"
2224    WRITE "other.txt" "c"
2225    LET $found: LIST<STRING> = GLOB("notes-*.md")
2226    ASSERT_EQ $found.0 "notes-a.md"
2227    ASSERT_EQ $found.1 "notes-b.md"
2228    "###
2229)]
2230fn glob<P: ProcessManager>(
2231    cx: &mut StepCtx<P>,
2232    /// Glob pattern matched against workspace paths.
2233    #[union(String, Path)]
2234    pattern: Value,
2235) -> Result<Value> {
2236    let text = super::args::string_or_path_text(&pattern)?;
2237    super::args::glob_from_value(&[Value::string(text)], cx)
2238}
2239
2240/// Load and parse a TOML file.
2241///
2242/// Reads a workspace file and parses TOML into a DSL value.
2243///
2244#[oxdock_func(rpn, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2245#[example(
2246    name = "load",
2247    code = r###"
2248    IMPORT [STD]
2249    WRITE "cfg.toml" "title = \"demo\""
2250    LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
2251    ASSERT_EQ $cfg.title "demo"
2252    "###
2253)]
2254fn load_toml<P: ProcessManager>(
2255    cx: &mut StepCtx<P>,
2256    /// Workspace file path to load and parse as TOML.
2257    #[union(String, Path)]
2258    path: Value,
2259) -> Result<Value> {
2260    let text = super::args::string_or_path_text(&path)?;
2261    super::args::load_toml_from_value(&[Value::string(text)], cx)
2262}
2263
2264/// Load and parse a JSON file.
2265///
2266/// Reads a workspace file and parses JSON into a DSL value. Returns
2267/// `ANY` by design: a top-level array or scalar parses to `LIST` or a
2268/// scalar word. `LET` coercion still checks the actual value at
2269/// assignment.
2270///
2271#[oxdock_func(rpn, returns = TypeTag::Any)]
2272#[example(
2273    name = "load",
2274    code = r###"
2275    IMPORT [STD]
2276    WRITE "data.json" "{\"a\": 1}"
2277    LET $doc: MAP<ANY> = LOAD_JSON("data.json")
2278    ASSERT_EQ $doc.a 1
2279    "###
2280)]
2281fn load_json<P: ProcessManager>(
2282    cx: &mut StepCtx<P>,
2283    /// Workspace file path to load and parse as JSON.
2284    #[union(String, Path)]
2285    path: Value,
2286) -> Result<Value> {
2287    let text = super::args::string_or_path_text(&path)?;
2288    super::args::load_json_from_value(&[Value::string(text)], cx)
2289}
2290
2291/// Hash a workspace file or directory with SHA-256.
2292///
2293/// The argument is always a path: reads through the workspace guard
2294/// like the file-loading builtins, so relative paths resolve against
2295/// the script cwd. To hash a literal string's bytes instead, use
2296/// `ASSERT_EQ --hash <digest> <string>`, which hashes the actual
2297/// directly. Returns the 64 lowercase hex chars with no trailing
2298/// newline.
2299///
2300#[oxdock_func(rpn, returns = TypeTag::String)]
2301#[example(
2302    name = "hash",
2303    code = r###"
2304    IMPORT [STD]
2305    WRITE payload.txt hello
2306    LET $digest: STRING = HASH_SHA256("payload.txt")
2307    ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
2308    "###
2309)]
2310fn hash_sha256<P: ProcessManager>(
2311    cx: &mut StepCtx<P>,
2312    /// Workspace file or directory path to hash.
2313    #[union(String, Path)]
2314    path: Value,
2315) -> Result<Value> {
2316    use sha2::Digest;
2317
2318    let text = super::args::string_or_path_text(&path)?;
2319    let target = cx.state.fs.resolve_read(&cx.state.cwd, &text)?;
2320    let mut hasher = sha2::Sha256::new();
2321    super::fs_ops::hash_path(cx.state.fs.as_ref(), &target, "", &mut hasher)?;
2322    let digest = hasher.finalize();
2323    let bytes: &[u8] = digest.as_ref();
2324    Ok(Value::string(oxdock_utils::hex_encode(bytes)))
2325}
2326
2327/// Current working directory as a workspace-absolute path.
2328///
2329/// Returns `STRING` because the result is already resolved: a `PATH`
2330/// value is workspace-relative text awaiting guard checks at use time,
2331/// while this directory is already checked and concrete, or absent
2332/// entirely under a pending snapshot. Compare or display it as text.
2333///
2334/// Reports the snapshot-pending sentinel when no concrete directory
2335/// exists yet, so snapshot scripts keep working unchanged.
2336///
2337#[oxdock_func(rpn, returns = TypeTag::String)]
2338#[example(
2339    name = "cwd",
2340    code = r###"
2341    IMPORT [STD]
2342    WORKDIR sub
2343    LET $c: STRING = CWD()
2344    ASSERT_CONTAINS $c "sub"
2345    "###
2346)]
2347fn cwd<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2348    if cx.state.fs.is_snapshot_pending() {
2349        return Ok(Value::string(super::SNAPSHOT_PENDING_DISPLAY.to_string()));
2350    }
2351    let concrete = cx.state.fs.concretize_cwd(&cx.state.cwd);
2352    let real = super::fs_ops::canonical_cwd(cx.state.fs.as_ref(), &concrete)?;
2353    Ok(Value::string(real))
2354}
2355
2356/// Parse TOML text already held in memory.
2357///
2358/// Uses the same conversion as file loading, so fetch bodies, file
2359/// contents, and captured text share one JSON/TOML shape.
2360///
2361#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2362#[example(
2363    name = "parse",
2364    code = r###"
2365    IMPORT [STD]
2366    LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
2367    ASSERT_EQ $doc.title "demo"
2368    "###
2369)]
2370fn parse_toml(
2371    /// TOML text already held in memory.
2372    text: String,
2373) -> Result<Value> {
2374    super::args::parse_toml_from_value(Value::string(text))
2375}
2376
2377/// Parse JSON text already held in memory.
2378///
2379/// Uses the same conversion as file loading, so fetch bodies, file
2380/// contents, and captured text share one JSON value shape. Returns
2381/// `ANY` by design, matching `LOAD_JSON`: a top-level array or scalar
2382/// parses to `LIST` or a scalar word. `LET` coercion still checks the
2383/// actual value at assignment.
2384///
2385#[oxdock_func(pure, returns = TypeTag::Any)]
2386#[example(
2387    name = "parse",
2388    code = r###"
2389    # Parse in-memory JSON text with the same conversion as file loading.
2390    IMPORT [STD]
2391    LET $body: STRING = "{\"a\": 1}"
2392    LET $doc: ANY = PARSE_JSON($body)
2393    ASSERT_EQ $doc.a 1
2394
2395    # Top-level arrays parse to LIST, which is why the return is ANY.
2396    LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
2397    ASSERT_EQ $items.0 1
2398    ASSERT_EQ $items.1 2
2399    "###
2400)]
2401fn parse_json(
2402    /// JSON text already held in memory.
2403    text: String,
2404) -> Result<Value> {
2405    super::args::parse_json_from_value(Value::string(text))
2406}
2407
2408/// Describe a filesystem entry.
2409///
2410/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
2411/// there is no RPN arm for filesystem IO.
2412///
2413#[oxdock_func(returns = TypeTag::String)]
2414#[example(
2415    name = "describe",
2416    code = r###"
2417    IMPORT [STD]
2418    WRITE "entry.txt" "words"
2419    LET $kind: STRING = PATH_TYPE("entry.txt")
2420    ASSERT_EQ $kind "file"
2421    LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
2422    ASSERT_EQ $missing "absent"
2423    "###
2424)]
2425fn path_type<P: ProcessManager>(
2426    cx: &mut StepCtx<P>,
2427    /// Workspace path of the entry to describe.
2428    #[union(String, Path)]
2429    path: Value,
2430) -> Result<Value> {
2431    let text = super::args::string_or_path_text(&path)?;
2432    super::args::path_type_from_value(&[Value::string(text)], cx)
2433}
2434
2435/// Report whether an ordinary file can be created at a path.
2436///
2437/// Walks up to the nearest existing ancestor, requires it be a
2438/// directory, and probes writability by creating and deleting a probe
2439/// file, so retry loops never litter. The empty string is false.
2440/// AST-only by design, like `PATH_TYPE`: there is no RPN arm for
2441/// filesystem IO.
2442///
2443#[oxdock_func(returns = TypeTag::Bool)]
2444#[example(
2445    name = "probe",
2446    code = r###"
2447    # An absent nested path is writable when its ancestor is.
2448    IMPORT [STD]
2449    LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
2450    ASSERT_EQ $fresh true
2451
2452    # The empty string never aliases the working directory.
2453    LET $empty: BOOL = PATH_WRITABLE("")
2454    ASSERT_EQ $empty false
2455    "###
2456)]
2457fn path_writable<P: ProcessManager>(
2458    cx: &mut StepCtx<P>,
2459    /// Workspace path to probe for file creation.
2460    #[union(String, Path)]
2461    path: Value,
2462) -> Result<Value> {
2463    let text = super::args::string_or_path_text(&path)?;
2464    super::args::path_writable_from_value(&[Value::string(text)], cx)
2465}
2466
2467/// Report whether a name resolves to an executable file (#100).
2468///
2469/// Bare command names search `env:PATH` (`IS_EXEC("tar")` finds the
2470/// first executable `tar`, plus `tar.exe`, on `PATH`); spellings
2471/// containing a separator check that file directly. True means a real
2472/// file with an executable bit on Unix, or a `PATHEXT` extension on
2473/// Windows: each `env:PATHEXT` entry is probed in order (unset or empty
2474/// probes nothing). Absolute `PATH` entries resolve through the workspace as
2475/// usual, so host probing wants `WORKSPACE SYSTEM` and an inherited
2476/// `PATH`; anything unresolvable reads false, never errors. AST-only
2477/// by design, like `PATH_TYPE`: there is no RPN arm for filesystem IO.
2478///
2479#[oxdock_func(returns = TypeTag::Bool)]
2480#[example(
2481    name = "probe",
2482    code = r###"
2483    # Missing tools read false instead of failing the run.
2484    IMPORT [STD]
2485    LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
2486    ASSERT_EQ $missing false
2487
2488    # Plain files are not executable on any platform.
2489    WRITE tool.txt payload
2490    LET $plain: BOOL = IS_EXEC("tool.txt")
2491    ASSERT_EQ $plain false
2492    "###
2493)]
2494fn is_exec<P: ProcessManager>(
2495    cx: &mut StepCtx<P>,
2496    /// Command name or file path to probe.
2497    #[union(String, Path)]
2498    name: Value,
2499) -> Result<Value> {
2500    let text = super::args::string_or_path_text(&name)?;
2501    super::args::is_exec_from_value(&[Value::string(text)], cx)
2502}
2503
2504/// Report whether a workspace path names an ordinary file.
2505///
2506/// No-follow by design like `PATH_TYPE`: a symlink is neither a file
2507/// nor a directory, so it reads false here. Missing or unresolvable
2508/// paths read false, never error. AST-only by design, like `PATH_TYPE`:
2509/// there is no RPN arm for filesystem IO.
2510///
2511#[oxdock_func(returns = TypeTag::Bool)]
2512#[example(
2513    name = "probe",
2514    code = r###"
2515    # Ordinary files read true; missing paths read false.
2516    IMPORT [STD]
2517    WRITE "entry.txt" "words"
2518    LET $hit: BOOL = IS_FILE("entry.txt")
2519    ASSERT_EQ $hit true
2520    LET $miss: BOOL = IS_FILE("no-such-entry.txt")
2521    ASSERT_EQ $miss false
2522    "###
2523)]
2524fn is_file<P: ProcessManager>(
2525    cx: &mut StepCtx<P>,
2526    /// Workspace path to probe.
2527    #[union(String, Path)]
2528    path: Value,
2529) -> Result<Value> {
2530    let text = super::args::string_or_path_text(&path)?;
2531    Ok(Value::bool(super::args::path_is_file(cx, &text)))
2532}
2533
2534/// Report whether a workspace path names a directory.
2535///
2536/// No-follow by design like `PATH_TYPE`: a symlink is neither a file
2537/// nor a directory, so it reads false here. Missing or unresolvable
2538/// paths read false, never error. AST-only by design, like `PATH_TYPE`:
2539/// there is no RPN arm for filesystem IO.
2540///
2541#[oxdock_func(returns = TypeTag::Bool)]
2542#[example(
2543    name = "probe",
2544    code = r###"
2545    # Directories read true; files read false.
2546    IMPORT [STD]
2547    LET $hit: BOOL = IS_DIR(".")
2548    ASSERT_EQ $hit true
2549    WRITE "entry.txt" "words"
2550    LET $miss: BOOL = IS_DIR("entry.txt")
2551    ASSERT_EQ $miss false
2552    "###
2553)]
2554fn is_dir<P: ProcessManager>(
2555    cx: &mut StepCtx<P>,
2556    /// Workspace path to probe.
2557    #[union(String, Path)]
2558    path: Value,
2559) -> Result<Value> {
2560    let text = super::args::string_or_path_text(&path)?;
2561    Ok(Value::bool(super::args::path_is_dir(cx, &text)))
2562}
2563
2564/// Report whether a workspace path exists in any form.
2565///
2566/// True for files, directories, and symlinks; false for absent or
2567/// unresolvable paths, never an error. AST-only by design, like
2568/// `PATH_TYPE`: there is no RPN arm for filesystem IO.
2569///
2570#[oxdock_func(returns = TypeTag::Bool)]
2571#[example(
2572    name = "probe",
2573    code = r###"
2574    # Present entries read true; absent paths read false.
2575    IMPORT [STD]
2576    WRITE "entry.txt" "words"
2577    LET $hit: BOOL = EXISTS("entry.txt")
2578    ASSERT_EQ $hit true
2579    LET $miss: BOOL = EXISTS("no-such-entry.txt")
2580    ASSERT_EQ $miss false
2581    "###
2582)]
2583fn exists<P: ProcessManager>(
2584    cx: &mut StepCtx<P>,
2585    /// Workspace path to probe.
2586    #[union(String, Path)]
2587    path: Value,
2588) -> Result<Value> {
2589    let text = super::args::string_or_path_text(&path)?;
2590    Ok(Value::bool(super::args::path_exists(cx, &text)))
2591}
2592
2593/// Report whether a map holds a key.
2594///
2595/// Pure MAP probe so scripts can branch on optional fields without
2596/// tripping the strict missing-key error.
2597///
2598#[oxdock_func(pure, returns = TypeTag::Bool)]
2599#[example(
2600    name = "probe",
2601    code = r###"
2602    IMPORT [STD]
2603    LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2604    LET $hit: BOOL = HAS_KEY($m, "a")
2605    ASSERT_EQ $hit true
2606    LET $miss: BOOL = HAS_KEY($m, "b")
2607    ASSERT_EQ $miss false
2608    "###
2609)]
2610fn has_key(
2611    /// Map to probe.
2612    map: BTreeMap<String, Value>,
2613    /// Key to look up.
2614    key: String,
2615) -> Result<Value> {
2616    super::args::has_key_from_value(Value::map(map), &key)
2617}
2618
2619/// Read one map entry with a default for missing keys.
2620///
2621/// Pure MAP getter so optional flags cost one line instead of a
2622/// `HAS_KEY` + index + rebind triple: present keys return their value
2623/// verbatim (no coercion), absent keys return `default`.
2624#[oxdock_func(pure, returns = TypeTag::Any)]
2625#[example(
2626    name = "present and absent",
2627    code = r###"
2628    IMPORT [STD]
2629    LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
2630    LET $hit: INT = GET($m, "a", 0)
2631    ASSERT_EQ $hit 1
2632    LET $miss: INT = GET($m, "b", 0)
2633    ASSERT_EQ $miss 0
2634    "###
2635)]
2636fn get(
2637    /// Map to read.
2638    map: BTreeMap<String, Value>,
2639    /// Key to look up.
2640    key: String,
2641    /// Default for absent keys.
2642    default: Value,
2643) -> Result<Value> {
2644    Ok(map.get(&key).cloned().unwrap_or(default))
2645}
2646
2647/// Insert one key into a map, returning the extended map.
2648///
2649/// Fails on duplicates so two entries sharing a key fail the run
2650/// instead of silently shadowing each other.
2651///
2652/// A frozen (`CONST`-derived) map fails instead of deriving: `CONST`
2653/// bindings never produce a mutable map, so snapshot explicitly
2654/// through a `LET` copy of unfrozen data if derivation is intended.
2655///
2656#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2657#[example(
2658    name = "insert",
2659    code = r###"
2660    IMPORT [STD]
2661    LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
2662    ASSERT_EQ $m.a 1
2663    "###
2664)]
2665fn map_set(
2666    /// Map to insert into.
2667    #[reject_frozen]
2668    map: BTreeMap<String, Value>,
2669    /// Key to insert; duplicates fail.
2670    key: String,
2671    /// Value to store.
2672    value: Value,
2673) -> Result<Value> {
2674    super::args::map_set_from_value(Value::map(map), key, value)
2675}
2676
2677/// Draw a random FLOAT uniformly from [0, 1), optionally seeded.
2678///
2679/// Impure by design: unseeded calls return different values, so this
2680/// runs on the AST script path only, never as a `{{ }}` placeholder
2681/// call. A seed draws the same value on every run, for deterministic
2682/// fixtures. Scale and shift the draw for wider ranges.
2683///
2684#[oxdock_func(returns = TypeTag::Float, summary = "Draw a random FLOAT uniformly from [0, 1), optionally seeded.")]
2685#[example(
2686    name = "seeded draw",
2687    code = r###"
2688    # A seed draws the same value on every run.
2689    IMPORT [STD]
2690    LET $one: FLOAT = RAND({seed: 7})
2691    LET $two: FLOAT = RAND({seed: 7})
2692    ASSERT_EQ $one $two
2693    "###
2694)]
2695#[example(
2696    name = "unseeded draw",
2697    code = r###"
2698    # Scale a unit draw into a backoff delay between 1 and 11 seconds.
2699    IMPORT [STD]
2700    LET $draw: FLOAT = RAND()
2701    LET $delay: FLOAT = 1.0 + $draw * 10.0
2702    IF $delay < 1.0 {
2703        EXIT 1
2704    }
2705    IF $delay >= 11.0 {
2706        EXIT 1
2707    }
2708    ECHO "retrying in {{ $delay }}s"
2709    "###
2710)]
2711fn rand<P: ProcessManager>(
2712    cx: &mut StepCtx<P>,
2713    /// Draw settings: `seed`. Omittable: a missing options MAP fills `{}`.
2714    #[options("seed?: INT")]
2715    #[optional]
2716    options: BTreeMap<String, Value>,
2717) -> Result<Value> {
2718    let _ = cx;
2719    // `check_options` in the wrapper verified the shape above; the
2720    // read below narrows infallibly after.
2721    let seed = options
2722        .get("seed")
2723        .map(|value| value.as_i64().expect("check_options verified INT"));
2724    super::args::rand_float_from_value(seed)
2725}
2726
2727/// Encode a STRING as standard base64.
2728///
2729/// Padded RFC 4648 alphabet, so encoded output pastes into any
2730/// standard decoder. Pairs with `BASE64_DECODE` for the round trip.
2731///
2732#[oxdock_func(pure, returns = TypeTag::String)]
2733#[example(
2734    name = "encode",
2735    code = r###"
2736    # Encode text to standard base64.
2737    IMPORT [STD]
2738    LET $encoded: STRING = BASE64_ENCODE("hello")
2739    ASSERT_EQ $encoded "aGVsbG8="
2740    "###
2741)]
2742fn base64_encode(
2743    /// Text to encode.
2744    text: String,
2745) -> Result<Value> {
2746    super::args::base64_encode_from_value(Value::string(text))
2747}
2748
2749/// Decode standard base64 to a STRING.
2750///
2751/// Fails naming the input on invalid alphabet characters or
2752/// non-UTF-8 payloads instead of rendering a silent empty. Pairs
2753/// with `BASE64_ENCODE` for the round trip.
2754///
2755#[oxdock_func(pure, returns = TypeTag::String)]
2756#[example(
2757    name = "decode",
2758    code = r###"
2759    # Decode standard base64 back to text.
2760    IMPORT [STD]
2761    LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
2762    ASSERT_EQ $decoded "hello"
2763    "###
2764)]
2765fn base64_decode(
2766    /// Base64 text to decode.
2767    text: String,
2768) -> Result<Value> {
2769    super::args::base64_decode_from_value(Value::string(text))
2770}
2771
2772/// Encode a script value as JSON with one trailing newline.
2773///
2774/// Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT,
2775/// BOOL, LIST, MAP) survive, anything else fails here instead of
2776/// rendering as a silent empty.
2777///
2778#[oxdock_func(pure, returns = TypeTag::String)]
2779#[example(
2780    name = "encode",
2781    code = r###"
2782    IMPORT [STD]
2783    LET $json: STRING = TO_JSON({a: 1})
2784    ASSERT_EQ $json "{\"a\":1}\n"
2785    "###
2786)]
2787fn to_json(
2788    /// Value to encode as JSON.
2789    #[union(String, Int, Float, Bool, List, Map)]
2790    value: Value,
2791) -> Result<Value> {
2792    super::args::to_json_from_value(value)
2793}
2794
2795/// Name the word a value holds, for data-driven branching.
2796///
2797/// Returns the registered type word (`STRING`, `INT`, `FLOAT`, `BOOL`,
2798/// `LIST`, `MAP`, plus handle words like `PIPE`): the same name the
2799/// value prints in arity and coercion errors, so scripts can branch
2800/// on config shapes (a path string or a path list) without failing.
2801///
2802#[oxdock_func(pure, returns = TypeTag::String)]
2803#[example(
2804    name = "name the word",
2805    code = r###"
2806    IMPORT [STD]
2807    LET $word: STRING = TYPE_OF(42)
2808    ASSERT_EQ $word "INT"
2809    "###
2810)]
2811fn type_of(
2812    /// Value whose word to name.
2813    value: Value,
2814) -> Result<Value> {
2815    super::args::type_of_from_value(value)
2816}
2817
2818/// Merge a LIST of MAPs in order under one duplicate policy.
2819///
2820/// `fail_on_duplicate` fails naming the repeated key, so two files
2821/// claiming one placeholder fail the run instead of shadowing each
2822/// other. `overwrite` lets later files win, for environment overlays.
2823/// Non MAP elements fail naming their position.
2824///
2825/// A frozen (`CONST`-derived) list or element fails instead of
2826/// deriving, mirroring `MAP_SET`: `CONST` bindings never produce a
2827/// mutable map.
2828///
2829#[oxdock_func(pure, returns = TypeTag::MapOf(std::sync::Arc::new(TypeTag::Any)))]
2830#[example(
2831    name = "merge",
2832    code = r###"
2833    IMPORT [STD]
2834    LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
2835    ASSERT_EQ $m.a 1
2836    ASSERT_EQ $m.b 2
2837    "###
2838)]
2839fn merge_maps(
2840    /// LIST of MAPs to merge in order.
2841    #[reject_frozen]
2842    maps: Vec<BTreeMap<String, Value>>,
2843    /// Duplicate policy.
2844    #[values("fail_on_duplicate", "overwrite")]
2845    policy: String,
2846) -> Result<Value> {
2847    super::args::merge_maps_from_value(
2848        Value::list(maps.into_iter().map(Value::map).collect()),
2849        policy,
2850    )
2851}
2852
2853/// Report the running engine version.
2854///
2855/// Returns the workspace version baked in at compile time, so scripts
2856/// and agents can branch on engine behavior instead of probing it.
2857#[oxdock_func(pure, returns = TypeTag::String)]
2858#[example(
2859    name = "report",
2860    code = r###"
2861    # The engine reports its own build version as a dotted string.
2862    IMPORT [STD]
2863    LET $v: STRING = VERSION()
2864    ASSERT_CONTAINS $v "."
2865    "###
2866)]
2867fn version() -> Result<Value> {
2868    Ok(Value::string(env!("CARGO_PKG_VERSION").to_string()))
2869}
2870
2871/// List all visible function names.
2872///
2873/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
2874/// plus host-registered names.
2875#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2876#[example(
2877    name = "list",
2878    code = r###"
2879    IMPORT [STD]
2880    LET $names: LIST<STRING> = FUNCTIONS()
2881    ASSERT_CONTAINS $names "STD::INT"
2882    "###
2883)]
2884fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2885    let mut names: Vec<String> = cx
2886        .state
2887        .list_functions()
2888        .into_iter()
2889        .map(|meta| meta.name)
2890        .collect();
2891    names.sort();
2892    names.dedup();
2893    Ok(Value::list(names.into_iter().map(Value::string).collect()))
2894}
2895
2896/// Report the verbatim CLI tail after the script position.
2897///
2898/// Staged per run from `Options.script_args` (#226): everything after
2899/// the script file (or `--script <file>`), with one leading `--`
2900/// stripped. Never merged with interpreter flags, so `--dry-run`
2901/// after the script arrives here instead of enabling dry-run.
2902#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
2903#[example(
2904    name = "empty",
2905    code = r###"
2906    # With no staged args the list is empty.
2907    IMPORT [STD]
2908    LET $args: LIST<STRING> = ARGV()
2909    LET $n: INT = LEN($args)
2910    ASSERT_EQ $n 0
2911    "###
2912)]
2913fn argv<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
2914    Ok(Value::list(
2915        cx.state
2916            .io
2917            .script_args()
2918            .iter()
2919            .cloned()
2920            .map(Value::string)
2921            .collect(),
2922    ))
2923}
2924
2925/// Parse an argv tail against `TYPE FLAGS`, returning flags and positionals.
2926///
2927/// Consumes a `LIST<STRING>` (usually `STD::ARGV()`) with the `lexopt`
2928/// tokenizer. Long `--key=value` binds the string value. Bare long
2929/// `--key` binds `true`. Short `-a` binds `true`. One `--` entry ends
2930/// option parsing, so the rest lands in `positionals`. Duplicate keys
2931/// overwrite in order, so the last occurrence wins.
2932///
2933/// The schema is always `TYPE FLAGS`: a `MAP` shape with scalar
2934/// fields. Present flags coerce to their target (`BOOL` accepts
2935/// `true`/`false` spellings, `INT`/`FLOAT` parse their strings); bare
2936/// `--key` for a non-`BOOL` target fails naming the flag. Missing
2937/// flags fill their `= default`, missing required flags fail, and
2938/// unknown flags fail. Defaults are literals only: `INT`, `FLOAT`,
2939/// `BOOL`, and double-quoted `STRING`. A variable or expression in
2940/// place of a literal fails the `TYPE` statement, so defaults stay
2941/// plain data in the shape. Absent optional flags without a default stay
2942/// absent (read them with a typed `GET` default). `positionals` is
2943/// omitted when empty, so a flags only `MAP<flags: FLAGS>` binds clean.
2944pub struct ParseArgs;
2945
2946impl<P: ProcessManager> OxDockFn<P> for ParseArgs {
2947    fn registration() -> HostRegistration<P> {
2948        let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
2949            if values.len() != 1 {
2950                anyhow::bail!("PARSE_ARGS() expects 1 argument, got {}", values.len());
2951            }
2952            let mut iter = values.into_iter();
2953            let args_val = iter.next().expect("arity checked above");
2954            let args = string_list_arg(&args_val, "PARSE_ARGS() argument `$args`")?;
2955            let specs = resolve_flags_specs(cx)?;
2956            let (raw, positionals) = tokenize_raw_args(args)?;
2957            let coerced = coerce_flags(&specs, &raw)?;
2958            let mut out = BTreeMap::new();
2959            out.insert("flags".to_string(), Value::map(coerced));
2960            if !positionals.is_empty() {
2961                out.insert("positionals".to_string(), Value::list(positionals));
2962            }
2963            Ok(Value::map(out))
2964        });
2965        HostRegistration::Stateful {
2966            name: "PARSE_ARGS".to_string(),
2967            meta: FuncMeta {
2968                name: "PARSE_ARGS".to_string(),
2969                module: String::new(),
2970                kind: FuncKind::HostPure,
2971                params: Some(vec![FuncParam {
2972                    name: "args".to_string(),
2973                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
2974                    allowed: None,
2975                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
2976                    options: None,
2977                    optional: false,
2978                }]),
2979                returns: Some(TypeTag::Record(Arc::from([
2980                    Field {
2981                        name: "flags".to_string(),
2982                        ty: TypeTag::Map,
2983                        docs: "Flags coerced to `TYPE FLAGS`.",
2984                        optional: false,
2985                        default: None,
2986
2987                        alias: None,
2988                    },
2989                    Field {
2990                        name: "positionals".to_string(),
2991                        ty: TypeTag::ListOf(Arc::new(TypeTag::String)),
2992                        docs: "Trailing values and entries after the first double dash. Omitted when empty.",
2993                        optional: true,
2994                        default: None,
2995
2996                        alias: None,
2997                    },
2998                ]))),
2999                rpn: true,
3000                summary: "Parse an argv tail against TYPE FLAGS.",
3001                docs: "Consumes a `LIST<STRING>` with the `lexopt` tokenizer and coerces flags through `TYPE FLAGS`. See the function reference for the coercion and omission rules.",
3002                examples: &[
3003                    crate::Example {
3004                        name: "flags and positionals",
3005                        fence_meta: None,
3006                        code: indoc::indoc! {r#"
3007                            IMPORT [STD]
3008                            # One schema TYPE drives coercion; the pair binds both slots.
3009                            TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
3010                            TYPE POSITIONS = LIST<STRING>
3011                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3012                            LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
3013                            LET $flags: FLAGS = $parsed.flags
3014                            ASSERT_EQ $flags.model "gpt-4"
3015                            ASSERT_EQ $flags.verbose true
3016                            ASSERT_EQ $parsed.positionals.0 "serve"
3017                        "#},
3018                    },
3019                    crate::Example {
3020                        name: "optional stays absent",
3021                        fence_meta: None,
3022                        code: indoc::indoc! {r#"
3023                            IMPORT [STD]
3024                            # Absent optionals stay absent; read them with a typed GET default.
3025                            TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
3026                            TYPE POSITIONS = LIST<STRING>
3027                            TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
3028                            LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3029                            LET $flags: FLAGS = $parsed.flags
3030                            LET $propose: BOOL = GET($flags, "propose", false)
3031                            ASSERT_EQ $propose false
3032                        "#},
3033                    },
3034                    crate::Example {
3035                        name: "flags only omits positionals",
3036                        fence_meta: None,
3037                        code: indoc::indoc! {r#"
3038                            IMPORT [STD]
3039                            # Empty positionals are omitted, so a flags only shape binds clean.
3040                            TYPE FLAGS = MAP<model: STRING>
3041                            TYPE PARSED = MAP<flags: FLAGS>
3042                            LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
3043                            LET $flags: FLAGS = $parsed.flags
3044                            ASSERT_EQ $flags.model "x"
3045                        "#},
3046                    },
3047                    crate::Example {
3048                        name: "literal defaults",
3049                        fence_meta: None,
3050                        code: indoc::indoc! {r#"
3051                            IMPORT [STD]
3052                            # Defaults are literals only: INT, FLOAT, BOOL,
3053                            # and double-quoted STRING fill absent flags.
3054                            TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
3055                            TYPE PARSED = MAP<flags: FLAGS>
3056                            LET $parsed: PARSED = PARSE_ARGS([])
3057                            LET $flags: FLAGS = $parsed.flags
3058                            ASSERT_EQ $flags.retries 2
3059                            ASSERT_EQ $flags.verbose true
3060                            ASSERT_EQ $flags.model "gpt-4"
3061                            LET $ratio_ok: BOOL = $flags.ratio == 2.5
3062                            ASSERT_EQ $ratio_ok true
3063                        "#},
3064                    },
3065                    crate::Example {
3066                        name: "variable default fails",
3067                        fence_meta: Some("expect_error:\"expected default literal\""),
3068                        code: indoc::indoc! {r#"
3069                            IMPORT [STD]
3070                            # Defaults are literals: a variable in place
3071                            # of a literal fails instead of evaluating.
3072                            TYPE FLAGS = MAP<n: INT = $x>
3073                            TYPE PARSED = MAP<flags: FLAGS>
3074                            LET $p: PARSED = PARSE_ARGS([])
3075                        "#},
3076                    },
3077                    crate::Example {
3078                        name: "missing required",
3079                        fence_meta: Some("expect_error:\"missing required flag\""),
3080                        code: indoc::indoc! {r#"
3081                            IMPORT [STD]
3082                            # Absent required flags fail naming the flag.
3083                            TYPE FLAGS = MAP<model: STRING>
3084                            TYPE PARSED = MAP<flags: FLAGS>
3085                            LET $parsed: PARSED = PARSE_ARGS([])
3086                        "#},
3087                    },
3088                    crate::Example {
3089                        name: "unknown flag",
3090                        fence_meta: Some("expect_error:\"unknown flag\""),
3091                        code: indoc::indoc! {r#"
3092                            IMPORT [STD]
3093                            # Undeclared flags fail instead of passing through.
3094                            TYPE FLAGS = MAP<model: STRING>
3095                            TYPE PARSED = MAP<flags: FLAGS>
3096                            LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
3097                        "#},
3098                    },
3099                    crate::Example {
3100                        name: "alias accepted",
3101                        fence_meta: None,
3102                        code: indoc::indoc! {r#"
3103                            IMPORT [STD]
3104                            # One canonical key binds both spellings; the
3105                            # alias never appears as a separate key.
3106                            TYPE FLAGS = MAP<h: BOOL ALIAS help>
3107                            TYPE PARSED = MAP<flags: FLAGS>
3108                            LET $a: PARSED = PARSE_ARGS(["--help"])
3109                            ASSERT_EQ $a.flags.h true
3110                            LET $b: PARSED = PARSE_ARGS(["--h"])
3111                            ASSERT_EQ $b.flags.h true
3112                        "#},
3113                    },
3114                    crate::Example {
3115                        name: "alias duplicate fails",
3116                        fence_meta: Some("expect_error:\"duplicate flag\""),
3117                        code: indoc::indoc! {r#"
3118                            IMPORT [STD]
3119                            # Canonical and alias together fail naming both.
3120                            TYPE FLAGS = MAP<h: BOOL ALIAS help>
3121                            TYPE PARSED = MAP<flags: FLAGS>
3122                            LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
3123                        "#},
3124                    },
3125                    crate::Example {
3126                        name: "alias missing names both",
3127                        fence_meta: Some("expect_error:\"--h/--help\""),
3128                        code: indoc::indoc! {r#"
3129                            IMPORT [STD]
3130                            # Missing required flags name both spellings.
3131                            TYPE FLAGS = MAP<h: BOOL ALIAS help>
3132                            TYPE PARSED = MAP<flags: FLAGS>
3133                            LET $p: PARSED = PARSE_ARGS([])
3134                        "#},
3135                    },
3136                ],
3137            },
3138            func,
3139        }
3140    }
3141}
3142
3143/// CLI target types for `PARSE_ARGS` schemas: the four scalar words
3144/// raw flags can coerce into. No new types without extending the
3145/// coercion below together with the schema resolution below it.
3146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3147enum CliType {
3148    String,
3149    Bool,
3150    Int,
3151    Float,
3152}
3153
3154/// Coerce one raw flag value to its schema target. Raw values are only
3155/// ever `BOOL true` (bare) or `STRING` (equals form); anything else is
3156/// a caller bug. Bare flags for non-`BOOL` targets fail naming the
3157/// flag instead of smuggling `true` into the slot.
3158fn coerce_cli_flag(target: CliType, flag: &str, raw: Value) -> Result<Value> {
3159    match target {
3160        CliType::Bool => {
3161            if let Some(b) = raw.as_bool() {
3162                return Ok(Value::bool(b));
3163            }
3164            if let Some(s) = raw.as_str() {
3165                match super::args::parse_bool_str(s) {
3166                    Some(b) => return Ok(Value::bool(b)),
3167                    None => anyhow::bail!(
3168                        "PARSE_ARGS flag --{flag} expects BOOL (true/false, 1/0, yes/no, on/off), got {s:?}"
3169                    ),
3170                }
3171            }
3172            anyhow::bail!(
3173                "PARSE_ARGS flag --{flag} expects BOOL, got {}",
3174                raw.type_name()
3175            )
3176        }
3177        CliType::String => {
3178            if let Some(s) = raw.as_str() {
3179                return Ok(Value::string(s.to_string()));
3180            }
3181            anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
3182        }
3183        CliType::Int => {
3184            if raw.as_bool().is_some() {
3185                anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
3186            }
3187            super::args::int_from_value(raw)
3188                .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects INT"))
3189        }
3190        CliType::Float => {
3191            if raw.as_bool().is_some() {
3192                anyhow::bail!("PARSE_ARGS flag --{flag} needs a value: use --{flag}=<value>");
3193            }
3194            super::args::float_from_value(raw)
3195                .map_err(|_| anyhow::anyhow!("PARSE_ARGS flag --{flag} expects FLOAT"))
3196        }
3197    }
3198}
3199
3200/// One CLI flag spec: target type, required bit, filled default, and
3201/// optional alternate spelling. Single owner so the tokenizer,
3202/// coercion, and both entry points share one signature.
3203#[derive(Debug, Clone)]
3204struct CliSpec {
3205    target: CliType,
3206    required: bool,
3207    default: Option<Value>,
3208    alias: Option<String>,
3209}
3210
3211/// Canonical specs keyed by canonical flag name.
3212type CliSpecs = BTreeMap<String, CliSpec>;
3213
3214/// Checked `LIST<STRING>` extraction for the CLI trio. Single owner
3215/// so all three functions admit exactly the same argv shape.
3216fn string_list_arg(val: &Value, what: &str) -> Result<Vec<String>> {
3217    crate::check_value_at(&TypeTag::ListOf(Arc::new(TypeTag::String)), val, what)?;
3218    Ok(val
3219        .as_list()
3220        .expect("check_value_at enforces LIST")
3221        .iter()
3222        .map(|v| {
3223            v.as_str()
3224                .expect("check_value_at enforces STRING")
3225                .to_string()
3226        })
3227        .collect())
3228}
3229
3230/// Shared argv tokenizer. Single owner so flags versus positionals
3231/// split identically for all three entry points. Raw values are only
3232/// `BOOL true` (bare) or `STRING` (equals form).
3233fn tokenize_raw_args(args: Vec<String>) -> Result<(BTreeMap<String, Value>, Vec<Value>)> {
3234    use lexopt::Arg::{Long, Short, Value as ArgValue};
3235    let mut parser = lexopt::Parser::from_args(args);
3236    let mut flags: BTreeMap<String, Value> = BTreeMap::new();
3237    let mut positionals: Vec<Value> = Vec::new();
3238    let utf8 = |value: std::ffi::OsString| -> Result<String> {
3239        value
3240            .into_string()
3241            .map_err(|_| anyhow::anyhow!("PARSE_ARGS: argument must be UTF-8"))
3242    };
3243    loop {
3244        match parser.next() {
3245            Ok(None) => break,
3246            Ok(Some(Long(name))) => {
3247                let key = name.to_owned();
3248                if let Some(raw) = parser.optional_value() {
3249                    flags.insert(key, Value::string(utf8(raw)?));
3250                } else {
3251                    flags.insert(key, Value::bool(true));
3252                }
3253            }
3254            Ok(Some(Short(ch))) => {
3255                flags.insert(ch.to_string(), Value::bool(true));
3256            }
3257            Ok(Some(ArgValue(raw))) => {
3258                positionals.push(Value::string(utf8(raw)?));
3259            }
3260            Err(lexopt::Error::UnexpectedValue { option, value }) => {
3261                let key = option
3262                    .strip_prefix("--")
3263                    .or_else(|| option.strip_prefix('-'))
3264                    .unwrap_or(option.as_str());
3265                flags.insert(key.to_string(), Value::string(utf8(value)?));
3266            }
3267            Err(err) => anyhow::bail!("PARSE_ARGS: {err}"),
3268        }
3269    }
3270    Ok((flags, positionals))
3271}
3272
3273/// Shared flag coercion. Single owner so `PARSE_ARGS` and
3274/// `PARSE_FLAGS` fill, require, and reject identically: present flags
3275/// (canonical or alias) coerce, missing defaulted flags fill, missing
3276/// required flags fail, missing optionals stay absent, unknown flags
3277/// fail. One canonical key lands in the parsed map; alias spellings
3278/// ride the command line only. Missing and duplicate errors name both
3279/// spellings when an alias exists.
3280fn coerce_flags(
3281    specs: &CliSpecs,
3282    raw: &BTreeMap<String, Value>,
3283) -> Result<BTreeMap<String, Value>> {
3284    // Alias reverse map: alias spelling to canonical key. Validated
3285    // unique at type resolution, so a duplicate insert is unreachable.
3286    let mut alias_to_canonical: BTreeMap<&str, &str> = BTreeMap::new();
3287    for (canonical, spec) in specs.iter() {
3288        if let Some(alias) = spec.alias.as_ref() {
3289            alias_to_canonical.insert(alias.as_str(), canonical.as_str());
3290        }
3291    }
3292    let mut coerced: BTreeMap<String, Value> = BTreeMap::new();
3293    for (flag, spec) in specs.iter() {
3294        if flag.is_empty() {
3295            anyhow::bail!("PARSE_ARGS schema flag names must be non-empty");
3296        }
3297        let canonical_raw = raw.get(flag);
3298        let alias_raw = spec.alias.as_ref().and_then(|alias| raw.get(alias));
3299        // Display name names both spellings when an alias exists.
3300        let display = match spec.alias.as_ref() {
3301            Some(alias) => format!("--{flag}/--{alias}"),
3302            None => format!("--{flag}"),
3303        };
3304        if canonical_raw.is_some() && alias_raw.is_some() {
3305            anyhow::bail!("PARSE_ARGS duplicate flag {display}");
3306        }
3307        if let Some(raw_val) = canonical_raw.or(alias_raw) {
3308            coerced.insert(
3309                flag.clone(),
3310                coerce_cli_flag(spec.target, flag, raw_val.clone())?,
3311            );
3312        } else if let Some(d) = spec.default.as_ref() {
3313            coerced.insert(flag.clone(), d.clone());
3314        } else if spec.required {
3315            anyhow::bail!("PARSE_ARGS missing required flag {display}");
3316        }
3317    }
3318    for flag in raw.keys() {
3319        if !specs.contains_key(flag) && !alias_to_canonical.contains_key(flag.as_str()) {
3320            anyhow::bail!("PARSE_ARGS unknown flag --{flag}");
3321        }
3322    }
3323    Ok(coerced)
3324}
3325
3326/// Resolve the fixed `TYPE FLAGS` schema into coercion specs: one entry
3327/// per record field, targets from scalar field types, required unless
3328/// optional or defaulted, defaults filled from the shape, aliases
3329/// carried for command-line acceptance. Single owner so both pair and
3330/// flags only entry points admit exactly the same set. Non-record
3331/// types and non-scalar fields fail naming the flag.
3332fn resolve_flags_specs<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<CliSpecs> {
3333    let name = "FLAGS";
3334    let tag = cx
3335        .state
3336        .resolve_tag(name)
3337        .map_err(|err| anyhow::anyhow!("PARSE_ARGS schema type {name:?}: {err:#}"))?;
3338    let TypeTag::Record(fields) = tag else {
3339        anyhow::bail!("PARSE_ARGS schema type {name:?} must be a MAP shape with scalar fields");
3340    };
3341    let mut specs = BTreeMap::new();
3342    for field in fields.iter() {
3343        let target = match field.ty {
3344            TypeTag::String => CliType::String,
3345            TypeTag::Bool => CliType::Bool,
3346            TypeTag::Int => CliType::Int,
3347            TypeTag::Float => CliType::Float,
3348            _ => anyhow::bail!(
3349                "PARSE_ARGS schema for --{}: type must be one of STRING, BOOL, INT, or FLOAT, got {}",
3350                field.name,
3351                field.ty.name(),
3352            ),
3353        };
3354        specs.insert(
3355            field.name.clone(),
3356            CliSpec {
3357                target,
3358                required: !field.optional && field.default.is_none(),
3359                default: field.default.clone(),
3360                alias: field.alias.clone(),
3361            },
3362        );
3363    }
3364    Ok(specs)
3365}
3366
3367/// Parse flags only against `TYPE FLAGS`.
3368///
3369/// Returns the flags `MAP` directly: no pair wrapper. Positional
3370/// arguments fail instead of dropping silently, so a space-separated
3371/// value (`--model gpt-4`) names the mistake instead of binding
3372/// `--model` to `true` and losing `gpt-4`.
3373/// Same tokenizer, coercion, defaults, and errors as `PARSE_ARGS`.
3374pub struct ParseFlags;
3375
3376impl<P: ProcessManager> OxDockFn<P> for ParseFlags {
3377    fn registration() -> HostRegistration<P> {
3378        let func: NativeFn<P> = Arc::new(|cx: &mut StepCtx<P>, values: Vec<Value>| {
3379            if values.len() != 1 {
3380                anyhow::bail!("PARSE_FLAGS() expects 1 argument, got {}", values.len());
3381            }
3382            let mut iter = values.into_iter();
3383            let args_val = iter.next().expect("arity checked above");
3384            let args = string_list_arg(&args_val, "PARSE_FLAGS() argument `$args`")?;
3385            let specs = resolve_flags_specs(cx)?;
3386            let (raw, positionals) = tokenize_raw_args(args)?;
3387            if !positionals.is_empty() {
3388                let shown: Vec<String> = positionals.iter().map(|pos| pos.to_string()).collect();
3389                anyhow::bail!(
3390                    "PARSE_FLAGS() does not accept positional arguments; found {}",
3391                    shown.join(", ")
3392                );
3393            }
3394            Ok(Value::map(coerce_flags(&specs, &raw)?))
3395        });
3396        HostRegistration::Stateful {
3397            name: "PARSE_FLAGS".to_string(),
3398            meta: FuncMeta {
3399                name: "PARSE_FLAGS".to_string(),
3400                module: String::new(),
3401                kind: FuncKind::HostPure,
3402                params: Some(vec![FuncParam {
3403                    name: "args".to_string(),
3404                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3405                    allowed: None,
3406                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3407                    options: None,
3408                    optional: false,
3409                }]),
3410                returns: Some(TypeTag::Map),
3411                rpn: true,
3412                summary: "Parse flags against TYPE FLAGS.",
3413                docs: "Consumes a `LIST<STRING>` and coerces flags through `TYPE FLAGS`. Returns the flags `MAP` directly; positional arguments fail.",
3414                examples: &[crate::Example {
3415                    name: "flags only",
3416                    fence_meta: None,
3417                    code: indoc::indoc! {r#"
3418                        IMPORT [STD]
3419                        # Flags only returns the flags MAP directly.
3420                        TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
3421                        LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
3422                        ASSERT_EQ $flags.model "x"
3423                        ASSERT_EQ $flags.retries 2
3424                    "#},
3425                }],
3426            },
3427            func,
3428        }
3429    }
3430}
3431
3432/// Parse positionals only: no schema, no `TYPE FLAGS` needed.
3433///
3434/// Returns trailing values and entries after the first double dash in
3435/// argv order. Tokenizer matches `PARSE_ARGS` exactly.
3436pub struct ParsePositionals;
3437
3438impl<P: ProcessManager> OxDockFn<P> for ParsePositionals {
3439    fn registration() -> HostRegistration<P> {
3440        let func: NativeFn<P> = Arc::new(|_: &mut StepCtx<P>, values: Vec<Value>| {
3441            if values.len() != 1 {
3442                anyhow::bail!(
3443                    "PARSE_POSITIONALS() expects 1 argument, got {}",
3444                    values.len()
3445                );
3446            }
3447            let mut iter = values.into_iter();
3448            let args_val = iter.next().expect("arity checked above");
3449            let args = string_list_arg(&args_val, "PARSE_POSITIONALS() argument `$args`")?;
3450            let (_raw, positionals) = tokenize_raw_args(args)?;
3451            Ok(Value::list(positionals))
3452        });
3453        HostRegistration::Stateful {
3454            name: "PARSE_POSITIONALS".to_string(),
3455            meta: FuncMeta {
3456                name: "PARSE_POSITIONALS".to_string(),
3457                module: String::new(),
3458                kind: FuncKind::HostPure,
3459                params: Some(vec![FuncParam {
3460                    name: "args".to_string(),
3461                    param_type: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3462                    allowed: None,
3463                    docs: "Argv tail to parse, usually from `STD::ARGV()`.",
3464                    options: None,
3465                    optional: false,
3466                }]),
3467                returns: Some(TypeTag::ListOf(Arc::new(TypeTag::String))),
3468                rpn: true,
3469                summary: "Parse positionals in argv order.",
3470                docs: "Consumes a `LIST<STRING>` and returns positionals in argv order with no schema.",
3471                examples: &[crate::Example {
3472                    name: "positionals only",
3473                    fence_meta: None,
3474                    code: indoc::indoc! {r#"
3475                        IMPORT [STD]
3476                        # No schema needed: positionals are always strings in order.
3477                        TYPE POSITIONS = LIST<STRING>
3478                        LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
3479                        ASSERT_EQ $pos.0 "serve"
3480                        ASSERT_EQ $pos.1 "--not-a-flag"
3481                    "#},
3482                }],
3483            },
3484            func,
3485        }
3486    }
3487}
3488
3489/// Describe one function by qualified name.
3490///
3491/// Returns a MAP with name, module, kind, params, returns, rpn, and
3492/// summary. `params` is always a LIST (empty for parameterless
3493/// functions) of entries carrying name, param_type, allowed, docs,
3494/// options, and optional flags, so the shape holds for every entry. Bare names
3495/// fail closed: `DESCRIBE` requires the qualified form (except
3496/// `INSPECT`, which is syntax rather than a registry entry). Errors
3497/// on unknown function.
3498///
3499/// Field table for the `DESCRIBE` result bundle: one source for the
3500/// shape the host mints, so introspection, enforcement, and
3501/// documentation cannot drift apart.
3502
3503#[oxdock_func(
3504    returns = TypeTag::Record(std::sync::Arc::from([Field {
3505        name: "name".to_string(),
3506        ty: TypeTag::String,
3507        docs: "Qualified function name.",
3508        optional: false,
3509        default: None,
3510
3511        alias: None,}, Field {
3512        name: "module".to_string(),
3513        ty: TypeTag::String,
3514        docs: "Owning module.",
3515        optional: false,
3516        default: None,
3517
3518        alias: None,}, Field {
3519        name: "kind".to_string(),
3520        ty: TypeTag::String,
3521        docs: "Origin label (`host` or `script`).",
3522        optional: false,
3523        default: None,
3524
3525        alias: None,}, Field {
3526        name: "params".to_string(),
3527        ty: TypeTag::ListOf(std::sync::Arc::new(TypeTag::MapOf(std::sync::Arc::new(
3528            TypeTag::Any,
3529        )))),
3530        docs: "Parameter entries (empty for parameterless functions).",
3531        optional: false,
3532        default: None,
3533
3534        alias: None,}, Field {
3535        name: "returns".to_string(),
3536        ty: TypeTag::String,
3537        docs: "Structural return shape (empty when untagged).",
3538        optional: false,
3539        default: None,
3540
3541        alias: None,}, Field {
3542        name: "rpn".to_string(),
3543        ty: TypeTag::Bool,
3544        docs: "True when callable in RPN position.",
3545        optional: false,
3546        default: None,
3547
3548        alias: None,}, Field {
3549        name: "summary".to_string(),
3550        ty: TypeTag::String,
3551        docs: "One-line description.",
3552        optional: false,
3553        default: None,
3554
3555        alias: None,}]))
3556    summary = "Describe one function by qualified name."
3557)]
3558#[example(
3559    name = "describe",
3560    code = r###"
3561    IMPORT [STD]
3562    LET $info: MAP<ANY> = DESCRIBE("STD::INT")
3563    ASSERT_EQ $info.name "STD::INT"
3564    ASSERT_EQ $info.returns "INT"
3565    "###
3566)]
3567fn describe<P: ProcessManager>(
3568    cx: &mut StepCtx<P>,
3569    /// Qualified function name (`MODULE::NAME`).
3570    name: String,
3571) -> Result<Value> {
3572    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
3573        anyhow::bail!(
3574            "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
3575        );
3576    }
3577    cx.state
3578        .describe_function(&name)
3579        .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
3580}
3581
3582/// List all known type names.
3583///
3584/// Sorted LIST of startup plus host-registered type descriptors. Reads the
3585/// run's name directory, so it runs on the AST path like the other
3586/// introspection functions.
3587#[oxdock_func(returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
3588#[example(
3589    name = "list",
3590    code = r###"
3591    IMPORT [STD]
3592    LET $names: LIST<STRING> = TYPES()
3593    ASSERT_CONTAINS $names "STRING"
3594    "###
3595)]
3596fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3597    Ok(Value::list(
3598        cx.state
3599            .type_names()
3600            .into_iter()
3601            .map(Value::string)
3602            .collect(),
3603    ))
3604}
3605
3606/// Describe one type by name.
3607///
3608/// Returns a MAP with name, summary, and docs. Errors on unknown type.
3609/// Reads the run's name directory, so it runs on the AST path.
3610///
3611#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3612    name: "name".to_string(),
3613    ty: TypeTag::String,
3614    docs: "Queried type name.",
3615    optional: false,
3616    default: None,
3617
3618    alias: None,}, Field {
3619    name: "summary".to_string(),
3620    ty: TypeTag::String,
3621    docs: "One-line description.",
3622    optional: false,
3623    default: None,
3624
3625    alias: None,}, Field {
3626    name: "docs".to_string(),
3627    ty: TypeTag::String,
3628    docs: "Full documentation text.",
3629    optional: false,
3630    default: None,
3631
3632    alias: None,}])))]
3633#[example(
3634    name = "describe",
3635    code = r###"
3636    IMPORT [STD]
3637    LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
3638    ASSERT_EQ $info.name "STRING"
3639    "###
3640)]
3641fn type_describe<P: ProcessManager>(
3642    cx: &mut StepCtx<P>,
3643    /// Type name to describe.
3644    name: String,
3645) -> Result<Value> {
3646    if let Some(descriptor) = cx.state.describe_type(&name) {
3647        let mut map = BTreeMap::new();
3648        map.insert(
3649            "name".to_string(),
3650            Value::string(descriptor.name.to_string()),
3651        );
3652        map.insert(
3653            "summary".to_string(),
3654            Value::string(descriptor.summary.to_string()),
3655        );
3656        map.insert(
3657            "docs".to_string(),
3658            Value::string(descriptor.docs.to_string()),
3659        );
3660        return Ok(Value::map(map));
3661    }
3662    // Script aliases have no descriptor but introspect the same way:
3663    // the entry names the alias and its canonical target spelling.
3664    if let Some(target) = cx.state.alias_target(&name) {
3665        let mut map = BTreeMap::new();
3666        map.insert("name".to_string(), Value::string(name.clone()));
3667        map.insert(
3668            "summary".to_string(),
3669            Value::string(format!("Script type alias for {target}.")),
3670        );
3671        map.insert(
3672            "docs".to_string(),
3673            Value::string(format!(
3674                "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
3675            )),
3676        );
3677        return Ok(Value::map(map));
3678    }
3679    Err(anyhow::anyhow!("unknown type {name}"))
3680}
3681
3682/// Path of the running interpreter binary.
3683///
3684/// Returns the executing binary as a `STRING`, so one script can
3685/// reinvoke the interpreter on another script without bridging an env
3686/// var. The child re-parses from bytes in a separate process: no
3687/// bindings cross back (only stdout and files), and each run pays
3688/// a spawn. Prefer modules for reuse (statically gated, in-process);
3689/// reach for reinvocation when the child must run isolated, or under
3690/// a different binary than the parent.
3691///
3692/// Unsupported under Miri isolation: the lookup itself fails there
3693/// instead of returning a path.
3694///
3695#[oxdock_func(returns = TypeTag::String)]
3696#[example(
3697    name = "self",
3698    code = r###"
3699    # The running interpreter resolves to a non-empty path.
3700    IMPORT [STD]
3701    LET $exe: STRING = INTERPRETER()
3702    LET $nonempty: BOOL = $exe != ""
3703    ASSERT_EQ $nonempty true
3704    "###
3705)]
3706#[example(
3707    name = "dynamic assembly",
3708    code = r###"
3709    # Assemble the child script dynamically: the parent interpolates
3710    # its own bindings into the pipe, then runs the interpreter on it.
3711    # Unescaped {{ }} bakes in at render time; \{{ }} stays literal
3712    # so the child expands it with its own bindings.
3713    # The pipe delivers EOF when the producer step ends, so the child
3714    # reads exactly one script.
3715    IMPORT [STD]
3716    LET $exe: STRING = INTERPRETER()
3717    LET $who: STRING = "Ada"
3718    LET $child: PIPE
3719    WITH_IO [stdout=$child] ECHO """
3720        ECHO "hello {{ $who }}!"
3721        LET $who: STRING = "Grace"
3722        ECHO "child sees \{{ $who }}!"
3723        """
3724    LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
3725    ASSERT_CONTAINS $out "hello Ada!"
3726    ASSERT_CONTAINS $out "child sees Grace!"
3727    "###
3728)]
3729fn interpreter<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3730    if let Some(staged) = cx.state.io.interpreter_override() {
3731        return Ok(Value::string(staged));
3732    }
3733    Ok(Value::string(oxdock_process::interpreter_exe()?))
3734}
3735
3736/// Report whether the current context is the entry script.
3737///
3738/// True at entry top level and inside entry-owned functions; false
3739/// inside module-owned functions and module init bodies. Lets a
3740/// library file double as a runnable demo: guard the demo with
3741/// `IF IS_MAIN()` so importing it stays side-effect free.
3742///
3743#[oxdock_func(returns = TypeTag::Bool)]
3744#[example(
3745    name = "main",
3746    code = r###"
3747    # Entry top level runs as main.
3748    IMPORT [STD]
3749    LET $m: BOOL = IS_MAIN()
3750    ASSERT_EQ $m true
3751    "###
3752)]
3753#[example(
3754    name = "library doubles as demo",
3755    fence_meta = "roots:unified",
3756    code = r###"
3757    # A library doubles as a runnable demo: guard the demo with
3758    # IF IS_MAIN() so importing it stays side effect free. The
3759    # parent writes both files, then runs each in a fresh
3760    # interpreter: direct execution prints the demo, importing
3761    # it does not. Unified roots: the child inherits one
3762    # workspace, so parent and child see the same files. The
3763    # exact stdout match proves the demo line stays out of the
3764    # importing run.
3765    IMPORT [STD]
3766
3767    # The library under test: demo guarded by IS_MAIN.
3768    WRITE lib.oxfile """
3769        IMPORT [STD]
3770        FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
3771        EXPORT GREET
3772        IF IS_MAIN() {
3773            ECHO "demo: hi Ada"
3774        }
3775        """
3776
3777    # The importer: calls the library, prints only its own line.
3778    WRITE main.oxfile """
3779        IMPORT ["lib.oxfile" AS LIB]
3780        LET $g: STRING = LIB::GREET("Bo")
3781        ECHO "imported: \{{ $g }}"
3782        """
3783
3784    # Direct run executes the demo.
3785    LET $exe: STRING = INTERPRETER()
3786    LET $direct: STRING = RUN [$exe, "lib.oxfile"]
3787    ASSERT_CONTAINS $direct "demo: hi Ada"
3788
3789    # Importing run stays silent apart from its own line.
3790    LET $via: STRING = RUN [$exe, "main.oxfile"]
3791    ASSERT_EQ $via "imported: hi Bo\n"
3792    "###
3793)]
3794fn is_main<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
3795    let main = match cx.state.module_stack.last() {
3796        None | Some(None) => true,
3797        Some(Some(_)) => false,
3798    };
3799    Ok(Value::bool(main))
3800}
3801
3802/// Report whether a standard stream is a terminal.
3803///
3804/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
3805/// answers for the step's stream as currently bound, so scripts can adapt
3806/// prompts, colors, and progress output. Anything diverted from the
3807/// terminal reports false without touching host handles: `WITH_IO` pipe
3808/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
3809/// runner sinks, and any materialized stdin stream (only a directly
3810/// inherited fd falls back to the process check). A transparent root tee
3811/// still answers the session question via the process check. The name
3812/// matches exactly (no case folding): anything else bails. AST-only:
3813/// reads the step context like the other introspection functions.
3814///
3815#[oxdock_func(returns = TypeTag::Bool)]
3816#[example(
3817    name = "null stdin",
3818    code = r###"
3819    # A null stdin is never a terminal, in every harness.
3820    IMPORT [STD]
3821    LET $term: BOOL = IS_TERMINAL("stdin")
3822    ASSERT_EQ $term false
3823    "###
3824)]
3825fn is_terminal<P: ProcessManager>(
3826    cx: &mut StepCtx<P>,
3827    /// Stream name: `stdin`, `stdout`, or `stderr` (exact match).
3828    #[values("stdin", "stdout", "stderr")]
3829    stream_name: String,
3830) -> Result<Value> {
3831    use std::io::IsTerminal;
3832    let terminal = match stream_name.as_str() {
3833        "stdin" => {
3834            // A script-pipe backend is definitive; Null is /dev/null.
3835            // Only a directly inherited fd answers the process check: a
3836            // materialized Stream is always a binding (staged input,
3837            // WITH_IO pipe, or OS half), never the raw fd.
3838            if cx.stdin_pipe.is_some() {
3839                false
3840            } else {
3841                match &cx.stdin {
3842                    CommandStdin::Null => false,
3843                    #[cfg(not(miri))]
3844                    CommandStdin::OsPipe(_) => false,
3845                    CommandStdin::Stream(_) => false,
3846                    CommandStdin::Inherit => std::io::stdin().is_terminal(),
3847                }
3848            }
3849        }
3850        "stdout" => {
3851            if cx.out_pipe.is_some() {
3852                // WITH_IO script-pipe binding: never a terminal.
3853                false
3854            } else if cx.state.io.stdout().is_some() {
3855                // Staged runner sink: the root tee diverts bytes to the
3856                // sink only, never to real stdout.
3857                false
3858            } else {
3859                match &cx.out {
3860                    // Unbound: inherited straight through.
3861                    None => std::io::stdout().is_terminal(),
3862                    // OS kernel pipe: never a terminal.
3863                    #[cfg(not(miri))]
3864                    Some(StreamHandle::Os(_)) => false,
3865                    // Root tee (transparent: forwards to real stdout when
3866                    // unstaged, so terminal-ness survives) versus a genuine
3867                    // diversion. WITH_IO bindings never reach here (script
3868                    // pipes trip out_pipe, OS pipes trip Os, staged sinks
3869                    // trip above). LET-capture cannot reach here either:
3870                    // assign_capture installs no sink for a bare NAME(...)
3871                    // call, so a direct query always observes the ambient
3872                    // routing. The process check answers the session
3873                    // question.
3874                    Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
3875                }
3876            }
3877        }
3878        "stderr" => {
3879            if cx.state.io.stderr().is_some() {
3880                // Staged runner sink: diverted, never a terminal.
3881                false
3882            } else {
3883                match &cx.err {
3884                    // Unbound: inherited straight through.
3885                    None => std::io::stderr().is_terminal(),
3886                    // OS kernel pipe: never a terminal.
3887                    #[cfg(not(miri))]
3888                    Some(StreamHandle::Os(_)) => false,
3889                    // Root never tees stderr and LET never captures it,
3890                    // so a bound handle here is always a WITH_IO binding.
3891                    Some(StreamHandle::Stream(_)) => false,
3892                }
3893            }
3894        }
3895        _ => anyhow::bail!(
3896            // Unreachable through the macro path: the generated
3897            // extractor rejects non-members before the body runs, and
3898            // the static pre-pass rejects bad literals earlier still.
3899            // Kept as a bail (never a panic) for hand-built callers.
3900            "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
3901        ),
3902    };
3903    Ok(Value::bool(terminal))
3904}
3905
3906/// Create a counting semaphore admitting at most `max` concurrent holders.
3907///
3908/// Non-positive maxima bail. The word names a shared backend: every clone
3909/// observes the same count, and admission runs through
3910/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
3911/// readout.
3912///
3913#[oxdock_func(returns = TypeTag::Semaphore)]
3914#[example(
3915    name = "mint",
3916    code = r###"
3917    # Mint a semaphore admitting at most two holders.
3918    IMPORT [STD]
3919    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
3920
3921    # A fresh semaphore reports its full cap as available.
3922    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
3923    ASSERT_EQ $free 2
3924    "###
3925)]
3926fn semaphore_new<P: ProcessManager>(
3927    cx: &mut StepCtx<P>,
3928    /// Maximum concurrent holders; must be positive.
3929    max: i64,
3930) -> Result<Value> {
3931    let _ = cx;
3932    if max <= 0 {
3933        return Err(anyhow::anyhow!(
3934            "SEMAPHORE_NEW() requires a positive max, got {max}"
3935        ));
3936    }
3937    Ok(Value::semaphore(max as usize))
3938}
3939
3940/// Attempt one non-blocking acquire, always answering a MAP.
3941///
3942/// `held` is `true` with the permit under the `permit` key, or `false`
3943/// with no `permit` key: branch on `$m.held` directly. The DSL has no
3944/// null, so the absent key is the miss shape. Do not read `$m.permit`
3945/// unless `held`: missing-key access bails strictly.
3946/// Never waits, so no wait can wedge.
3947///
3948#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
3949    name: "held".to_string(),
3950    ty: TypeTag::Bool,
3951    docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
3952    optional: false,
3953    default: None,
3954
3955    alias: None,}, Field {
3956    name: "permit".to_string(),
3957    ty: TypeTag::Permit,
3958    docs: "Permit handle; read only when `held`.",
3959    optional: true,
3960    default: None,
3961
3962    alias: None,}])))]
3963#[example(
3964    name = "acquire",
3965    code = r###"
3966    # First acquire holds with a permit to bind.
3967    IMPORT [STD]
3968    LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
3969    LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3970    ASSERT_EQ $first.held true
3971    LET $permit: PERMIT = $first.permit
3972
3973    # A capped semaphore answers held false with no permit key.
3974    LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
3975    ASSERT_EQ $second.held false
3976    LET $has_permit: BOOL = HAS_KEY($second, "permit")
3977    ASSERT_EQ $has_permit false
3978    "###
3979)]
3980fn semaphore_try_acquire<P: ProcessManager>(
3981    cx: &mut StepCtx<P>,
3982    /// Semaphore handle from `SEMAPHORE_NEW`.
3983    sem: Arc<SemaphoreState>,
3984) -> Result<Value> {
3985    let _ = cx;
3986    let mut map = BTreeMap::new();
3987    if sem.try_acquire() {
3988        map.insert("held".to_string(), Value::bool(true));
3989        map.insert("permit".to_string(), Value::permit(&sem));
3990    } else {
3991        map.insert("held".to_string(), Value::bool(false));
3992    }
3993    Ok(Value::map(map))
3994}
3995
3996/// Read free permits under the lock, with no mutation.
3997///
3998/// Observability only (audit lines, healthchecks: `active = max - free`).
3999/// Exact at read time and stale the instant the caller acts on it, so it
4000/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
4001///
4002#[oxdock_func(pure, returns = TypeTag::Int)]
4003#[example(
4004    name = "readout",
4005    code = r###"
4006    # Hold one permit on a cap of two.
4007    IMPORT [STD]
4008    LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
4009    LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
4010    ASSERT_EQ $acq.held true
4011
4012    # One held permit leaves exactly one free.
4013    LET $free: INT = SEMAPHORE_AVAILABLE($sem)
4014    ASSERT_EQ $free 1
4015    "###
4016)]
4017fn semaphore_available(
4018    /// Semaphore handle from `SEMAPHORE_NEW`.
4019    sem: Arc<SemaphoreState>,
4020) -> Result<Value> {
4021    Ok(Value::int(sem.available() as i64))
4022}
4023
4024/// Trim Unicode whitespace from both ends of text.
4025///
4026/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
4027/// Pipes stream on a pump thread with O(chunk) memory: leading
4028/// whitespace falls at the stream head while trailing whitespace
4029/// holds in the spill substrate until the next segment proves it
4030/// interior, so unbounded streams never buffer unbounded memory.
4031///
4032#[oxdock_func(
4033    rpn,
4034    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4035    template = text_trim_string
4036)]
4037#[example(
4038    name = "trim",
4039    code = r###"
4040    # Leading and trailing whitespace falls away.
4041    IMPORT [STD]
4042    LET $clean: STRING = TEXT_TRIM("  hello  ")
4043    ASSERT_EQ $clean "hello"
4044    "###
4045)]
4046#[example(
4047    name = "trim pipe mirrors",
4048    code = r###"
4049    # Pipe input mints pipe output with the same transform.
4050    IMPORT [STD]
4051    LET $cap: PIPE
4052    WITH_IO [stdout=$cap] {
4053        ECHO "  hello  "
4054    }
4055    LET $out: PIPE = TEXT_TRIM($cap)
4056    WITH_IO [stdin=$out] READ_LINE $line
4057    ASSERT_EQ $line "hello"
4058    "###
4059)]
4060#[example(
4061    name = "trim template",
4062    code = r###"
4063    # String inputs run inside placeholders too.
4064    IMPORT [STD]
4065    LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM("  hello  ") }}'
4066    ASSERT_EQ $msg "clean:hello"
4067    "###
4068)]
4069#[example(
4070    name = "trim file template",
4071    code = r###"
4072    # EXPAND templates resolve the same registry.
4073    IMPORT [STD]
4074    WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\"  hello  \") }}"
4075    LET $out: STRING = EXPAND "tpl.txt"
4076    ASSERT_EQ $out "clean:hello"
4077    "###
4078)]
4079fn text_trim<P: ProcessManager>(
4080    cx: &mut StepCtx<P>,
4081    /// Text to trim.
4082    #[union(String, Pipe)]
4083    text: Value,
4084) -> Result<Value> {
4085    super::args::mirror_stream(cx, "TEXT_TRIM", &text, super::args::TextPump::Trim)
4086}
4087
4088/// Template projection of `TEXT_TRIM`: the same trim for `{{ }}`
4089/// placeholders, which carry no step IO for pipes.
4090fn text_trim_string(text: Value) -> Result<Value> {
4091    super::args::mirror_string("TEXT_TRIM", &text, super::args::TextPump::Trim)
4092}
4093
4094/// Strip one leading prefix, returning the input unchanged when absent.
4095///
4096/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
4097/// Pipes decide on the first `prefix.len()` bytes and stream the rest
4098/// untouched. Matching is case-sensitive; there is no
4099/// case-insensitive mode.
4100/// Used for tag prefix strips such as `v1.2.3` to `1.2.3`.
4101///
4102#[oxdock_func(
4103    rpn,
4104    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4105    template = text_trim_prefix_string
4106)]
4107#[example(
4108    name = "strip prefix",
4109    code = r###"
4110    # A present prefix falls away; absence returns the input unchanged.
4111    IMPORT [STD]
4112    LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
4113    ASSERT_EQ $bare "1.2.3"
4114
4115    # Missing prefixes pass through untouched.
4116    LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
4117    ASSERT_EQ $same "1.2.3"
4118    "###
4119)]
4120#[example(
4121    name = "strip prefix pipe mirrors",
4122    code = r###"
4123    # Pipe input mints pipe output with the same strip.
4124    IMPORT [STD]
4125    LET $cap: PIPE
4126    WITH_IO [stdout=$cap] {
4127        ECHO "v1.2.3"
4128    }
4129    LET $trimmed: PIPE = TEXT_TRIM($cap)
4130    LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
4131    WITH_IO [stdin=$out] READ_LINE $line
4132    ASSERT_EQ $line "1.2.3"
4133    "###
4134)]
4135#[example(
4136    name = "strip prefix template",
4137    code = r###"
4138    # String inputs run inside placeholders too.
4139    IMPORT [STD]
4140    LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
4141    ASSERT_EQ $msg "bare:1.2.3"
4142    "###
4143)]
4144fn text_trim_prefix<P: ProcessManager>(
4145    cx: &mut StepCtx<P>,
4146    /// Text to strip.
4147    #[union(String, Pipe)]
4148    text: Value,
4149    /// Leading prefix to remove once.
4150    prefix: String,
4151) -> Result<Value> {
4152    super::args::mirror_stream(
4153        cx,
4154        "TEXT_TRIM_PREFIX",
4155        &text,
4156        super::args::TextPump::TrimPrefix(prefix),
4157    )
4158}
4159
4160/// Template projection of `TEXT_TRIM_PREFIX`: the same strip for
4161/// `{{ }}` placeholders, which carry no step IO for pipes.
4162fn text_trim_prefix_string(text: Value, prefix: String) -> Result<Value> {
4163    super::args::mirror_string(
4164        "TEXT_TRIM_PREFIX",
4165        &text,
4166        super::args::TextPump::TrimPrefix(prefix),
4167    )
4168}
4169
4170/// Strip one trailing suffix, returning the input unchanged when absent.
4171///
4172/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
4173/// Pipes hold a `suffix.len()` trailing window and stream the rest.
4174/// Matching is case-sensitive; there is no case-insensitive mode.
4175///
4176#[oxdock_func(
4177    rpn,
4178    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4179    template = text_trim_suffix_string
4180)]
4181#[example(
4182    name = "strip suffix",
4183    code = r###"
4184    # A present suffix falls away; absence returns the input unchanged.
4185    IMPORT [STD]
4186    LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
4187    ASSERT_EQ $bare "archive.tar"
4188
4189    # Missing suffixes pass through untouched.
4190    LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
4191    ASSERT_EQ $same "archive.tar"
4192    "###
4193)]
4194#[example(
4195    name = "strip suffix pipe mirrors",
4196    code = r###"
4197    # Pipe input mints pipe output with the same strip.
4198    IMPORT [STD]
4199    LET $cap: PIPE
4200    WITH_IO [stdout=$cap] {
4201        ECHO "archive.tar.gz"
4202    }
4203    LET $trimmed: PIPE = TEXT_TRIM($cap)
4204    LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
4205    WITH_IO [stdin=$out] READ_LINE $line
4206    ASSERT_EQ $line "archive.tar"
4207    "###
4208)]
4209#[example(
4210    name = "strip suffix template",
4211    code = r###"
4212    # String inputs run inside placeholders too.
4213    IMPORT [STD]
4214    LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
4215    ASSERT_EQ $msg "bare:archive.tar"
4216    "###
4217)]
4218fn text_trim_suffix<P: ProcessManager>(
4219    cx: &mut StepCtx<P>,
4220    /// Text to strip.
4221    #[union(String, Pipe)]
4222    text: Value,
4223    /// Trailing suffix to remove once.
4224    suffix: String,
4225) -> Result<Value> {
4226    super::args::mirror_stream(
4227        cx,
4228        "TEXT_TRIM_SUFFIX",
4229        &text,
4230        super::args::TextPump::TrimSuffix(suffix),
4231    )
4232}
4233
4234/// Template projection of `TEXT_TRIM_SUFFIX`: the same strip for
4235/// `{{ }}` placeholders, which carry no step IO for pipes.
4236fn text_trim_suffix_string(text: Value, suffix: String) -> Result<Value> {
4237    super::args::mirror_string(
4238        "TEXT_TRIM_SUFFIX",
4239        &text,
4240        super::args::TextPump::TrimSuffix(suffix),
4241    )
4242}
4243
4244/// Join a directory and a file name with the host-native separator.
4245///
4246/// Both inputs accept `STRING` or workspace `PATH` words; the result
4247/// is a `STRING` joined with the platform separator, so installers
4248/// never hand-roll separators in templates. No filesystem access:
4249/// missing parents fail later at the consumer. Stays `STRING` (not
4250/// `PATH`) on purpose: the joined value is a not-yet-validated
4251/// destination string like `$dir` itself, and `PATH` words
4252/// re-canonicalize to forward slashes on template expansion, which
4253/// would undo the native join.
4254#[oxdock_func(returns = TypeTag::String)]
4255#[example(
4256    name = "join path",
4257    code = r###"
4258    # Directory and file stem join with the native separator.
4259    # Source `\\` is one backslash at runtime; `/` works on Windows
4260    # too, native just reads better there.
4261    IMPORT [STD]
4262    LET $p: STRING = PATH_JOIN("some-dir", "some-file")
4263    [family:unix] ASSERT_EQ $p "some-dir/some-file"
4264    [family:windows] ASSERT_EQ $p "some-dir\\some-file"
4265    "###
4266)]
4267fn path_join<P: ProcessManager>(
4268    _cx: &mut StepCtx<P>,
4269    /// Directory half of the destination.
4270    #[union(String, Path)]
4271    dir: Value,
4272    /// File half of the destination.
4273    #[union(String, Path)]
4274    name: Value,
4275) -> Result<Value> {
4276    let d = super::args::string_or_path_text(&dir)?;
4277    let n = super::args::string_or_path_text(&name)?;
4278    Ok(Value::string(oxdock_fs::join_native(&d, &n)))
4279}
4280
4281/// Final segment of a path (`PATH_BASE`).
4282///
4283/// Pure lexical surgery with no filesystem access: backslashes normalize
4284/// to slashes, trailing slashes trim (root stays `/`), then the text
4285/// after the last slash binds. Empty input fails closed. Runs in
4286/// templates like every pure builtin.
4287///
4288#[oxdock_func(pure, returns = TypeTag::String)]
4289#[example(
4290    name = "base",
4291    code = r###"
4292    # Final segments bind without filesystem access.
4293    IMPORT [STD]
4294    LET $b: STRING = PATH_BASE("some-dir/some-file")
4295    ASSERT_EQ $b "some-file"
4296
4297    # Trailing slashes trim before the split.
4298    LET $d: STRING = PATH_BASE("some-dir/")
4299    ASSERT_EQ $d "some-dir"
4300    "###
4301)]
4302fn path_base(
4303    /// Path whose final segment to bind.
4304    #[union(String, Path)]
4305    path: Value,
4306) -> Result<Value> {
4307    let text = super::args::string_or_path_text(&path)?;
4308    let base = oxdock_fs::path_base(&text).map_err(|e| anyhow::anyhow!("PATH_BASE: {e:#}"))?;
4309    Ok(Value::string(base))
4310}
4311
4312/// Lexical relativization (`PATH_REL`): remainder of a path below a base.
4313///
4314/// Pure string surgery with no filesystem access: both sides normalize
4315/// backslashes to slashes and trim trailing slashes, then `base`
4316/// segments must prefix `path` segments on a segment boundary. Equal
4317/// paths bind `.`; non-prefix inputs fail closed naming both sides.
4318/// Absolute and relative shapes never mix. Runs in templates like
4319/// every pure builtin.
4320///
4321#[oxdock_func(pure, returns = TypeTag::String)]
4322#[example(
4323    name = "relativize",
4324    code = r###"
4325    # Prefix bases strip to their remainder.
4326    IMPORT [STD]
4327    LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
4328    ASSERT_EQ $r "some-file"
4329
4330    # Equal paths bind dot.
4331    LET $dot: STRING = PATH_REL("some-dir", "some-dir")
4332    ASSERT_EQ $dot "."
4333    "###
4334)]
4335fn path_rel(
4336    /// Base prefix segments must match.
4337    #[union(String, Path)]
4338    base: Value,
4339    /// Path below the base to relativize.
4340    #[union(String, Path)]
4341    path: Value,
4342) -> Result<Value> {
4343    let b = super::args::string_or_path_text(&base)?;
4344    let p = super::args::string_or_path_text(&path)?;
4345    let rel = oxdock_fs::path_rel(&b, &p).map_err(|e| anyhow::anyhow!("PATH_REL: {e:#}"))?;
4346    Ok(Value::string(rel))
4347}
4348
4349/// Uppercase text with full Unicode mapping.
4350///
4351/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
4352/// Pipes map chunk by chunk across a char-boundary carry, so
4353/// multibyte characters split across reads still fold correctly.
4354///
4355#[oxdock_func(
4356    rpn,
4357    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4358    template = text_to_upper_string
4359)]
4360#[example(
4361    name = "uppercase",
4362    code = r###"
4363    # Text folds to uppercase.
4364    IMPORT [STD]
4365    LET $loud: STRING = TEXT_TO_UPPER("hello")
4366    ASSERT_EQ $loud "HELLO"
4367    "###
4368)]
4369#[example(
4370    name = "uppercase pipe mirrors",
4371    code = r###"
4372    # Pipe input mints pipe output with the same fold.
4373    IMPORT [STD]
4374    LET $cap: PIPE
4375    WITH_IO [stdout=$cap] {
4376        ECHO "hello"
4377    }
4378    LET $out: PIPE = TEXT_TO_UPPER($cap)
4379    WITH_IO [stdin=$out] READ_LINE $line
4380    ASSERT_EQ $line "HELLO"
4381    "###
4382)]
4383#[example(
4384    name = "uppercase template",
4385    code = r###"
4386    # String inputs run inside placeholders too.
4387    IMPORT [STD]
4388    LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
4389    ASSERT_EQ $msg "loud:HELLO"
4390    "###
4391)]
4392fn text_to_upper<P: ProcessManager>(
4393    cx: &mut StepCtx<P>,
4394    /// Text to uppercase.
4395    #[union(String, Pipe)]
4396    text: Value,
4397) -> Result<Value> {
4398    super::args::mirror_stream(cx, "TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
4399}
4400
4401/// Template projection of `TEXT_TO_UPPER`: the same fold for `{{ }}`
4402/// placeholders, which carry no step IO for pipes.
4403fn text_to_upper_string(text: Value) -> Result<Value> {
4404    super::args::mirror_string("TEXT_TO_UPPER", &text, super::args::TextPump::ToUpper)
4405}
4406
4407/// Lowercase text with full Unicode mapping.
4408///
4409/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
4410/// Pipes map chunk by chunk across a char-boundary carry, like
4411/// `TEXT_TO_UPPER`.
4412///
4413#[oxdock_func(
4414    rpn,
4415    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4416    template = text_to_lower_string
4417)]
4418#[example(
4419    name = "lowercase",
4420    code = r###"
4421    # Text folds to lowercase.
4422    IMPORT [STD]
4423    LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
4424    ASSERT_EQ $quiet "hello"
4425    "###
4426)]
4427#[example(
4428    name = "lowercase pipe mirrors",
4429    code = r###"
4430    # Pipe input mints pipe output with the same fold.
4431    IMPORT [STD]
4432    LET $cap: PIPE
4433    WITH_IO [stdout=$cap] {
4434        ECHO "HELLO"
4435    }
4436    LET $out: PIPE = TEXT_TO_LOWER($cap)
4437    WITH_IO [stdin=$out] READ_LINE $line
4438    ASSERT_EQ $line "hello"
4439    "###
4440)]
4441#[example(
4442    name = "lowercase template",
4443    code = r###"
4444    # String inputs run inside placeholders too.
4445    IMPORT [STD]
4446    LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
4447    ASSERT_EQ $msg "quiet:hello"
4448    "###
4449)]
4450fn text_to_lower<P: ProcessManager>(
4451    cx: &mut StepCtx<P>,
4452    /// Text to lowercase.
4453    #[union(String, Pipe)]
4454    text: Value,
4455) -> Result<Value> {
4456    super::args::mirror_stream(cx, "TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
4457}
4458
4459/// Template projection of `TEXT_TO_LOWER`: the same fold for `{{ }}`
4460/// placeholders, which carry no step IO for pipes.
4461fn text_to_lower_string(text: Value) -> Result<Value> {
4462    super::args::mirror_string("TEXT_TO_LOWER", &text, super::args::TextPump::ToLower)
4463}
4464
4465/// Replace every literal occurrence of `from` with `to`.
4466///
4467/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
4468/// Pipes scan through a `from.len()` sliding window, so needles split
4469/// across chunk reads still rewrite.
4470/// Literal sliding search, not a pattern: an empty `from` fails
4471/// closed, and regex work with captures belongs to
4472/// `TEXT_REPLACE_REGEX`. Matching is case-sensitive; there is no
4473/// case-insensitive mode.
4474///
4475#[oxdock_func(
4476    rpn,
4477    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4478    template = text_replace_string
4479)]
4480#[example(
4481    name = "replace",
4482    code = r###"
4483    # Every literal occurrence rewrites in place.
4484    IMPORT [STD]
4485    LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
4486    ASSERT_EQ $fixed "hello there"
4487    "###
4488)]
4489#[example(
4490    name = "replace pipe mirrors",
4491    code = r###"
4492    # Pipe input mints pipe output with the same rewrite.
4493    IMPORT [STD]
4494    LET $cap: PIPE
4495    WITH_IO [stdout=$cap] {
4496        ECHO "hello world"
4497    }
4498    LET $trimmed: PIPE = TEXT_TRIM($cap)
4499    LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
4500    WITH_IO [stdin=$out] READ_LINE $line
4501    ASSERT_EQ $line "hello there"
4502    "###
4503)]
4504#[example(
4505    name = "replace template",
4506    code = r###"
4507    # String inputs run inside placeholders too.
4508    IMPORT [STD]
4509    LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
4510    ASSERT_EQ $msg "fixed:hello there"
4511    "###
4512)]
4513fn text_replace<P: ProcessManager>(
4514    cx: &mut StepCtx<P>,
4515    /// Text to rewrite.
4516    #[union(String, Pipe)]
4517    text: Value,
4518    /// Literal text to search for; empty fails closed.
4519    from: String,
4520    /// Literal replacement text.
4521    to: String,
4522) -> Result<Value> {
4523    super::args::mirror_stream(
4524        cx,
4525        "TEXT_REPLACE",
4526        &text,
4527        super::args::TextPump::ReplaceLiteral { from, to },
4528    )
4529}
4530
4531/// Template projection of `TEXT_REPLACE`: the same rewrite for `{{ }}`
4532/// placeholders, which carry no step IO for pipes.
4533fn text_replace_string(text: Value, from: String, to: String) -> Result<Value> {
4534    super::args::mirror_string(
4535        "TEXT_REPLACE",
4536        &text,
4537        super::args::TextPump::ReplaceLiteral { from, to },
4538    )
4539}
4540
4541/// Replace every regex match, expanding `$1` and `$name` captures.
4542///
4543/// Accepts `STRING` or `PIPE`; the return mirrors the input kind.
4544/// Eager-only framing: matches span chunks, so pipe inputs stage
4545/// through the spill substrate instead of streaming.
4546/// Bad patterns fail closed naming the pattern and its position.
4547/// Matching is case-sensitive unless the pattern carries an inline
4548/// `(?i)` flag, which makes uppercase and lowercase letters match
4549/// each other.
4550/// The literal counterpart is `TEXT_REPLACE`.
4551///
4552#[oxdock_func(
4553    rpn,
4554    returns = TypeTag::union(vec![TypeTag::String, TypeTag::Pipe]),
4555    template = text_replace_regex_string
4556)]
4557#[example(
4558    name = "replace with captures",
4559    code = r###"
4560    # Capture groups expand in the replacement.
4561    IMPORT [STD]
4562    LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4563    ASSERT_EQ $swapped "13/10/2026"
4564    "###
4565)]
4566#[example(
4567    name = "replace regex pipe mirrors",
4568    code = r###"
4569    # Pipe input mints pipe output with the same rewrite.
4570    IMPORT [STD]
4571    LET $cap: PIPE
4572    WITH_IO [stdout=$cap] {
4573        ECHO "2026-10-13"
4574    }
4575    LET $trimmed: PIPE = TEXT_TRIM($cap)
4576    LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1")
4577    WITH_IO [stdin=$out] READ_LINE $line
4578    ASSERT_EQ $line "13/10/2026"
4579    "###
4580)]
4581#[example(
4582    name = "replace regex template",
4583    code = r###"
4584    # String inputs run inside placeholders too.
4585    IMPORT [STD]
4586    LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\\d+)-(\\d+)-(\\d+)", "$3/$2/$1") }}'
4587    ASSERT_EQ $msg "swapped:13/10/2026"
4588    "###
4589)]
4590fn text_replace_regex<P: ProcessManager>(
4591    cx: &mut StepCtx<P>,
4592    /// Text to rewrite.
4593    #[union(String, Pipe)]
4594    text: Value,
4595    /// Regex pattern to match.
4596    pattern: String,
4597    /// Replacement with `$1` and `$name` capture expansion.
4598    replacement: String,
4599) -> Result<Value> {
4600    if let Some(s) = text.as_str() {
4601        let out =
4602            super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
4603        return Ok(Value::string(out));
4604    }
4605    let content = super::args::read_pipe_eager(cx, "TEXT_REPLACE_REGEX", &text)?;
4606    let out = super::args::text_replace_regex_str(
4607        &content,
4608        &pattern,
4609        &replacement,
4610        "TEXT_REPLACE_REGEX",
4611    )?;
4612    super::args::write_completed_pipe(cx, "TEXT_REPLACE_REGEX", out)
4613}
4614
4615/// Template projection of `TEXT_REPLACE_REGEX`: the same rewrite for
4616/// `{{ }}` placeholders, which carry no step IO for pipes.
4617fn text_replace_regex_string(text: Value, pattern: String, replacement: String) -> Result<Value> {
4618    let Some(s) = text.as_str() else {
4619        return Err(super::args::pipe_needs_step_io("TEXT_REPLACE_REGEX"));
4620    };
4621    let out = super::args::text_replace_regex_str(s, &pattern, &replacement, "TEXT_REPLACE_REGEX")?;
4622    Ok(Value::string(out))
4623}
4624
4625/// Split text on a literal delimiter into a `LIST<STRING>`.
4626///
4627/// An empty delimiter splits into single characters. Eager-only by
4628/// design: splitting into a list has no line framing to stream.
4629/// Delimiters match case-sensitively; there is no
4630/// case-insensitive mode.
4631///
4632#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4633#[example(
4634    name = "split",
4635    code = r###"
4636    # Delimiters split into list items.
4637    IMPORT [STD]
4638    LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
4639    ASSERT_EQ $parts.0 "a"
4640    ASSERT_EQ $parts.1 "b"
4641    ASSERT_EQ $parts.2 "c"
4642    "###
4643)]
4644fn text_split(
4645    /// Text to split.
4646    text: String,
4647    /// Literal delimiter; empty splits into characters.
4648    delimiter: String,
4649) -> Result<Value> {
4650    Ok(super::args::text_list_value(super::args::text_split_str(
4651        &text, &delimiter,
4652    )))
4653}
4654
4655/// Join a `LIST<STRING>` with a literal separator into a `STRING`.
4656///
4657#[oxdock_func(pure, returns = TypeTag::String)]
4658#[example(
4659    name = "join",
4660    code = r###"
4661    # List items join with the separator between them.
4662    IMPORT [STD]
4663    LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
4664    ASSERT_EQ $joined "a,b,c"
4665    "###
4666)]
4667fn text_join(
4668    /// List elements to join.
4669    elements: Vec<String>,
4670    /// Literal delimiter placed between elements.
4671    delimiter: String,
4672) -> Result<Value> {
4673    Ok(Value::string(elements.join(delimiter.as_str())))
4674}
4675
4676/// Split a shell command string into argv words.
4677///
4678/// Parses POSIX shell word syntax (single and double quotes, backslash
4679/// escapes) with the `shell-words` crate, the same splitter the remote
4680/// plugins use. Returns a `LIST<STRING>`. Unbalanced quotes fail.
4681/// Inverse of `SHELL_JOIN_ARGS`: joining the result re-splits
4682/// to the same words.
4683///
4684/// Shell syntax only: plain prose with no quoting splits on
4685/// whitespace like any shell would, which is rarely what prose wants.
4686///
4687#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4688#[example(
4689    name = "split args",
4690    code = r###"
4691    # Quoted segments stay one word.
4692    IMPORT [STD]
4693    LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
4694    ASSERT_EQ $argv.0 "gh"
4695    ASSERT_EQ $argv.3 "153"
4696    ASSERT_EQ $argv.5 "notes.md"
4697
4698    # Quotes and escapes parse the shell way.
4699    LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
4700    ASSERT_EQ $quoted.0 "say"
4701    ASSERT_EQ $quoted.1 "hi there"
4702    ASSERT_EQ $quoted.2 "a b"
4703    "###
4704)]
4705fn shell_split_args(
4706    /// Shell command string to split into words.
4707    command: String,
4708) -> Result<Value> {
4709    match shell_words::split(&command) {
4710        Ok(words) => Ok(super::args::text_list_value(words)),
4711        Err(err) => anyhow::bail!("SHELL_SPLIT_ARGS: {err}"),
4712    }
4713}
4714
4715/// Join argv words into one shell-parseable string.
4716///
4717/// Quotes each word with POSIX single-quote escaping through the
4718/// `shell-words` crate, so the result re-splits to the same words.
4719/// Inverse of `SHELL_SPLIT_ARGS` on the word side: splitting the
4720/// result returns the input list unchanged.
4721///
4722#[oxdock_func(pure, returns = TypeTag::String)]
4723#[example(
4724    name = "join args",
4725    code = r###"
4726    # Plain words join with spaces and no quoting.
4727    IMPORT [STD]
4728    LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
4729    ASSERT_EQ $plain "gh issue list"
4730
4731    # Words with spaces quote, and the round trip is exact.
4732    LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
4733    LET $joined: STRING = SHELL_JOIN_ARGS($words)
4734    LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
4735    ASSERT_EQ $back.0 "say"
4736    ASSERT_EQ $back.1 "hi there"
4737    ASSERT_EQ $back.2 "a'b"
4738    "###
4739)]
4740fn shell_join_args(
4741    /// Words to join into a shell command string.
4742    words: Vec<String>,
4743) -> Result<Value> {
4744    Ok(Value::string(shell_words::join(&words)))
4745}
4746
4747/// Split text into lines with universal newline handling.
4748///
4749/// Normalizes through the line-ending crate first so LF, CRLF, CR,
4750/// and mixed endings all split, then delegates the split itself to
4751/// `LineEnding::split` instead of hand-rolled scanning.
4752/// Returns a `LIST<STRING>`; eager-only like `TEXT_SPLIT`.
4753///
4754#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4755#[example(
4756    name = "lines",
4757    code = r###"
4758    # Newlines split into line items.
4759    IMPORT [STD]
4760    LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
4761    ASSERT_EQ $lines.0 "one"
4762    ASSERT_EQ $lines.1 "two"
4763    ASSERT_EQ $lines.2 "three"
4764
4765    # Windows endings split the same way after normalization.
4766    LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
4767    ASSERT_EQ $crlf.0 "one"
4768    ASSERT_EQ $crlf.1 "two"
4769    ASSERT_EQ $crlf.2 "three"
4770
4771    # Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
4772    LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
4773    ASSERT_EQ $mixed.0 "a"
4774    ASSERT_EQ $mixed.1 "b"
4775    ASSERT_EQ $mixed.2 "c"
4776    ASSERT_EQ $mixed.3 "d"
4777    "###
4778)]
4779fn text_lines(
4780    /// Text to split into lines.
4781    text: String,
4782) -> Result<Value> {
4783    Ok(super::args::text_list_value(super::args::text_lines_str(
4784        &text,
4785    )))
4786}
4787
4788/// Split text into whitespace-separated fields, ignoring empties.
4789///
4790/// Returns a `LIST<STRING>`; the checksum-line parser that replaces
4791/// `cut -d' ' -f1` in CI legs.
4792///
4793#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4794#[example(
4795    name = "fields",
4796    code = r###"
4797    # Runs of whitespace separate fields; empties never appear.
4798    IMPORT [STD]
4799    LET $fields: LIST<STRING> = TEXT_FIELDS("  abc  def ")
4800    ASSERT_EQ $fields.0 "abc"
4801    ASSERT_EQ $fields.1 "def"
4802    "###
4803)]
4804fn text_fields(
4805    /// Text to split into fields.
4806    text: String,
4807) -> Result<Value> {
4808    Ok(super::args::text_list_value(super::args::text_fields_str(
4809        &text,
4810    )))
4811}
4812
4813/// Read lines `from` through `to` as a `LIST<STRING>`: the `sed -n
4814/// 'A,Bp'` window over universal newlines, for reading one file
4815/// section without holding the surrounding text.
4816///
4817/// Lines are 1-based and inclusive on both ends. Ranges past the end
4818/// clamp like sed instead of failing; a start before line 1 or past
4819/// `to` fails closed, since no line reading satisfies it.
4820///
4821#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4822#[example(
4823    name = "line range",
4824    code = r###"
4825    # Lines 2 through 3 come back as a list, 1-based inclusive.
4826    IMPORT [STD]
4827    LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
4828    ASSERT_EQ $window.0 "two"
4829    ASSERT_EQ $window.1 "three"
4830
4831    # Ranges past the end clamp instead of failing.
4832    LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
4833    ASSERT_EQ $tail.0 "two"
4834    "###
4835)]
4836fn text_lines_range(
4837    /// Text whose lines to window.
4838    text: String,
4839    /// First line, 1-based inclusive.
4840    from: i64,
4841    /// Last line, inclusive; past the end clamps.
4842    to: i64,
4843) -> Result<Value> {
4844    Ok(super::args::text_list_value(
4845        super::args::text_lines_range_str(&text, from, to, "TEXT_LINES_RANGE")?,
4846    ))
4847}
4848
4849/// Report whether text matches a regex pattern.
4850///
4851/// Returns `BOOL`. Bad patterns fail closed naming the pattern and
4852/// its position. Matching is case-sensitive unless the pattern
4853/// carries an inline `(?i)` flag, which makes uppercase and lowercase
4854/// letters match each other.
4855///
4856#[oxdock_func(pure, returns = TypeTag::Bool)]
4857#[example(
4858    name = "match",
4859    code = r###"
4860    # Regex matches report true; misses report false.
4861    IMPORT [STD]
4862    LET $hit: BOOL = TEXT_MATCH("abc123", "\\d+")
4863    ASSERT_EQ $hit true
4864
4865    # A miss is false, not a failure.
4866    LET $miss: BOOL = TEXT_MATCH("abc", "^\\d+$")
4867    ASSERT_EQ $miss false
4868    "###
4869)]
4870fn text_match(
4871    /// Text to test.
4872    text: String,
4873    /// Regex pattern to match.
4874    pattern: String,
4875) -> Result<Value> {
4876    let re = super::args::text_compile_pattern("TEXT_MATCH", &pattern)?;
4877    Ok(Value::bool(re.is_match(&text)))
4878}
4879
4880/// Convert a value to BOOL.
4881///
4882/// Trims ASCII whitespace; accepts `true`/`false`, `1`/`0`,
4883/// `yes`/`no`, `on`/`off` in any case. Passes Bool through. Empty
4884/// and anything else fail: an empty string is not a boolean, so
4885/// absent env names (which read empty) must go through `BOOL_OR`
4886/// with a stated default instead of converting here.
4887///
4888#[oxdock_func(pure, name = "BOOL", returns = TypeTag::Bool)]
4889#[example(
4890    name = "convert",
4891    code = r###"
4892    IMPORT [STD]
4893    LET $n: BOOL = BOOL("yes")
4894    ASSERT_EQ $n true
4895    LET $f: BOOL = BOOL("0")
4896    ASSERT_EQ $f false
4897    "###
4898)]
4899fn bool_convert(
4900    /// Value to convert to `BOOL`.
4901    #[union(Bool, String)]
4902    val: Value,
4903) -> Result<Value> {
4904    if let Some(b) = val.as_bool() {
4905        return Ok(Value::bool(b));
4906    }
4907    let Some(s) = val.as_str() else {
4908        return Err(anyhow::anyhow!(
4909            "BOOL needs a Bool or String, found {val:?}"
4910        ));
4911    };
4912    match super::args::parse_bool_str(s) {
4913        Some(b) => Ok(Value::bool(b)),
4914        None => anyhow::bail!("BOOL cannot coerce {s:?} to BOOL"),
4915    }
4916}
4917
4918/// Coerce text to `BOOL`, substituting a default for empty.
4919///
4920/// Returns `BOOL`. Blank input (a declared-but-absent env name, which
4921/// reads empty) resolves to `default` instead of failing, so each flag
4922/// site states its own absent polarity explicitly: negative-polarity
4923/// flags (`dry_run`) default true, positive ones default false. No
4924/// implicit polarity lives in the coercion. Non-blank garbage still
4925/// fails naming the input, exactly like `LET $x: BOOL` coercion.
4926///
4927#[oxdock_func(pure, returns = TypeTag::Bool)]
4928#[example(
4929    name = "absent-default",
4930    code = r###"
4931    # Absent names read empty; the default settles the polarity.
4932    IMPORT [STD]
4933    INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
4934    LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
4935    ASSERT_EQ $dry true
4936
4937    # Present values coerce strictly, ignoring the default.
4938    LET $off: BOOL = BOOL_OR("false", true)
4939    ASSERT_EQ $off false
4940    "###
4941)]
4942fn bool_or(
4943    /// Text to coerce (`true`/`false`, `1`/`0`, `yes`/`no`/`on`/`off`, any case).
4944    text: String,
4945    /// Absent-value default, used when the text is blank.
4946    default: bool,
4947) -> Result<Value> {
4948    if text.trim().is_empty() {
4949        return Ok(Value::bool(default));
4950    }
4951    match super::args::parse_bool_str(&text) {
4952        Some(b) => Ok(Value::bool(b)),
4953        None => anyhow::bail!("BOOL_OR cannot coerce {text:?} to BOOL"),
4954    }
4955}
4956
4957/// Extract capture groups for the first regex match.
4958///
4959/// Returns a `LIST<STRING>` where index 0 is the full match and the
4960/// rest are groups in order; non-participating groups bind empty so
4961/// indexes stay stable. No match binds an empty list. Matching is
4962/// case-sensitive unless the pattern carries an inline `(?i)` flag,
4963/// which makes uppercase and lowercase letters match each other.
4964///
4965#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
4966#[example(
4967    name = "extract",
4968    code = r###"
4969    # Index zero is the full match; groups follow in order.
4970    IMPORT [STD]
4971    LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\\d+)")
4972    ASSERT_EQ $caps.0 "abc123"
4973    ASSERT_EQ $caps.1 "abc"
4974    ASSERT_EQ $caps.2 "123"
4975    "###
4976)]
4977fn text_extract(
4978    /// Text to search.
4979    text: String,
4980    /// Regex pattern with capture groups.
4981    pattern: String,
4982) -> Result<Value> {
4983    let groups = super::args::text_extract_str(&text, &pattern, "TEXT_EXTRACT")?;
4984    Ok(super::args::text_list_value(groups))
4985}
4986
4987/// Report whether text starts with a literal prefix.
4988///
4989/// Returns `BOOL`; the literal check behind tag and target branching
4990/// such as `matrix.target` suffix and prefix tests. Matching is
4991/// case-sensitive; there is no case-insensitive mode.
4992///
4993#[oxdock_func(pure, returns = TypeTag::Bool)]
4994#[example(
4995    name = "starts with",
4996    code = r###"
4997    # Present prefixes report true; misses report false.
4998    IMPORT [STD]
4999    LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
5000    ASSERT_EQ $hit true
5001
5002    # A miss is false, not a failure.
5003    LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
5004    ASSERT_EQ $miss false
5005    "###
5006)]
5007fn text_starts_with(
5008    /// Text to test.
5009    text: String,
5010    /// Literal prefix to look for.
5011    prefix: String,
5012) -> Result<Value> {
5013    Ok(Value::bool(text.starts_with(prefix.as_str())))
5014}
5015
5016/// Report whether text ends with a literal suffix.
5017///
5018/// Returns `BOOL`; the `endsWith(matrix.target, 'linux-musl')`
5019/// check in CI legs. Matching is case-sensitive; there is no
5020/// case-insensitive mode.
5021///
5022#[oxdock_func(pure, returns = TypeTag::Bool)]
5023#[example(
5024    name = "ends with",
5025    code = r###"
5026    # Present suffixes report true; misses report false.
5027    IMPORT [STD]
5028    LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
5029    ASSERT_EQ $hit true
5030
5031    # A miss is false, not a failure.
5032    LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
5033    ASSERT_EQ $miss false
5034    "###
5035)]
5036fn text_ends_with(
5037    /// Text to test.
5038    text: String,
5039    /// Literal suffix to look for.
5040    suffix: String,
5041) -> Result<Value> {
5042    Ok(Value::bool(text.ends_with(suffix.as_str())))
5043}
5044
5045/// Report whether a `STRING` holds a substring or a `LIST` holds a member.
5046///
5047/// Dispatches on the haystack like `LEN`: `STRING` does a literal
5048/// substring search (case-sensitive, no case-insensitive mode);
5049/// `LIST<ANY>` compares members with strict `values_equal` (numeric
5050/// `INT` and `FLOAT` compare across types, every other cross-type pair
5051/// is unequal, matching `SWITCH`). Returns `BOOL`; misses are false,
5052/// never failures.
5053///
5054#[oxdock_func(pure, returns = TypeTag::Bool)]
5055#[example(
5056    name = "contains",
5057    code = r###"
5058    # Present needles report true; misses report false.
5059    IMPORT [STD]
5060    LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
5061    ASSERT_EQ $hit true
5062
5063    # A miss is false, not a failure.
5064    LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
5065    ASSERT_EQ $miss false
5066    "###
5067)]
5068#[example(
5069    name = "contains list",
5070    code = r###"
5071    # List membership uses strict equality across any element type.
5072    IMPORT [STD]
5073    LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
5074    ASSERT_EQ $hit true
5075    LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
5076    ASSERT_EQ $miss false
5077    LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
5078    ASSERT_EQ $num true
5079
5080    # Stringified numbers never coerce to integers.
5081    LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
5082    ASSERT_EQ $strnum false
5083
5084    # Boolean lists match true and miss false with no coercion.
5085    LET $bools: LIST<BOOL> = [true]
5086    LET $bhit: BOOL = CONTAINS($bools, true)
5087    ASSERT_EQ $bhit true
5088    LET $bmiss: BOOL = CONTAINS($bools, false)
5089    ASSERT_EQ $bmiss false
5090    LET $nocoerce: BOOL = CONTAINS($bools, 1)
5091    ASSERT_EQ $nocoerce false
5092    "###
5093)]
5094fn contains(
5095    /// Text to search or list to probe.
5096    #[union(String, List)]
5097    haystack: Value,
5098    /// Literal substring or member to look for.
5099    needle: Value,
5100) -> Result<Value> {
5101    if let Some(text) = haystack.as_str() {
5102        let Some(n) = needle.as_str() else {
5103            return Err(anyhow::anyhow!(
5104                "CONTAINS needs a STRING needle for a STRING haystack, found {}",
5105                needle.type_name()
5106            ));
5107        };
5108        return Ok(Value::bool(text.contains(n)));
5109    }
5110    if let Some(items) = haystack.as_list() {
5111        for item in items {
5112            if super::args::values_equal(item, &needle) {
5113                return Ok(Value::bool(true));
5114            }
5115        }
5116        return Ok(Value::bool(false));
5117    }
5118    Err(anyhow::anyhow!(
5119        "CONTAINS needs a STRING or LIST haystack, found {}",
5120        haystack.type_name()
5121    ))
5122}
5123
5124/// Deduplicate a `LIST`, keeping the first occurrence of each member.
5125///
5126/// Membership uses strict `values_equal` (numeric `INT` and `FLOAT`
5127/// compare across types, every other cross-type pair is unequal,
5128/// matching `CONTAINS` and `==`), so `[1, 1.0]` collapses to one
5129/// element while `["1", 1]` keeps both. Order is first occurrence;
5130/// the empty list binds empty, never failing.
5131#[oxdock_func(pure, returns = TypeTag::List)]
5132#[example(
5133    name = "deduplicate",
5134    code = r###"
5135    # First occurrences win, later repeats drop.
5136    IMPORT [STD]
5137    LET $seen: LIST<STRING> = UNIQUE(["a", "b", "a", "c", "b"])
5138    ASSERT_EQ $seen.0 "a"
5139    ASSERT_EQ $seen.1 "b"
5140    ASSERT_EQ $seen.2 "c"
5141    ASSERT_EQ LEN($seen) 3
5142
5143    # The empty list stays empty.
5144    LET $empty: LIST<STRING> = UNIQUE([])
5145    ASSERT_EQ LEN($empty) 0
5146    "###
5147)]
5148#[example(
5149    name = "strict membership",
5150    code = r###"
5151    # Numerics collapse across INT and FLOAT like CONTAINS.
5152    IMPORT [STD]
5153    LET $nums: LIST<ANY> = UNIQUE([1, 2.0, 1, 3])
5154    ASSERT_EQ $nums.0 1
5155    ASSERT_EQ $nums.1 2.0
5156    ASSERT_EQ $nums.2 3
5157    ASSERT_EQ LEN($nums) 3
5158
5159    # Stringified numbers never coerce to integers.
5160    LET $mixed: LIST<ANY> = UNIQUE(["1", 1])
5161    ASSERT_EQ $mixed.0 "1"
5162    ASSERT_EQ $mixed.1 1
5163    ASSERT_EQ LEN($mixed) 2
5164    "###
5165)]
5166fn unique(
5167    /// List to deduplicate.
5168    items: Vec<Value>,
5169) -> Result<Value> {
5170    let mut out: Vec<Value> = Vec::with_capacity(items.len());
5171    for item in items {
5172        if !out
5173            .iter()
5174            .any(|seen| super::args::values_equal(seen, &item))
5175        {
5176            out.push(item);
5177        }
5178    }
5179    Ok(Value::list(out))
5180}
5181
5182/// Count the elements of a text, list, or map as an `INT`.
5183///
5184/// Strings count Unicode scalars: multibyte characters count once
5185/// each, so this is not the byte length (`"héllo"` binds 5, not 6).
5186/// Lists count elements, maps count entries; empty values bind 0.
5187/// The `${#var}` and `wc -m` counterpart for scripts that size tags,
5188/// digests, and table rows.
5189///
5190#[oxdock_func(pure, returns = TypeTag::Int)]
5191#[example(
5192    name = "length",
5193    code = r###"
5194    # Plain text counts one per character.
5195    IMPORT [STD]
5196    LET $n: INT = LEN("hello")
5197    ASSERT_EQ $n 5
5198
5199    # Multibyte characters count once each, not per byte.
5200    LET $wide: INT = LEN("héllo")
5201    ASSERT_EQ $wide 5
5202
5203    # Lists count elements, maps count entries.
5204    LET $items: LIST<STRING> = ["a", "b", "c"]
5205    LET $nitems: INT = LEN($items)
5206    ASSERT_EQ $nitems 3
5207    LET $row: MAP<name: STRING> = {name: "ada"}
5208    LET $nkeys: INT = LEN($row)
5209    ASSERT_EQ $nkeys 1
5210    LET $empty: INT = LEN([])
5211    ASSERT_EQ $empty 0
5212    "###
5213)]
5214fn len(
5215    /// Value to measure.
5216    #[union(String, List, Map)]
5217    value: Value,
5218) -> Result<Value> {
5219    if let Some(text) = value.as_str() {
5220        return Ok(Value::int(text.chars().count() as i64));
5221    }
5222    if let Some(items) = value.as_list() {
5223        return Ok(Value::int(items.len() as i64));
5224    }
5225    if let Some(entries) = value.as_map() {
5226        return Ok(Value::int(entries.len() as i64));
5227    }
5228    Err(anyhow::anyhow!(
5229        "LEN needs a STRING, LIST, or MAP value, got {}",
5230        value.type_name()
5231    ))
5232}
5233
5234/// Count non-overlapping literal occurrences of a needle.
5235///
5236/// Matches never share bytes, so `"aaa"` holds one `"aa"`, matching
5237/// `grep -o 'aa' | wc -l`. An empty needle fails closed instead of
5238/// binding every character boundary. Matching is case-sensitive;
5239/// there is no case-insensitive mode.
5240///
5241#[oxdock_func(pure, returns = TypeTag::Int)]
5242#[example(
5243    name = "count",
5244    code = r###"
5245    # Every non-overlapping occurrence counts once.
5246    IMPORT [STD]
5247    LET $n: INT = TEXT_COUNT("hello world", "o")
5248    ASSERT_EQ $n 2
5249
5250    # Overlapping candidates never double count.
5251    LET $once: INT = TEXT_COUNT("aaa", "aa")
5252    ASSERT_EQ $once 1
5253    "###
5254)]
5255fn text_count(
5256    /// Text to search.
5257    text: String,
5258    /// Literal needle to count; empty fails closed.
5259    needle: String,
5260) -> Result<Value> {
5261    let n = super::args::text_count_str(&text, &needle, "TEXT_COUNT")?;
5262    Ok(Value::int(n))
5263}
5264
5265/// Count lines matching a regex pattern.
5266///
5267/// Lines split with universal newline handling, like `TEXT_LINES`,
5268/// and each line reports independently: this is `grep -c`, so a line
5269/// with two matches still counts once. Bad patterns fail closed
5270/// naming the pattern and its position. Matching is case-sensitive
5271/// unless the pattern carries an inline `(?i)` flag, which makes
5272/// uppercase and lowercase letters match each other.
5273///
5274#[oxdock_func(pure, returns = TypeTag::Int)]
5275#[example(
5276    name = "count matches",
5277    code = r###"
5278    # One line matches once no matter how many times it hits.
5279    IMPORT [STD]
5280    LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
5281    ASSERT_EQ $n 2
5282
5283    # A miss binds zero, never an error.
5284    LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
5285    ASSERT_EQ $none 0
5286    "###
5287)]
5288fn text_count_matches(
5289    /// Text whose lines to test.
5290    text: String,
5291    /// Regex pattern tested per line.
5292    pattern: String,
5293) -> Result<Value> {
5294    let n = super::args::text_count_matches_str(&text, &pattern, "TEXT_COUNT_MATCHES")?;
5295    Ok(Value::int(n))
5296}
5297
5298/// Keep the lines matching a regex pattern.
5299///
5300/// Splits with universal newline handling, like `TEXT_LINES`, and
5301/// returns every matching line in order: plain `grep`, so a miss
5302/// binds an empty list instead of failing. A trailing options MAP
5303/// carries `invert`: `TEXT_GREP($text, $pattern, {invert: true})`
5304/// keeps every non-matching line instead, the `grep -v` shape. The
5305/// MAP omits freely; a missing MAP keeps matches. Matching is
5306/// case-sensitive unless the pattern carries an inline `(?i)` flag,
5307/// which makes uppercase and lowercase letters match each other. Bad
5308/// patterns fail closed naming the pattern and its position.
5309///
5310#[oxdock_func(pure, returns = TypeTag::ListOf(std::sync::Arc::new(TypeTag::String)))]
5311#[example(
5312    name = "grep",
5313    code = r###"
5314    # Matching lines come back as a list, in order.
5315    IMPORT [STD]
5316    LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
5317    ASSERT_EQ $hits.0 "one"
5318    ASSERT_EQ $hits.1 "one more"
5319
5320    # A miss binds an empty list, never an error.
5321    LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
5322    LET $joined: STRING = TEXT_JOIN($miss, ",")
5323    ASSERT_EQ $joined ""
5324
5325    # The (?i) flag ignores case, so uppercase lines match too.
5326    LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
5327    ASSERT_EQ $folded.0 "One"
5328    ASSERT_EQ $folded.1 "ONE more"
5329    "###
5330)]
5331#[example(
5332    name = "grep invert",
5333    code = r###"
5334    # The invert option keeps every non-matching line instead.
5335    IMPORT [STD]
5336    LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
5337    ASSERT_EQ $kept.0 "two"
5338
5339    # A pattern matching every line binds an empty list, never an error.
5340    LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
5341    LET $joined: STRING = TEXT_JOIN($none, ",")
5342    ASSERT_EQ $joined ""
5343
5344    # Options ride into placeholders as MAP literals. Placeholder
5345    # strings unescape only backslash and quote, so multiline text
5346    # arrives through a variable.
5347    LET $two_lines: STRING = "one\ntwo"
5348    LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
5349    ASSERT_EQ $msg "kept:two"
5350    "###
5351)]
5352fn text_grep(
5353    /// Text whose lines to filter.
5354    text: String,
5355    /// Regex pattern keeping a line.
5356    pattern: String,
5357    /// Filter settings: `invert`. Omittable: a missing options MAP fills `{}`.
5358    #[options("invert?: BOOL")]
5359    #[optional]
5360    options: BTreeMap<String, Value>,
5361) -> Result<Value> {
5362    // `check_options` in the wrapper verified the shape above (keys
5363    // and value types); the read below narrows infallibly after.
5364    let invert = super::args::text_invert_flag(&options);
5365    Ok(super::args::text_list_value(super::args::text_grep_str(
5366        &text,
5367        &pattern,
5368        invert,
5369        "TEXT_GREP",
5370    )?))
5371}
5372
5373/// True when a pipe sits at end of stream: closed with nothing buffered,
5374/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
5375/// Live writers, pinned keepers, and buffered bytes all answer false.
5376/// Never blocks: a reader already blocked stays blocked, so branch on
5377/// `EOF` before reading, not after. OS pairs and unbound handles answer
5378/// best-effort (kernel bytes are invisible there; see `INSPECT`).
5379/// Non-pipe arguments bail at the boundary: the parameter declares
5380/// `PIPE`, so the extractor and the static pass reject them before
5381/// the body runs.
5382///
5383#[oxdock_func(returns = TypeTag::Bool)]
5384#[example(
5385    name = "drain to end",
5386    code = r###"
5387    # Capture two lines, then drain to end of stream with no sentinel line.
5388    IMPORT [STD]
5389    LET $cap: PIPE
5390    WITH_IO [stdout=$cap] {
5391        ECHO "one"
5392        ECHO "two"
5393    }
5394
5395    # The loop exits on close, and the count proves both lines drained.
5396    LET $n: INT = 0
5397    WHILE !EOF($cap) {
5398        WITH_IO [stdin=$cap] READ_LINE $line
5399        $n = $n + 1
5400    }
5401    ASSERT_EQ $n 2
5402    "###
5403)]
5404fn eof<P: ProcessManager>(
5405    cx: &mut StepCtx<P>,
5406    /// Pipe handle to query for end of stream.
5407    pipe: PipeHandle,
5408) -> Result<Value> {
5409    let info = cx.state.io.inspect_pipe(&pipe);
5410    Ok(Value::bool(info.closed && info.buffered == 0))
5411}
5412
5413/// Field table for the `TASK_POLL` result map. Shared by the declared
5414/// return tag and the generated schema and reference docs, so the
5415/// shape agents see is the shape the builtin builds.
5416fn task_poll_result_fields() -> Arc<[Field]> {
5417    Arc::from(vec![
5418        Field {
5419            name: "state".to_string(),
5420            ty: TypeTag::String,
5421            docs: "Task phase: `running` or `finished`.",
5422            optional: false,
5423            default: None,
5424
5425            alias: None,
5426        },
5427        Field {
5428            name: "ok".to_string(),
5429            ty: TypeTag::Bool,
5430            docs: "True unless the task failed.",
5431            optional: false,
5432            default: None,
5433
5434            alias: None,
5435        },
5436        Field {
5437            name: "stdout_tail".to_string(),
5438            ty: TypeTag::String,
5439            docs: "Bounded stdout tail, live while running.",
5440            optional: false,
5441            default: None,
5442
5443            alias: None,
5444        },
5445        Field {
5446            name: "stderr_tail".to_string(),
5447            ty: TypeTag::String,
5448            docs: "Bounded stderr tail, live while running.",
5449            optional: false,
5450            default: None,
5451
5452            alias: None,
5453        },
5454        Field {
5455            name: "truncated_bytes".to_string(),
5456            ty: TypeTag::Int,
5457            docs: "Dropped head bytes past the per-stream cap.",
5458            optional: false,
5459            default: None,
5460
5461            alias: None,
5462        },
5463        Field {
5464            name: "exit_code".to_string(),
5465            ty: TypeTag::Int,
5466            docs: "Process exit code, present once finished.",
5467            optional: true,
5468            default: None,
5469
5470            alias: None,
5471        },
5472        Field {
5473            name: "result".to_string(),
5474            ty: TypeTag::Any,
5475            docs: "Task `RETURN` value, present on clean finish.",
5476            optional: true,
5477            default: None,
5478
5479            alias: None,
5480        },
5481        Field {
5482            name: "error".to_string(),
5483            ty: TypeTag::String,
5484            docs: "Failure text, present on failed finish.",
5485            optional: true,
5486            default: None,
5487
5488            alias: None,
5489        },
5490    ])
5491}
5492
5493/// Poll a background task without consuming it.
5494///
5495/// Reports the running state, the output tails accumulated so far,
5496/// and the final outcome once finished. Repeated polls are safe, and
5497/// a later `AWAIT` still joins normally. Polling after `AWAIT` fails
5498/// like double-await: the handle is spent.
5499///
5500/// Map keys: `state` always names the phase (`"running"` or
5501/// `"finished"`); `ok` is true unless the task failed; `stdout_tail`
5502/// and `stderr_tail` carry bounded output with `truncated_bytes`
5503/// counting dropped head bytes. Finished tasks add `exit_code`;
5504/// clean finishes add `result`, failed ones add `error` instead.
5505#[oxdock_func(returns = TypeTag::Record(task_poll_result_fields()))]
5506#[example(
5507    name = "running poll",
5508    code = r###"
5509    # A sleeping task is still running on the first poll.
5510    IMPORT [STD]
5511    LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
5512    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)
5513    ASSERT_EQ $m.state "running"
5514    ASSERT_EQ $m.ok true
5515    # Clean up the sleeper so the run ends promptly.
5516    CANCEL $t
5517    "###
5518)]
5519#[example(
5520    name = "finished poll",
5521    code = r###"
5522    # A finished task reports its value and final tails, then still awaits.
5523    IMPORT [STD]
5524    LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
5525    # Do other work while the task runs; poll once it should be done.
5526    SLEEP 2s
5527    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)
5528    ASSERT_EQ $m.state "finished"
5529    ASSERT_EQ $m.result "done"
5530    LET $o: STRING = AWAIT $t
5531    ASSERT_EQ $o "done"
5532    "###
5533)]
5534fn task_poll<P: ProcessManager>(
5535    cx: &mut StepCtx<P>,
5536    /// Task handle from ASYNC.
5537    task: HandleValue,
5538) -> Result<Value> {
5539    let entry =
5540        super::handlers::resolve_task_entry_by_id(task.0, &format!("TASK_POLL({})", task.0), cx)?;
5541    let obs = entry.observe_completion();
5542    let (stdout_tail, stderr_tail, dropped) = entry.snapshot_tails();
5543    let mut out = BTreeMap::new();
5544    out.insert(
5545        "state".to_string(),
5546        Value::string(if obs.running { "running" } else { "finished" }.to_string()),
5547    );
5548    out.insert("ok".to_string(), Value::bool(obs.ok));
5549    if !obs.running {
5550        out.insert("exit_code".to_string(), Value::int(obs.exit_code));
5551    }
5552    if let Some(result) = obs.result {
5553        out.insert("result".to_string(), result);
5554    }
5555    if !obs.error.is_empty() {
5556        out.insert("error".to_string(), Value::string(obs.error));
5557    }
5558    out.insert("stdout_tail".to_string(), Value::string(stdout_tail));
5559    out.insert("stderr_tail".to_string(), Value::string(stderr_tail));
5560    out.insert(
5561        "truncated_bytes".to_string(),
5562        Value::int(dropped.min(i64::MAX as u64) as i64),
5563    );
5564    Ok(Value::map(out))
5565}
5566
5567fn meta_to_value(meta: &FuncMeta) -> Value {
5568    let mut map = BTreeMap::new();
5569    map.insert("name".to_string(), Value::string(meta.name.clone()));
5570    map.insert("module".to_string(), Value::string(meta.module.clone()));
5571    map.insert(
5572        "kind".to_string(),
5573        Value::string(meta.kind.label().to_string()),
5574    );
5575    let params = match &meta.params {
5576        Some(params) => Value::list(
5577            params
5578                .iter()
5579                .map(|p| {
5580                    let mut entry = BTreeMap::new();
5581                    entry.insert("name".to_string(), Value::string(p.name.clone()));
5582                    entry.insert(
5583                        "param_type".to_string(),
5584                        Value::string(
5585                            p.param_type
5586                                .as_ref()
5587                                .map(render_structural)
5588                                .unwrap_or_default(),
5589                        ),
5590                    );
5591                    entry.insert(
5592                        "allowed".to_string(),
5593                        Value::string(
5594                            p.allowed
5595                                .map(|values| values.join(", "))
5596                                .unwrap_or_default(),
5597                        ),
5598                    );
5599                    entry.insert("docs".to_string(), Value::string(String::new()));
5600                    entry.insert("optional".to_string(), Value::bool(p.optional));
5601                    entry.insert(
5602                        "options".to_string(),
5603                        match p.options {
5604                            Some(keys) => Value::list(
5605                                keys.iter()
5606                                    .map(|key| {
5607                                        let mut option = BTreeMap::new();
5608                                        option.insert(
5609                                            "name".to_string(),
5610                                            Value::string(key.name.to_string()),
5611                                        );
5612                                        option.insert(
5613                                            "value_type".to_string(),
5614                                            Value::string(render_structural(&key.value)),
5615                                        );
5616                                        option.insert(
5617                                            "required".to_string(),
5618                                            Value::bool(key.required),
5619                                        );
5620                                        option.insert(
5621                                            "default".to_string(),
5622                                            Value::string(
5623                                                key.default.unwrap_or_default().to_string(),
5624                                            ),
5625                                        );
5626                                        Value::map(option)
5627                                    })
5628                                    .collect(),
5629                            ),
5630                            None => Value::string(String::new()),
5631                        },
5632                    );
5633                    Value::map(entry)
5634                })
5635                .collect(),
5636        ),
5637        // Parameterless functions mint an empty LIST, never an empty
5638        // STRING: the `DESCRIBE` return tag promises `LIST<MAP<ANY>>`
5639        // for every entry, and the boundary enforces it.
5640        None => Value::list(Vec::new()),
5641    };
5642    map.insert("params".to_string(), params);
5643    map.insert(
5644        "returns".to_string(),
5645        Value::string(
5646            meta.returns
5647                .as_ref()
5648                .map(render_structural)
5649                .unwrap_or_default(),
5650        ),
5651    );
5652    map.insert("rpn".to_string(), Value::bool(meta.rpn));
5653    map.insert(
5654        "summary".to_string(),
5655        Value::string(meta.summary.to_string()),
5656    );
5657    Value::map(map)
5658}
5659
5660/// One named record schema: a shape host functions produce and scripts
5661/// bind by name (`LET $s: SSH_SESSION_INFO`). Travels with its module
5662/// so schemas register exactly when their producer does.
5663#[derive(Debug, Clone)]
5664pub struct RecordSchema {
5665    pub name: &'static str,
5666    pub fields: std::sync::Arc<[Field]>,
5667}
5668
5669/// One host library: functions and types registered under a single module
5670/// name. `Engine::register_module` stages these; runs expose them as
5671/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
5672#[derive(Clone)]
5673pub struct HostModule<P: ProcessManager> {
5674    pub name: String,
5675    pub funcs: Vec<HostRegistration<P>>,
5676    pub types: Vec<&'static TypeDescriptor>,
5677    pub record_schemas: Vec<RecordSchema>,
5678    /// Shared module state (endpoint registries and the like), stashed
5679    /// at registration and reachable from bodies through
5680    /// `StepCtx::module_state`. Lets every entry stay `#[oxdock_func]`:
5681    /// the macro only generates closers-over-nothing, so state that
5682    /// cannot ride in a value travels here instead of a hand-built
5683    /// closure. Prefer `.with_state(...)` over spelling this field.
5684    pub states: Vec<ModuleState>,
5685}
5686
5687/// One shared state object traveling with its module. Keyed by the
5688/// owning module name plus the value type at registration, so two
5689/// modules sharing one state type never collide.
5690#[derive(Clone)]
5691pub struct ModuleState {
5692    id: std::any::TypeId,
5693    state: std::sync::Arc<dyn std::any::Any + Send + Sync>,
5694}
5695
5696/// A pre-run steps inspection: pure function of the parsed steps,
5697///
5698/// shared so the struct field stays under the complexity lint.
5699pub type PreRunInspector = dyn Fn(&[Step]) -> Result<()> + Send + Sync;
5700
5701/// A pre-run check riding in a module's `states`: the runner executes
5702/// every staged check against the parsed steps before the first step
5703/// runs, so unmapped services fail fast with zero side effects. Modules
5704/// attach one with `.with_state(Arc::new(check))`; the runner discovers
5705/// them by type, so no struct field or plugin knowledge is needed here.
5706#[derive(Clone)]
5707pub struct PreRunCheck {
5708    check: Arc<PreRunInspector>,
5709}
5710
5711impl PreRunCheck {
5712    /// Wrap a steps inspector as a pre-run check.
5713    pub fn new(check: impl Fn(&[Step]) -> Result<()> + Send + Sync + 'static) -> Self {
5714        Self {
5715            check: Arc::new(check),
5716        }
5717    }
5718
5719    /// Run the inspection: `Ok` lets execution start.
5720    pub fn run(&self, steps: &[Step]) -> Result<()> {
5721        (self.check)(steps)
5722    }
5723}
5724
5725impl<P: ProcessManager> HostModule<P> {
5726    /// Attach shared state for bodies to fetch with
5727    /// `cx.module_state::<T>("MODULE")`. Chainable, like registration.
5728    pub fn with_state<T: Send + Sync + 'static>(mut self, state: std::sync::Arc<T>) -> Self {
5729        self.states.push(ModuleState {
5730            id: std::any::TypeId::of::<T>(),
5731            state,
5732        });
5733        self
5734    }
5735
5736    /// Run every staged [`PreRunCheck`] against already-parsed steps.
5737    /// The runner calls this before the first step executes; the first
5738    /// failing check aborts the run with no side effects.
5739    pub fn check_pre_run(&self, steps: &[Step]) -> Result<()> {
5740        for state in &self.states {
5741            if let Some(check) = state.state.downcast_ref::<PreRunCheck>() {
5742                check.run(steps)?;
5743            }
5744        }
5745        Ok(())
5746    }
5747}
5748
5749impl<P: ProcessManager> ExecState<P> {
5750    /// Register one [`HostModule`]: every function becomes callable as
5751    /// `MODULE::NAME`, every type joins the run's name directory.
5752    pub fn register_module(&mut self, module: HostModule<P>) {
5753        for registration in module.funcs {
5754            match registration {
5755                HostRegistration::Stateful { name, meta, func } => {
5756                    self.functions.register_host(&module.name, name, meta, func);
5757                }
5758                HostRegistration::Pure { name, meta, func } => {
5759                    self.functions
5760                        .register_pure_host(&module.name, name, meta, func);
5761                }
5762                HostRegistration::Both {
5763                    name,
5764                    meta,
5765                    func,
5766                    template,
5767                } => {
5768                    self.functions
5769                        .register_both_host(&module.name, name, meta, func, template);
5770                }
5771            }
5772        }
5773        for descriptor in module.types {
5774            self.register_type(descriptor);
5775        }
5776        for schema in module.record_schemas {
5777            self.register_record_schema(schema.name, schema.fields);
5778        }
5779        for state in module.states {
5780            self.module_states
5781                .insert((module.name.clone(), state.id), state.state);
5782        }
5783    }
5784
5785    /// All visible functions: natives plus hosts plus current DSL definitions.
5786    pub fn list_functions(&self) -> Vec<FuncMeta> {
5787        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
5788        // TODO: Make a "virtual function" and don't hardcode
5789        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
5790            out.push(FuncMeta {
5791                name: KEYWORD_INSPECT.to_string(),
5792                module: STD_MODULE_NAME.to_string(),
5793                kind: FuncKind::HostCtx,
5794                params: None,
5795                returns: Some(TypeTag::Map),
5796                rpn: false,
5797                summary: "Inspect a variable binding.",
5798                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5799                examples: &[],
5800            });
5801        }
5802        out.sort_by(|a, b| a.name.cmp(&b.name));
5803        out
5804    }
5805
5806    /// Describe one function by name, or `None` when unknown.
5807    pub fn describe_function(&self, name: &str) -> Option<Value> {
5808        if let Some(meta) = self.functions.meta(name) {
5809            return Some(meta_to_value(&meta));
5810        }
5811        // TODO: Make a "virtual function" and don't hardcode
5812        if name == KEYWORD_INSPECT {
5813            return Some(meta_to_value(&FuncMeta {
5814                name: KEYWORD_INSPECT.to_string(),
5815                module: STD_MODULE_NAME.to_string(),
5816                kind: FuncKind::HostCtx,
5817                params: None,
5818                returns: Some(TypeTag::Map),
5819                rpn: false,
5820                summary: "Inspect a variable binding.",
5821                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
5822                examples: &[],
5823            }));
5824        }
5825        None
5826    }
5827
5828    /// Shared snapshot of every registered pure function for
5829    /// placeholder and host driven expansion. Public so host crates
5830    /// resolve calls through the live registry instead of hardcoding
5831    /// module or function names. Cloning the `Arc` never copies the map.
5832    pub fn pure_function_table(&self) -> Arc<PureTable> {
5833        self.functions.pure_shared()
5834    }
5835}
5836
5837#[cfg(test)]
5838mod tests {
5839    use super::*;
5840
5841    #[test]
5842    fn placeholder_resolver_dispatches_table_entries() {
5843        // Single dispatch implementation for every expansion path:
5844        // known names route to the entry, unknown names fail with
5845        // the sorted known-functions listing.
5846        let echo: PureFn = Arc::new(|args| {
5847            args.into_iter()
5848                .next()
5849                .ok_or_else(|| anyhow::anyhow!("ECHO needs 1 arg"))
5850        });
5851        let mut entries = HashMap::new();
5852        entries.insert("ECHO".to_string(), echo);
5853        let mut table = PureTable::new();
5854        table.insert("T".to_string(), entries);
5855        let resolve = placeholder_resolver(Arc::new(table));
5856        let out = resolve("T", "ECHO", vec![Value::string("hi".to_string())]).expect("dispatch");
5857        assert_eq!(out.as_str().expect("string"), "hi");
5858        let err = format!(
5859            "{:#}",
5860            resolve("T", "NOPE", vec![]).expect_err("unknown must fail")
5861        );
5862        assert!(
5863            err.contains("unknown placeholder function 'T::NOPE'"),
5864            "names the call: {err}"
5865        );
5866        assert!(
5867            err.contains("known functions: T::ECHO"),
5868            "lists known names: {err}"
5869        );
5870    }
5871
5872    #[test]
5873    fn describe_entry_renders_union_spellings() {
5874        // Union params and returns render through the same structural
5875        // renderer every other tag uses: `DESCRIBE` (and the generated
5876        // reference built on it) names the admission set, never a
5877        // bare word or an empty string. Built by macro, so the
5878        // spelling cannot drift from the members.
5879        let union = oxdock_parser::union_tag!(String, Pipe);
5880        let meta = FuncMeta {
5881            name: "T::F".to_string(),
5882            module: "T".to_string(),
5883            kind: FuncKind::HostPure,
5884            params: Some(vec![FuncParam {
5885                name: "text".to_string(),
5886                param_type: Some(union.clone()),
5887                allowed: None,
5888                docs: "",
5889                options: None,
5890                optional: false,
5891            }]),
5892            returns: Some(union),
5893            rpn: false,
5894            summary: "test-only",
5895            docs: "test-only",
5896            examples: &[],
5897        };
5898        let value = meta_to_value(&meta);
5899        let map = value.as_map().expect("describe value is a map");
5900        let params = map
5901            .get("params")
5902            .expect("params key")
5903            .as_list()
5904            .expect("params is a list");
5905        let first = params[0].as_map().expect("entry is a map");
5906        assert_eq!(
5907            first.get("param_type").and_then(Value::as_str),
5908            Some("STRING|PIPE"),
5909            "param renders the set"
5910        );
5911        assert_eq!(
5912            map.get("returns").and_then(Value::as_str),
5913            Some("STRING|PIPE"),
5914            "returns render the set"
5915        );
5916    }
5917
5918    #[test]
5919    fn describe_entry_renders_handle_payload() {
5920        // Shaped handles render structurally (HANDLE<STRING>, not
5921        // bare HANDLE): script ASYNC FUNC declarations surface their
5922        // payload through DESCRIBE exactly as declared.
5923        let meta = FuncMeta {
5924            name: "SCRIPT::FETCH".to_string(),
5925            module: "SCRIPT".to_string(),
5926            kind: FuncKind::Script,
5927            params: Some(vec![]),
5928            returns: Some(TypeTag::HandleOf(std::sync::Arc::new(TypeTag::String))),
5929            rpn: false,
5930            summary: "test-only",
5931            docs: "test-only",
5932            examples: &[],
5933        };
5934        let value = meta_to_value(&meta);
5935        let map = value.as_map().expect("describe value is a map");
5936        assert_eq!(
5937            map.get("returns").and_then(Value::as_str),
5938            Some("HANDLE<STRING>"),
5939            "returns render the payload"
5940        );
5941    }
5942
5943    #[test]
5944    fn describe_entry_carries_optional_flag() {
5945        // The `optional` key on params entries is the machine-readable
5946        // half of the `?` rendering: pin both values through the same
5947        // builder the runtime serves, not through prose.
5948        let meta = FuncMeta {
5949            name: "T::F".to_string(),
5950            module: "T".to_string(),
5951            kind: FuncKind::HostPure,
5952            params: Some(vec![
5953                FuncParam {
5954                    name: "url".to_string(),
5955                    param_type: Some(TypeTag::String),
5956                    allowed: None,
5957                    docs: "",
5958                    options: None,
5959                    optional: false,
5960                },
5961                FuncParam {
5962                    name: "options".to_string(),
5963                    param_type: Some(TypeTag::Map),
5964                    allowed: None,
5965                    docs: "",
5966                    options: None,
5967                    optional: true,
5968                },
5969            ]),
5970            returns: Some(TypeTag::String),
5971            rpn: false,
5972            summary: "test-only",
5973            docs: "test-only",
5974            examples: &[],
5975        };
5976        let value = meta_to_value(&meta);
5977        let map = value.as_map().expect("describe value is a map");
5978        let params = map
5979            .get("params")
5980            .expect("params key")
5981            .as_list()
5982            .expect("params is a list");
5983        assert_eq!(params.len(), 2);
5984        let first = params[0].as_map().expect("entry is a map");
5985        let second = params[1].as_map().expect("entry is a map");
5986        assert_eq!(
5987            first.get("optional").and_then(Value::as_bool),
5988            Some(false),
5989            "required param must read false"
5990        );
5991        assert_eq!(
5992            second.get("optional").and_then(Value::as_bool),
5993            Some(true),
5994            "omittable param must read true"
5995        );
5996    }
5997
5998    #[test]
5999    fn template_twins_mirror_string_paths_and_refuse_pipes() {
6000        // Every template twin answers strings through the shared pump
6001        // semantics and refuses pipes naming the step IO they need:
6002        // placeholder evaluation carries no step context to pump
6003        // through. Table-driven so a twinless mirror op fails here
6004        // naming it.
6005        let pipe = Value::pipe_fresh();
6006        type TwinCase = (&'static str, Box<dyn Fn() -> Result<Value>>);
6007        let cases: Vec<TwinCase> = vec![
6008            (
6009                "TEXT_TRIM",
6010                Box::new(|| text_trim_string(Value::string("  hello  ".to_string()))),
6011            ),
6012            (
6013                "TEXT_TRIM_PREFIX",
6014                Box::new(|| {
6015                    text_trim_prefix_string(Value::string("v1".to_string()), "v".to_string())
6016                }),
6017            ),
6018            (
6019                "TEXT_TRIM_SUFFIX",
6020                Box::new(|| {
6021                    text_trim_suffix_string(Value::string("a.gz".to_string()), "x".to_string())
6022                }),
6023            ),
6024            (
6025                "TEXT_TO_UPPER",
6026                Box::new(|| text_to_upper_string(Value::string("hi".to_string()))),
6027            ),
6028            (
6029                "TEXT_TO_LOWER",
6030                Box::new(|| text_to_lower_string(Value::string("HI".to_string()))),
6031            ),
6032            (
6033                "TEXT_REPLACE",
6034                Box::new(|| {
6035                    text_replace_string(
6036                        Value::string("ab".to_string()),
6037                        "b".to_string(),
6038                        "c".to_string(),
6039                    )
6040                }),
6041            ),
6042            (
6043                "TEXT_REPLACE_REGEX",
6044                Box::new(|| {
6045                    text_replace_regex_string(
6046                        Value::string("ab".to_string()),
6047                        "b".to_string(),
6048                        "c".to_string(),
6049                    )
6050                }),
6051            ),
6052        ];
6053        assert_eq!(cases.len(), 7, "every mirror op needs a twin row");
6054        for (name, run) in &cases {
6055            let value = run().unwrap_or_else(|e| panic!("{name} twin must answer strings: {e:#}"));
6056            assert!(
6057                value.as_str().is_some(),
6058                "{name} twin must answer STRING, got {}",
6059                value.type_name()
6060            );
6061        }
6062        assert_eq!(
6063            text_trim_string(Value::string("  hello  ".to_string()))
6064                .expect("trim twin")
6065                .as_str(),
6066            Some("hello")
6067        );
6068        // Pipes refuse through the shared message on every twin.
6069        let pipe_cases: Vec<(&str, Result<Value>)> = vec![
6070            ("TEXT_TRIM", text_trim_string(pipe.clone())),
6071            (
6072                "TEXT_TRIM_PREFIX",
6073                text_trim_prefix_string(pipe.clone(), "v".to_string()),
6074            ),
6075            (
6076                "TEXT_TRIM_SUFFIX",
6077                text_trim_suffix_string(pipe.clone(), ".gz".to_string()),
6078            ),
6079            ("TEXT_TO_UPPER", text_to_upper_string(pipe.clone())),
6080            ("TEXT_TO_LOWER", text_to_lower_string(pipe.clone())),
6081            (
6082                "TEXT_REPLACE",
6083                text_replace_string(pipe.clone(), "a".to_string(), "b".to_string()),
6084            ),
6085            (
6086                "TEXT_REPLACE_REGEX",
6087                text_replace_regex_string(pipe.clone(), "a".to_string(), "b".to_string()),
6088            ),
6089        ];
6090        for (name, result) in pipe_cases {
6091            let err = result.expect_err(&format!("{name} twin must refuse PIPE"));
6092            assert!(
6093                format!("{err:#}").contains("step IO"),
6094                "{name} refusal names the missing context: {err:#}"
6095            );
6096        }
6097    }
6098
6099    #[test]
6100    fn shell_words_join_split_round_trip() {
6101        // Join and split are absolute inverses on the word side: the
6102        // joiner quotes through `shell-words`, the splitter parses the
6103        // same syntax, so every adversarial word survives the round trip.
6104        let words = vec![
6105            "gh".to_string(),
6106            "issue".to_string(),
6107            "comment".to_string(),
6108            "with spaces".to_string(),
6109            "it's".to_string(),
6110            "say \"hi\"".to_string(),
6111            "$HOME".to_string(),
6112            "$(whoami)".to_string(),
6113            "C:\\path\\to".to_string(),
6114            "naïve café".to_string(),
6115            "".to_string(),
6116        ];
6117        let joined = shell_words::join(&words);
6118        let back = shell_words::split(&joined).expect("join output must parse");
6119        assert_eq!(back, words);
6120        assert!(shell_words::split("unbalanced \"quote").is_err());
6121    }
6122
6123    /// Fake module graph for the shared forward walk: export lists,
6124    /// per-file alias targets, and per-file bindings set directly,
6125    /// so every chase branch pins without files or execution.
6126    struct FakeView {
6127        exports: HashMap<String, Vec<String>>,
6128        targets: HashMap<String, AliasTargets>,
6129        bindings: HashMap<String, HashMap<String, bool>>,
6130    }
6131
6132    impl ModuleGraphView for FakeView {
6133        fn const_exports(&self, file: &str) -> Option<&[String]> {
6134            self.exports.get(file).map(Vec::as_slice)
6135        }
6136
6137        fn alias_targets(&self, file: &str) -> AliasTargets {
6138            self.targets.get(file).cloned().unwrap_or_default()
6139        }
6140
6141        fn binding(&self, file: &str, name: &str) -> BindingPresence {
6142            match self.bindings.get(file).and_then(|names| names.get(name)) {
6143                Some(true) => BindingPresence::Const,
6144                Some(false) => BindingPresence::Let,
6145                None => BindingPresence::Absent,
6146            }
6147        }
6148    }
6149
6150    fn fake_targets(pairs: &[(&str, &str)]) -> AliasTargets {
6151        let mut targets = AliasTargets::new();
6152        for (alias, file) in pairs {
6153            targets
6154                .entry((*alias).to_string())
6155                .or_default()
6156                .push((Some((*file).to_string()), None));
6157        }
6158        targets
6159    }
6160
6161    fn os_guard(os: &str) -> GuardExpr {
6162        GuardExpr::Predicate(oxdock_parser::Guard::Attr {
6163            ns: oxdock_parser::Ns::Os,
6164            key: None,
6165            val: Some(os.to_string()),
6166        })
6167    }
6168
6169    #[test]
6170    fn chase_resolves_bare_and_single_forward() {
6171        // Bare entries terminate in place; one forward hop lands on
6172        // the defining file; chains compose hop by hop.
6173        let mut view = FakeView {
6174            exports: HashMap::from([
6175                ("a".to_string(), vec!["N".to_string()]),
6176                ("b".to_string(), vec!["A::N".to_string()]),
6177                ("c".to_string(), vec!["B::N".to_string()]),
6178            ]),
6179            targets: HashMap::from([
6180                ("u".to_string(), fake_targets(&[("B", "b")])),
6181                ("b".to_string(), fake_targets(&[("A", "a")])),
6182                ("c".to_string(), fake_targets(&[("B", "b")])),
6183            ]),
6184            bindings: HashMap::new(),
6185        };
6186        assert_eq!(
6187            chase_const_forward(&view, "a", "N", "U::N").expect("bare"),
6188            vec!["a".to_string()]
6189        );
6190        assert_eq!(
6191            chase_const_forward(&view, "b", "N", "U::N").expect("forward"),
6192            vec!["a".to_string()]
6193        );
6194        view.targets
6195            .insert("u".to_string(), fake_targets(&[("C", "c")]));
6196        assert_eq!(
6197            chase_const_forward(&view, "c", "N", "U::N").expect("chain"),
6198            vec!["a".to_string()]
6199        );
6200    }
6201
6202    #[test]
6203    fn chase_prefers_bare_over_forwards() {
6204        // A local bare definition shadows forwards of the same base:
6205        // the file answers for its own binding.
6206        let view = FakeView {
6207            exports: HashMap::from([("b".to_string(), vec!["N".to_string(), "A::N".to_string()])]),
6208            targets: HashMap::from([("b".to_string(), fake_targets(&[("A", "a")]))]),
6209            bindings: HashMap::new(),
6210        };
6211        assert_eq!(
6212            chase_const_forward(&view, "b", "N", "U::N").expect("bare wins"),
6213            vec!["b".to_string()]
6214        );
6215    }
6216
6217    #[test]
6218    fn chase_rejects_split_forwards() {
6219        // Two forwards of one base in one file fail instead of
6220        // picking one.
6221        let view = FakeView {
6222            exports: HashMap::from([(
6223                "b".to_string(),
6224                vec!["A::N".to_string(), "C::N".to_string()],
6225            )]),
6226            targets: HashMap::new(),
6227            bindings: HashMap::new(),
6228        };
6229        let err = format!(
6230            "{}",
6231            chase_const_forward(&view, "b", "N", "U::N").expect_err("split must fail")
6232        );
6233        assert!(err.contains("ambiguous CONST `U::N`"), "{err}");
6234        assert!(err.contains("A::N") && err.contains("C::N"), "{err}");
6235    }
6236
6237    #[test]
6238    fn chase_names_broken_link_detail() {
6239        // A hop landing nowhere names the break: missing binding,
6240        // unexported CONST, or LET terminal each render distinctly.
6241        let view = FakeView {
6242            exports: HashMap::from([
6243                ("b".to_string(), vec!["A::M".to_string()]),
6244                ("c".to_string(), vec!["A::P".to_string()]),
6245                ("d".to_string(), vec!["A::Q".to_string()]),
6246                ("a".to_string(), Vec::new()),
6247            ]),
6248            targets: HashMap::from([
6249                ("b".to_string(), fake_targets(&[("A", "a")])),
6250                ("c".to_string(), fake_targets(&[("A", "a")])),
6251                ("d".to_string(), fake_targets(&[("A", "a")])),
6252            ]),
6253            bindings: HashMap::from([(
6254                "a".to_string(),
6255                HashMap::from([("P".to_string(), true), ("Q".to_string(), false)]),
6256            )]),
6257        };
6258        let err = format!(
6259            "{}",
6260            chase_const_forward(&view, "b", "M", "U::M").expect_err("missing must fail")
6261        );
6262        assert!(err.contains("does not resolve"), "{err}");
6263        assert!(err.contains("no import alias `A` exports `M`"), "{err}");
6264        let err = format!(
6265            "{}",
6266            chase_const_forward(&view, "c", "P", "U::P").expect_err("unexported must fail")
6267        );
6268        assert!(
6269            err.contains("holds `P` as CONST but does not export it"),
6270            "{err}"
6271        );
6272        let err = format!(
6273            "{}",
6274            chase_const_forward(&view, "d", "Q", "U::Q").expect_err("LET must fail")
6275        );
6276        assert!(
6277            err.contains("is a LET binding and cannot be exported"),
6278            "{err}"
6279        );
6280    }
6281
6282    #[test]
6283    fn chase_rejects_cycles() {
6284        // Mutual forwards never resolve: the walk names the chain
6285        // instead of recursing forever.
6286        let view = FakeView {
6287            exports: HashMap::from([
6288                ("a".to_string(), vec!["B::N".to_string()]),
6289                ("b".to_string(), vec!["A::N".to_string()]),
6290            ]),
6291            targets: HashMap::from([
6292                ("a".to_string(), fake_targets(&[("B", "b")])),
6293                ("b".to_string(), fake_targets(&[("A", "a")])),
6294            ]),
6295            bindings: HashMap::new(),
6296        };
6297        let err = format!(
6298            "{}",
6299            chase_const_forward(&view, "a", "N", "U::N").expect_err("cycle must fail")
6300        );
6301        assert!(err.contains("re-export cycle"), "{err}");
6302    }
6303
6304    #[test]
6305    fn chase_unions_disjoint_guard_branches() {
6306        // One forward over disjoint platform imports chases each live
6307        // branch to its own terminal instead of failing ambiguous.
6308        let mut guarded = AliasTargets::new();
6309        guarded.insert(
6310            "A".to_string(),
6311            vec![
6312                (Some("lin".to_string()), Some(os_guard("linux"))),
6313                (Some("mac".to_string()), Some(os_guard("macos"))),
6314            ],
6315        );
6316        let view = FakeView {
6317            exports: HashMap::from([
6318                ("b".to_string(), vec!["A::N".to_string()]),
6319                ("lin".to_string(), vec!["N".to_string()]),
6320                ("mac".to_string(), vec!["N".to_string()]),
6321            ]),
6322            targets: HashMap::from([("b".to_string(), guarded)]),
6323            bindings: HashMap::new(),
6324        };
6325        assert_eq!(
6326            chase_const_forward(&view, "b", "N", "U::N").expect("disjoint branches"),
6327            vec!["lin".to_string(), "mac".to_string()]
6328        );
6329    }
6330
6331    #[test]
6332    fn holder_classification_sorts_and_rejects() {
6333        // Holders come back sorted; unknown aliases and overlapping
6334        // files report through their own variants.
6335        let view = FakeView {
6336            exports: HashMap::from([
6337                ("b".to_string(), vec!["N".to_string()]),
6338                ("c".to_string(), vec!["N".to_string()]),
6339            ]),
6340            targets: HashMap::new(),
6341            bindings: HashMap::new(),
6342        };
6343        let unit = fake_targets(&[("B", "b"), ("B", "c")]);
6344        match const_holder_files(&view, &unit, "B", "N") {
6345            ConstHolders::Ambiguous { .. } => {}
6346            other => panic!("overlapping holders must be ambiguous, got {other:?}"),
6347        }
6348        match const_holder_files(&view, &unit, "Z", "N") {
6349            ConstHolders::NoAlias => {}
6350            other => panic!("unknown alias must report NoAlias, got {other:?}"),
6351        }
6352        let unit = fake_targets(&[("B", "b")]);
6353        match const_holder_files(&view, &unit, "B", "N") {
6354            ConstHolders::Found(files) => assert_eq!(files, vec!["b".to_string()]),
6355            other => panic!("single holder must be found, got {other:?}"),
6356        }
6357    }
6358}