Skip to main content

oxdock_core/exec/
native.rs

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