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