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