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