oxdock-core 0.24.2-alpha

Core engine for OxDock's Dockerfile-inspired compile-time DSL, orchestrating workspace snapshots and asset embedding.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

use anyhow::Result;
use oxdock_func_macro::oxdock_func;
use oxdock_parser::{
    Field, KEYWORD_INSPECT, SCRIPT_MODULE_NAME, STD_MODULE_NAME, SemaphoreState, Step, TypeTag,
    Value, base_name, qualify, render_structural, split_qualified,
};
use oxdock_pipe::PipeHandle;
use oxdock_process::{CommandStdin, DefaultProcessManager, ProcessManager};

use super::io::StreamHandle;
use super::state::ExecState;
use super::steps::StepCtx;
use super::typing::TypeDescriptor;
use super::typing::check_options;

/// Origin of a callable in the unified function registry. `Script` is an
/// interpreted `FUNC` body; `HostCtx` and `HostPure` are compiled Rust
/// functions (the `#[oxdock_func]` host export macro). Builtins and
/// runtime-registered hosts share the host kinds; only `DESCRIBE` output
/// shows the label, and both host kinds keep rendering as `host`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FuncKind {
    Script,
    HostCtx,
    HostPure,
}

impl FuncKind {
    pub fn label(&self) -> &'static str {
        match self {
            FuncKind::Script => "script",
            FuncKind::HostCtx | FuncKind::HostPure => "host",
        }
    }
}

/// One declared parameter of a registered function. `param_type` is `None`
/// for unconstrained `Value` parameters (the macro accepts any value).
/// `allowed` names the closed value set for constrained `STRING`
/// parameters, declared once via `#[values(...)]`: the generated
/// extractor enforces membership and the reference renders the set,
/// so the list cannot rot apart from the check. `docs` carries the
/// parameter's description (parsed from the `# Arguments` doc section
/// for macro functions, written inline for hand-built entries) and
/// renders into every reference surface. `options` declares the known
/// keys of a `MAP` options parameter: same single-source rule as
/// `allowed`, with per-key types, required flags, defaults, and docs.
/// `optional` marks a trailing `MAP` parameter callers may omit: the
/// runtime fills an empty MAP, and signatures render `= {}`. Only
/// trailing `MAP` params may be optional (run-start validation
/// rejects anything else), so omission always means "no options".
/// The macro never emits optional params: only hand-built entries
/// use them, and only for options MAPs.
#[derive(Debug, Clone)]
pub struct FuncParam {
    pub name: String,
    pub param_type: Option<TypeTag>,
    pub allowed: Option<&'static [&'static str]>,
    pub docs: &'static str,
    pub options: Option<&'static [ParamOption]>,
    pub optional: bool,
}

/// Required argument count: total params minus trailing optionals.
/// Callers may pass any count in `required..=total`; omitted trailing
/// MAPs fill with an empty MAP. Shared by the static arity gate and
/// the runtime gate so the two can never disagree.
pub fn required_arity(params: &[FuncParam]) -> usize {
    params
        .iter()
        .rev()
        .take_while(|param| param.optional)
        .fold(params.len(), |count, _| count - 1)
}

/// Fill omitted trailing optional MAP params with empty MAPs. The
/// caller guarantees `values.len()` is within
/// `required_arity(params)..=params.len()`; anything else is a bug,
/// not a user error, so over- and under-counts panic loudly.
pub fn fill_optional_args(params: &[FuncParam], mut values: Vec<Value>) -> Vec<Value> {
    assert!(
        values.len() <= params.len(),
        "arity gate must run before fill_optional_args"
    );
    assert!(
        values.len() >= required_arity(params),
        "arity gate must run before fill_optional_args"
    );
    while values.len() < params.len() {
        values.push(Value::map(BTreeMap::new()));
    }
    values
}

/// One known key of a `MAP` options parameter: name, value type,
/// whether callers must pass it, the rendered default for optional
/// keys, and what it controls. Declared once per options parameter
/// (macro `#[options(...)]` plus the `# Options` doc section, or
/// inline for hand-built entries) and rendered into signatures,
/// `DESCRIBE` output, and generated references alike.
#[derive(Debug, Clone, Copy)]
pub struct ParamOption {
    pub name: &'static str,
    pub value: TypeTag,
    pub required: bool,
    pub default: Option<&'static str>,
}

/// Introspectable metadata for one function. Single source for
/// `DESCRIBE(name)` output and the static function reference. `rpn` names
/// whether the function also runs on the compiled math path (`true` for
/// pure functions and opted-in stateful ones); everything runs on the AST
/// path.
#[derive(Debug, Clone)]
pub struct FuncMeta {
    pub name: String,
    /// Owning module (`STD` for builtins, `SCRIPT` for DSL definitions,
    /// the host module name otherwise). `name` is always the qualified
    /// `MODULE::BASE` form, so listings and `DESCRIBE` never lose origin.
    pub module: String,
    pub kind: FuncKind,
    pub params: Option<Vec<FuncParam>>,
    pub returns: Option<TypeTag>,
    pub rpn: bool,
    pub summary: &'static str,
    pub docs: &'static str,
}

/// Pure scalar function: no filesystem, no scope, no process access.
/// Usable from both AST evaluation and compiled RPN math.
pub type PureFn = Arc<dyn Fn(Vec<Value>) -> Result<Value> + Send + Sync>;

/// Stateful/IO function with full step context (fs, cwd, envs, vars, pipes).
pub type NativeFn<P> = Arc<dyn Fn(&mut StepCtx<P>, Vec<Value>) -> Result<Value> + Send + Sync>;

/// Export hook for a DSL function, implemented by `#[oxdock_func]` on a
/// registration marker. The engine calls `registration()` and never names
/// a generated symbol.
pub trait OxDockFn<P: ProcessManager> {
    /// The registry entry deriving from the Rust signature plus doc
    /// comments: name, metadata, and entry point, composed.
    fn registration() -> HostRegistration<P>;
}

/// One host-registered function, grouped into a [`HostModule`] and passed
/// to `Engine::register_module`. Build the entry with the `#[oxdock_func]`-
/// generated registration marker, or by hand. `Pure` entries run
/// on both the AST and the compiled RPN math paths; `Stateful` entries run
/// on the AST path with full step context.
pub enum HostRegistration<P: ProcessManager> {
    Stateful {
        name: String,
        meta: FuncMeta,
        func: NativeFn<P>,
    },
    Pure {
        name: String,
        meta: FuncMeta,
        func: PureFn,
    },
}

// Manual `Clone` (a derive would demand `P: Clone`): entries share their
// function pointers through the `Arc`s and deep-copy the metadata.
impl<P: ProcessManager> Clone for HostRegistration<P> {
    fn clone(&self) -> Self {
        match self {
            HostRegistration::Stateful { name, meta, func } => HostRegistration::Stateful {
                name: name.clone(),
                meta: meta.clone(),
                func: Arc::clone(func),
            },
            HostRegistration::Pure { name, meta, func } => HostRegistration::Pure {
                name: name.clone(),
                meta: meta.clone(),
                func: Arc::clone(func),
            },
        }
    }
}

impl<P: ProcessManager> HostRegistration<P> {
    /// Introspectable metadata for this entry, for documentation tooling
    /// that reads modules without registering them.
    pub fn meta(&self) -> &FuncMeta {
        match self {
            HostRegistration::Stateful { meta, .. } => meta,
            HostRegistration::Pure { meta, .. } => meta,
        }
    }
}

/// One user-defined function body (`FUNC NAME($p: TYPE, ...) { ... }`).
/// Param types resolve to tags at definition time, where the type
/// directory is in scope; the registry never holds raw type strings.
#[derive(Debug, Clone)]
pub(super) struct FuncDefData {
    pub(super) params: Vec<(String, TypeTag)>,
    pub(super) body: Vec<Step>,
}

/// Executable body behind one registry entry: an interpreted script, a
/// pure scalar function, or a stateful function with step context.
pub(super) enum FuncBody<P: ProcessManager> {
    Script(FuncDefData),
    Pure(PureFn),
    Ctx(NativeFn<P>),
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for FuncBody<P> {
    fn clone(&self) -> Self {
        match self {
            FuncBody::Script(def) => FuncBody::Script(def.clone()),
            FuncBody::Pure(func) => FuncBody::Pure(Arc::clone(func)),
            FuncBody::Ctx(func) => FuncBody::Ctx(Arc::clone(func)),
        }
    }
}

/// One entry in the unified function registry: introspectable metadata
/// (mandatory for every entry, backing the pre-evaluation arity gate)
/// plus the executable body.
pub(super) struct FuncEntry<P: ProcessManager> {
    pub(super) meta: FuncMeta,
    pub(super) body: FuncBody<P>,
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for FuncEntry<P> {
    fn clone(&self) -> Self {
        Self {
            meta: self.meta.clone(),
            body: self.body.clone(),
        }
    }
}

/// Names defined in one lexical scope frame: `defined` rejects duplicates
/// in the same scope, `shadowed` restores outer definitions on exit.
struct ScopeFrame<P: ProcessManager> {
    defined: HashSet<String>,
    shadowed: Vec<(String, FuncEntry<P>)>,
}

// Manual `Clone` (a derive would demand `P: Clone`).
impl<P: ProcessManager> Clone for ScopeFrame<P> {
    fn clone(&self) -> Self {
        Self {
            defined: self.defined.clone(),
            shadowed: self.shadowed.clone(),
        }
    }
}

/// The single function registry: DSL `FUNC` definitions, builtins, and
/// host extensions share one lookup table, one metadata path, and one
/// dispatch order. Script entries scope lexically (defined names revert on
/// scope exit, shadowing an outer definition restores it); native entries
/// persist for the run. Shared across `fork()` via clone; the entry maps
/// clone while scope frames stay per state.
/// Module to function-name table of pure entries, shared by reference.
/// Nested so placeholder dispatch looks up `table[module][func]` with
/// zero allocation; rebuilt only when native entries register.
pub type PureTable = HashMap<String, HashMap<String, PureFn>>;

pub struct FunctionRegistry<P: ProcessManager> {
    entries: HashMap<String, FuncEntry<P>>,
    scopes: Vec<ScopeFrame<P>>,
    pure_shared: Arc<PureTable>,
}

impl<P: ProcessManager> FunctionRegistry<P> {
    pub(super) fn with_builtins() -> Self {
        let mut reg = Self {
            entries: HashMap::new(),
            pure_shared: Arc::new(HashMap::new()),
            scopes: vec![ScopeFrame {
                defined: HashSet::new(),
                shadowed: Vec::new(),
            }],
        };
        // Every builtin registers through the same `HostRegistration`
        // entries hosts use: no separate authoring path for engine natives.
        // Builtins land in the `STD` module, exactly like a host module.
        for host in Self::builtin_registrations() {
            match host {
                HostRegistration::Stateful { name, meta, func } => {
                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Ctx(func));
                }
                HostRegistration::Pure { name, meta, func } => {
                    reg.insert_qualified(STD_MODULE_NAME, name, meta, FuncBody::Pure(func));
                }
            }
        }
        reg
    }

    /// All builtins as host-style registrations, built from the same
    /// `#[oxdock_func]`-generated markers hosts use. `with_builtins`
    /// consumes this list, so builtins and hosts share one registration
    /// pathway instead of two authoring models.
    pub(super) fn builtin_registrations() -> Vec<HostRegistration<P>> {
        vec![
            Int::registration(),
            Float::registration(),
            Types::registration(),
            TypeDescribe::registration(),
            Glob::registration(),
            LoadToml::registration(),
            LoadJson::registration(),
            ParseToml::registration(),
            ParseJson::registration(),
            PathType::registration(),
            HasKey::registration(),
            MapSet::registration(),
            MergeMaps::registration(),
            Base64Encode::registration(),
            Base64Decode::registration(),
            Rand::registration(),
            ToJson::registration(),
            TypeOf::registration(),
            Functions::registration(),
            Describe::registration(),
            IsTerminal::registration(),
            Eof::registration(),
            SemaphoreNew::registration(),
            SemaphoreTryAcquire::registration(),
            SemaphoreAvailable::registration(),
        ]
    }

    /// Every name the registry answers to. Backs parse-time shadow
    /// validation through `builtin_function_names`.
    pub(super) fn keys(&self) -> HashSet<String> {
        self.entries.keys().cloned().collect()
    }

    /// Single lookup for every callable: script, pure, or stateful.
    pub(super) fn get(&self, name: &str) -> Option<FuncEntry<P>> {
        self.entries.get(name).cloned()
    }

    fn insert_native(&mut self, name: String, meta: FuncMeta, body: FuncBody<P>) {
        self.entries.insert(name, FuncEntry { meta, body });
        self.rebuild_pure_shared();
    }

    /// Rebuild the shared pure table. Runs only on native insertion:
    /// script definitions insert `Script` bodies directly and never
    /// affect the pure set, so this stays correct between rebuilds.
    fn rebuild_pure_shared(&mut self) {
        let mut table: PureTable = HashMap::new();
        for (name, entry) in &self.entries {
            let FuncBody::Pure(ref func) = entry.body else {
                continue;
            };
            if let Some((module, base)) = split_qualified(name) {
                table
                    .entry(module.to_string())
                    .or_default()
                    .insert(base.to_string(), Arc::clone(func));
            }
        }
        self.pure_shared = Arc::new(table);
    }

    /// Insert under `MODULE::BASE`, stamping provenance on the metadata.
    /// The single choke point for every registry entry: builtins pass
    /// `STD`, hosts pass their module, scripts pass `SCRIPT`.
    fn insert_qualified(
        &mut self,
        module: &str,
        base: String,
        mut meta: FuncMeta,
        body: FuncBody<P>,
    ) {
        meta.name = qualify(module, &base);
        meta.module = module.to_string();
        // Last-write-wins would silently reroute calls, so a repeated
        // qualified name is a programmer error, never a shadow: panic like
        // conflicting type registrations do. `SCRIPT` definitions bypass
        // this path (`define_script` owns their scoped shadowing).
        if self.entries.contains_key(&meta.name) {
            panic!("duplicate function registration `{}`", meta.name);
        }
        self.insert_native(meta.name.clone(), meta, body);
    }

    pub(super) fn register_host(
        &mut self,
        module: &str,
        name: String,
        mut meta: FuncMeta,
        func: NativeFn<P>,
    ) {
        meta.kind = FuncKind::HostCtx;
        self.insert_qualified(module, name, meta, FuncBody::Ctx(func));
    }

    pub(super) fn register_pure_host(
        &mut self,
        module: &str,
        name: String,
        mut meta: FuncMeta,
        func: PureFn,
    ) {
        meta.kind = FuncKind::HostPure;
        self.insert_qualified(module, name, meta, FuncBody::Pure(func));
    }

    /// Define a DSL `FUNC`: names colliding with any known base name cannot
    /// shadow, same-scope duplicates cannot redefine, and nested shadowing
    /// of an outer script definition restores on scope exit. Stored as
    /// `SCRIPT::NAME`, exactly like every other qualified entry.
    pub(super) fn define_script(
        &mut self,
        name: &str,
        params: &[(String, TypeTag)],
        body: &[Step],
    ) -> Result<()> {
        let qualified = qualify(SCRIPT_MODULE_NAME, name);
        let shadowable = matches!(
            self.entries.get(&qualified).map(|entry| &entry.body),
            Some(FuncBody::Script(_))
        );
        // Reserved spans every module: compare base names so the message
        // keeps naming the bare script identifier.
        let reserved = self
            .entries
            .keys()
            .any(|key| split_qualified(key).is_some_and(|(_, base)| base == name));
        if reserved && !shadowable {
            anyhow::bail!("cannot shadow reserved function `{name}`");
        }
        if self
            .scopes
            .last()
            .is_some_and(|frame| frame.defined.contains(&qualified))
        {
            anyhow::bail!("duplicate function `{name}` in same scope");
        }
        let old = self.entries.insert(
            qualified.clone(),
            FuncEntry {
                meta: FuncMeta {
                    name: qualified.clone(),
                    module: SCRIPT_MODULE_NAME.to_string(),
                    kind: FuncKind::Script,
                    params: Some(
                        params
                            .iter()
                            .map(|(name, param_type)| FuncParam {
                                name: name.clone(),
                                param_type: Some(*param_type),
                                allowed: None,
                                // Script `FUNC` params carry no prose:
                                // declarations have no doc syntax.
                                docs: "",
                                options: None,
                                optional: false,
                            })
                            .collect(),
                    ),
                    returns: None,
                    rpn: false,
                    summary: "DSL-defined function.",
                    docs: "Defined via FUNC in script.",
                },
                body: FuncBody::Script(FuncDefData {
                    params: params.to_vec(),
                    body: body.to_vec(),
                }),
            },
        );
        if let Some(frame) = self.scopes.last_mut() {
            frame.defined.insert(qualified.clone());
            if let Some(old) = old {
                frame.shadowed.push((qualified, old));
            }
        }
        Ok(())
    }

    /// Open a lexical scope frame for script definitions. Native entries
    /// persist; only script names track here.
    pub(super) fn push_scope(&mut self) {
        self.scopes.push(ScopeFrame {
            defined: HashSet::new(),
            shadowed: Vec::new(),
        });
    }

    /// Close a lexical scope frame: names defined inside revert, and any
    /// outer definition they shadowed is restored.
    pub(super) fn pop_scope(&mut self) {
        let Some(frame) = self.scopes.pop() else {
            return;
        };
        for name in frame.defined {
            self.entries.remove(&name);
        }
        for (name, old) in frame.shadowed {
            self.entries.insert(name, old);
        }
    }

    /// True when `name` is an interpreted script definition (needing call
    /// scoping and depth budgeting through `call_func_value` rather than
    /// inline evaluation).
    pub(super) fn contains_script(&self, name: &str) -> bool {
        matches!(
            self.entries.get(name).map(|entry| &entry.body),
            Some(FuncBody::Script(_))
        )
    }

    /// Clone the pure fn for `name` (ending the registry borrow) so callers
    /// can invoke it without holding `&self` across a `&mut StepCtx` use.
    fn clone_pure_fn(&self, name: &str) -> Option<PureFn> {
        match self.entries.get(name)?.body {
            FuncBody::Pure(ref func) => Some(Arc::clone(func)),
            _ => None,
        }
    }

    /// Shared snapshot of every pure entry, nested by module and base
    /// name. Cloning the `Arc` is refcount-only: placeholder dispatch
    /// borrows this per expansion with no map copies.
    pub(super) fn pure_shared(&self) -> Arc<PureTable> {
        Arc::clone(&self.pure_shared)
    }

    /// Every entry's metadata, scripts included, sorted by name. Backs
    /// run-start type tag validation.
    pub(super) fn all_metas(&self) -> Vec<FuncMeta> {
        self.entries_metas()
    }

    /// Clone the ctx fn for `name` (ending the registry borrow) so callers
    /// can invoke it with `&mut StepCtx` without double-borrowing state.
    fn clone_ctx_fn(&self, name: &str) -> Option<NativeFn<P>> {
        match self.entries.get(name)?.body {
            FuncBody::Ctx(ref func) => Some(Arc::clone(func)),
            _ => None,
        }
    }

    fn meta(&self, name: &str) -> Option<FuncMeta> {
        self.entries.get(name).map(|entry| entry.meta.clone())
    }

    fn native_metas(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = Vec::new();
        for entry in self.entries.values() {
            if !matches!(entry.body, FuncBody::Script(_)) {
                out.push(entry.meta.clone());
            }
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Every entry's metadata, scripts included, sorted by name. Backs
    /// runtime `FUNCTIONS()` listings.
    fn entries_metas(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = self
            .entries
            .values()
            .map(|entry| entry.meta.clone())
            .collect();
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }
}

impl<P: ProcessManager> Clone for FunctionRegistry<P> {
    fn clone(&self) -> Self {
        Self {
            entries: self.entries.clone(),
            scopes: self.scopes.clone(),
            pure_shared: Arc::clone(&self.pure_shared),
        }
    }
}

/// Names of all compiled-in builtins plus `INSPECT` (a dedicated AST/RPN
/// node, not a registry entry). Read straight off a stock registry, so the
/// `#[oxdock_func]` annotations stay the single source of truth: adding a
/// builtin extends this set with no parallel list to update. Seeds
/// parse-time shadow validation, so the parser crate keeps zero
/// compile-time knowledge of builtin names.
pub fn builtin_function_names() -> HashSet<String> {
    let mut names = FunctionRegistry::<DefaultProcessManager>::with_builtins().keys();
    names.insert(KEYWORD_INSPECT.to_string());
    names
}

/// Metadata of every builtin function, sorted by name, for static
/// rendering (docs-gen). Same single source as `builtin_function_names`:
/// the `#[oxdock_func]` annotations, never a parallel list.
pub fn builtin_function_metas() -> Vec<FuncMeta> {
    FunctionRegistry::<DefaultProcessManager>::with_builtins().native_metas()
}

/// Stock `STD` module table derived from the `#[oxdock_func]` builtins:
/// the single source of truth for builtin membership and RPN eligibility.
/// Seeds parse-time module resolution, so the parser crate keeps zero
/// compile-time knowledge of builtin names.
pub fn std_module_table() -> oxdock_parser::ModuleTable {
    // Registry names are qualified (`STD::GLOB`); the table holds bases.
    let functions: HashSet<String> = builtin_function_metas()
        .into_iter()
        .map(|meta| base_name(&meta.name).to_string())
        .collect();
    oxdock_parser::ModuleTable {
        modules: HashMap::from([(
            STD_MODULE_NAME.to_string(),
            Some(oxdock_parser::ModuleFuncs { functions }),
        )]),
    }
}

// Builtins below use the `#[oxdock_func]` host export macro, the exact same authoring
// model as host-registered functions: metadata, arity checks, and argument
// unpacking derive from the signature plus doc comments, so adding a native
// means writing one small typed function plus one line each in
// `builtin_registrations` (consumed by `with_builtins`) and the
// `FUNCTIONS`/`DESCRIBE`/`TYPES` surface, which all read the same symbols.

/// Convert a value to INT.
///
/// Trims ASCII whitespace and parses i64. Passes Int through; Float only
/// when integral and finite.
///
#[oxdock_func(pure, returns = TypeTag::Int)]
fn int(
    /// Value to convert to `INT`.
    val: Value,
) -> Result<Value> {
    super::args::int_from_value(val)
}

/// Convert a value to FLOAT.
///
/// Parses f64 (accepts int strings), bails on non-finite or non-numeric.
///
#[oxdock_func(pure, returns = TypeTag::Float)]
fn float(
    /// Value to convert to `FLOAT`.
    val: Value,
) -> Result<Value> {
    super::args::float_from_value(val)
}

/// List workspace paths matching a glob pattern.
///
/// Sorted, root-relative LIST; empty on no match or `..` escape.
///
#[oxdock_func(rpn, returns = TypeTag::ListOf(&TypeTag::String))]
fn glob<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Glob pattern matched against workspace paths.
    pattern: String,
) -> Result<Value> {
    super::args::glob_from_value(&[Value::string(pattern)], cx)
}

/// Load and parse a TOML file.
///
/// Reads a workspace file and parses TOML into a DSL value.
///
#[oxdock_func(rpn, returns = TypeTag::MapOf(&TypeTag::Any))]
fn load_toml<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace file path to load and parse as TOML.
    path: String,
) -> Result<Value> {
    super::args::load_toml_from_value(&[Value::string(path)], cx)
}

/// Load and parse a JSON file.
///
/// Reads a workspace file and parses JSON into a DSL value. Returns
/// `ANY` by design: a top-level array or scalar parses to `LIST` or a
/// scalar word. `LET` coercion still checks the actual value at
/// assignment.
///
#[oxdock_func(rpn, returns = TypeTag::Any)]
fn load_json<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace file path to load and parse as JSON.
    path: String,
) -> Result<Value> {
    super::args::load_json_from_value(&[Value::string(path)], cx)
}

/// Parse TOML text already held in memory.
///
/// Uses the same conversion as file loading, so fetch bodies, file
/// contents, and captured text share one JSON/TOML shape.
///
#[oxdock_func(pure, returns = TypeTag::MapOf(&TypeTag::Any))]
fn parse_toml(
    /// TOML text already held in memory.
    text: String,
) -> Result<Value> {
    super::args::parse_toml_from_value(Value::string(text))
}

/// Parse JSON text already held in memory.
///
/// Uses the same conversion as file loading, so fetch bodies, file
/// contents, and captured text share one JSON value shape. Returns
/// `ANY` by design, matching `LOAD_JSON`: a top-level array or scalar
/// parses to `LIST` or a scalar word. `LET` coercion still checks the
/// actual value at assignment.
///
/// ```oxdock
/// # Parse in-memory JSON text with the same conversion as file loading.
/// IMPORT [STD]
/// LET $body: STRING = "{\"a\": 1}"
/// LET $doc: ANY = PARSE_JSON($body)
/// ASSERT_EQ $doc.a 1
///
/// # Top-level arrays parse to LIST, which is why the return is ANY.
/// LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
/// ASSERT_EQ $items.0 1
/// ASSERT_EQ $items.1 2
/// ```
///
#[oxdock_func(pure, returns = TypeTag::Any)]
fn parse_json(
    /// JSON text already held in memory.
    text: String,
) -> Result<Value> {
    super::args::parse_json_from_value(Value::string(text))
}

/// Describe a filesystem entry.
///
/// Reports file, dir, symlink (no-follow), or absent. AST-only by design;
/// there is no RPN arm for filesystem IO.
///
#[oxdock_func(returns = TypeTag::String)]
fn path_type<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Workspace path of the entry to describe.
    path: String,
) -> Result<Value> {
    super::args::path_type_from_value(&[Value::string(path)], cx)
}

/// Report whether a map holds a key.
///
/// Pure MAP probe so scripts can branch on optional fields without
/// tripping the strict missing-key error.
///
#[oxdock_func(pure, returns = TypeTag::Bool)]
fn has_key(
    /// Map to probe.
    map: BTreeMap<String, Value>,
    /// Key to look up.
    key: String,
) -> Result<Value> {
    super::args::has_key_from_value(Value::map(map), &key)
}

/// Insert one key into a map.
///
/// Fails on duplicates so two entries sharing a key fail the run
/// instead of silently shadowing each other.
///
#[oxdock_func(pure, returns = TypeTag::MapOf(&TypeTag::Any))]
fn map_set(
    /// Map to insert into.
    map: BTreeMap<String, Value>,
    /// Key to insert; duplicates fail.
    key: String,
    /// Value to store.
    value: Value,
) -> Result<Value> {
    super::args::map_set_from_value(Value::map(map), key, value)
}

/// `RAND` options, shared by the registration metadata and the
/// arity check. One params vector feeds both, so the two can never
/// disagree: add a parameter once, here.
static RAND_OPTIONS: &[ParamOption] = &[ParamOption {
    name: "seed",
    value: TypeTag::Int,
    required: false,
    default: None,
}];

/// Draw a random FLOAT uniformly from [0, 1), optionally seeded.
///
/// Impure by design: unseeded calls return different values, so this
/// runs on the AST script path only, never as a `{{ }}` placeholder
/// call. A seed draws the same value on every run, for deterministic
/// fixtures. Scale and shift the draw for wider ranges. Hand-built
/// (not `#[oxdock_func]`): the macro marks every param required, and
/// only hand-built entries can leave a trailing options MAP omittable,
/// so bare `RAND()` fills `{}`.
///
/// ```oxdock
/// # Scale a unit draw into a backoff delay between 1 and 11 seconds.
/// IMPORT [STD]
/// LET $draw: FLOAT = RAND()
/// LET $delay: FLOAT = 1.0 + $draw * 10.0
/// IF $delay < 1.0 {
///     EXIT 1
/// }
/// IF $delay >= 11.0 {
///     EXIT 1
/// }
/// ECHO "retrying in {{ $delay }}s"
///
/// # A seed draws the same value on every run.
/// LET $one: FLOAT = RAND({seed: 7})
/// LET $two: FLOAT = RAND({seed: 7})
/// ASSERT_EQ $one $two
/// ```
///
/// Registration marker for `RAND`, hand-implementing [`OxDockFn`]:
/// the `#[oxdock_func]` macro marks every param required, and only a
/// hand-built entry can leave the trailing options MAP omittable, so
/// bare `RAND()` fills `{}`.
pub struct Rand;
impl<P: ProcessManager> OxDockFn<P> for Rand {
    fn registration() -> HostRegistration<P> {
        rand_registration()
    }
}

fn rand_registration<P: ProcessManager>() -> HostRegistration<P> {
    // One params vector feeds both the metadata and the arity check,
    // so the two can never disagree: add a parameter once, here.
    let params = vec![FuncParam {
        name: "options".to_string(),
        param_type: Some(TypeTag::Map),
        allowed: None,
        docs: "Draw settings: `seed`. Omittable: a missing options MAP fills `{}`.",
        options: Some(RAND_OPTIONS),
        optional: true,
    }];
    let arity = params.len();
    let required = required_arity(&params);
    let fill_params = params.clone();
    let func: NativeFn<P> = Arc::new(move |cx, values| {
        let _ = cx;
        if values.len() < required || values.len() > arity {
            anyhow::bail!(
                "RAND() expects {required} to {arity} argument(s), got {}",
                values.len()
            );
        }
        let mut values = fill_optional_args(&fill_params, values).into_iter();
        let options_value = values.next().expect("arity checked above");
        let options_map = match options_value.as_map() {
            Some(map) => map.clone(),
            None => anyhow::bail!(
                "RAND() argument `$options` must be a MAP, got {}",
                options_value.type_name()
            ),
        };
        check_options(&options_map, RAND_OPTIONS, "RAND")?;
        let seed = match options_map.get("seed") {
            Some(value) => Some(value.as_i64().ok_or_else(|| {
                anyhow::anyhow!(
                    "RAND option 'seed' must be an INT, got {}",
                    value.type_name()
                )
            })?),
            None => None,
        };
        super::args::rand_float_from_value(seed)
    });
    HostRegistration::Stateful {
        name: "RAND".to_string(),
        meta: FuncMeta {
            name: "RAND".to_string(),
            // Assigned at registration, like the macro's markers.
            module: String::new(),
            kind: FuncKind::HostCtx,
            params: Some(params),
            returns: Some(TypeTag::Float),
            rpn: false,
            summary: "Draw a random FLOAT uniformly from [0, 1), optionally seeded.",
            docs: indoc::indoc! {r#"
                Draw a random FLOAT uniformly from [0, 1), optionally seeded. Impure by design: unseeded calls return different values, so this runs on the AST script path only, never as a `{{ }}` placeholder call. A seed draws the same value on every run, for deterministic fixtures. Scale and shift the draw for wider ranges. Hand-built (not `#[oxdock_func]`): the macro marks every param required, and only hand-built entries can leave a trailing options MAP omittable, so bare `RAND()` fills `{}`.

                ```oxdock
                # Scale a unit draw into a backoff delay between 1 and 11 seconds.
                IMPORT [STD]
                LET $draw: FLOAT = RAND()
                LET $delay: FLOAT = 1.0 + $draw * 10.0
                IF $delay < 1.0 {
                    EXIT 1
                }
                IF $delay >= 11.0 {
                    EXIT 1
                }
                ECHO "retrying in {{ $delay }}s"

                # A seed draws the same value on every run.
                LET $one: FLOAT = RAND({seed: 7})
                LET $two: FLOAT = RAND({seed: 7})
                ASSERT_EQ $one $two
                ```
            "#},
        },
        func,
    }
}

/// Encode a STRING as standard base64.
///
/// Padded RFC 4648 alphabet, so encoded output pastes into any
/// standard decoder. Pairs with `BASE64_DECODE` for the round trip.
///
/// ```oxdock
/// # Encode text to standard base64.
/// IMPORT [STD]
/// LET $encoded: STRING = BASE64_ENCODE("hello")
/// ASSERT_EQ $encoded "aGVsbG8="
/// ```
///
#[oxdock_func(pure, returns = TypeTag::String)]
fn base64_encode(
    /// Text to encode.
    text: String,
) -> Result<Value> {
    super::args::base64_encode_from_value(Value::string(text))
}

/// Decode standard base64 to a STRING.
///
/// Fails naming the input on invalid alphabet characters or
/// non-UTF-8 payloads instead of rendering a silent empty. Pairs
/// with `BASE64_ENCODE` for the round trip.
///
/// ```oxdock
/// # Decode standard base64 back to text.
/// IMPORT [STD]
/// LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
/// ASSERT_EQ $decoded "hello"
/// ```
///
#[oxdock_func(pure, returns = TypeTag::String)]
fn base64_decode(
    /// Base64 text to decode.
    text: String,
) -> Result<Value> {
    super::args::base64_decode_from_value(Value::string(text))
}

/// Encode a script value as JSON with one trailing newline.
///
/// Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT,
/// BOOL, LIST, MAP) survive, anything else fails here instead of
/// rendering as a silent empty.
///
#[oxdock_func(pure, returns = TypeTag::String)]
fn to_json(
    /// Value to encode as JSON.
    value: Value,
) -> Result<Value> {
    super::args::to_json_from_value(value)
}

/// Name the word a value holds, for data-driven branching.
///
/// Returns the registered type word (`STRING`, `INT`, `FLOAT`, `BOOL`,
/// `LIST`, `MAP`, plus handle words like `PIPE`): the same name the
/// value prints in arity and coercion errors, so scripts can branch
/// on config shapes (a path string or a path list) without failing.
///
#[oxdock_func(pure, returns = TypeTag::String)]
fn type_of(
    /// Value whose word to name.
    value: Value,
) -> Result<Value> {
    super::args::type_of_from_value(value)
}

/// Merge a LIST of MAPs in order under one duplicate policy.
///
/// `fail_on_duplicate` fails naming the repeated key, so two files
/// claiming one placeholder fail the run instead of shadowing each
/// other. `overwrite` lets later files win, for environment overlays.
/// Non MAP elements fail naming their position.
///
#[oxdock_func(pure, returns = TypeTag::MapOf(&TypeTag::Any))]
fn merge_maps(
    /// LIST of MAPs to merge in order.
    maps: Vec<BTreeMap<String, Value>>,
    /// Duplicate policy.
    #[values("fail_on_duplicate", "overwrite")]
    policy: String,
) -> Result<Value> {
    super::args::merge_maps_from_value(
        Value::list(maps.into_iter().map(Value::map).collect()),
        policy,
    )
}

/// List all visible function names.
///
/// Sorted LIST of qualified `MODULE::NAME` entries: DSL-defined plus native
/// plus host-registered names.
#[oxdock_func(returns = TypeTag::ListOf(&TypeTag::String))]
fn functions<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
    let mut names: Vec<String> = cx
        .state
        .list_functions()
        .into_iter()
        .map(|meta| meta.name)
        .collect();
    names.sort();
    names.dedup();
    Ok(Value::list(names.into_iter().map(Value::string).collect()))
}

/// Describe one function by qualified name.
///
/// Returns a MAP with name, module, kind, params, returns, rpn, and
/// summary. `params` is always a LIST (empty for parameterless
/// functions) of entries carrying name, param_type, allowed, docs,
/// options, and optional flags, so the shape holds for every entry. Bare names
/// fail closed: `DESCRIBE` requires the qualified form (except
/// `INSPECT`, which is syntax rather than a registry entry). Errors
/// on unknown function.
///
/// Field table for the `DESCRIBE` result bundle: one source for the
/// shape the host mints, so introspection, enforcement, and
/// documentation cannot drift apart. `const` (not `static`) so the
/// inline `Record` below const-promotes to `'static` like the
/// `TYPE_DESCRIBE` table beside it.
const DESCRIBE_PARAMS_MAP: TypeTag = TypeTag::MapOf(&TypeTag::Any);
const DESCRIBE_PARAMS: TypeTag = TypeTag::ListOf(&DESCRIBE_PARAMS_MAP);

#[oxdock_func(
    returns = TypeTag::Record(&[Field {
        name: "name",
        ty: TypeTag::String,
        docs: "Qualified function name.",
        optional: false,
    }, Field {
        name: "module",
        ty: TypeTag::String,
        docs: "Owning module.",
        optional: false,
    }, Field {
        name: "kind",
        ty: TypeTag::String,
        docs: "Origin label (`host` or `script`).",
        optional: false,
    }, Field {
        name: "params",
        ty: DESCRIBE_PARAMS,
        docs: "Parameter entries (empty for parameterless functions).",
        optional: false,
    }, Field {
        name: "returns",
        ty: TypeTag::String,
        docs: "Structural return shape (empty when untagged).",
        optional: false,
    }, Field {
        name: "rpn",
        ty: TypeTag::Bool,
        docs: "True when callable in RPN position.",
        optional: false,
    }, Field {
        name: "summary",
        ty: TypeTag::String,
        docs: "One-line description.",
        optional: false,
    }]),
    summary = "Describe one function by qualified name."
)]
fn describe<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Qualified function name (`MODULE::NAME`).
    name: String,
) -> Result<Value> {
    if split_qualified(&name).is_none() && name != KEYWORD_INSPECT {
        anyhow::bail!(
            "unknown function `{name}`: DESCRIBE requires a qualified name (e.g. `STD::{name}`)"
        );
    }
    cx.state
        .describe_function(&name)
        .ok_or_else(|| anyhow::anyhow!("unknown function {name}"))
}

/// List all known type names.
///
/// Sorted LIST of startup plus host-registered type descriptors. Reads the
/// run's name directory, so it runs on the AST path like the other
/// introspection functions.
#[oxdock_func(returns = TypeTag::ListOf(&TypeTag::String))]
fn types<P: ProcessManager>(cx: &mut StepCtx<P>) -> Result<Value> {
    Ok(Value::list(
        cx.state
            .type_names()
            .into_iter()
            .map(Value::string)
            .collect(),
    ))
}

/// Describe one type by name.
///
/// Returns a MAP with name, summary, and docs. Errors on unknown type.
/// Reads the run's name directory, so it runs on the AST path.
///
#[oxdock_func(returns = TypeTag::Record(&[Field {
    name: "name",
    ty: TypeTag::String,
    docs: "Queried type name.",
    optional: false,
}, Field {
    name: "summary",
    ty: TypeTag::String,
    docs: "One-line description.",
    optional: false,
}, Field {
    name: "docs",
    ty: TypeTag::String,
    docs: "Full documentation text.",
    optional: false,
}]))]
fn type_describe<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Type name to describe.
    name: String,
) -> Result<Value> {
    if let Some(descriptor) = cx.state.describe_type(&name) {
        let mut map = BTreeMap::new();
        map.insert(
            "name".to_string(),
            Value::string(descriptor.name.to_string()),
        );
        map.insert(
            "summary".to_string(),
            Value::string(descriptor.summary.to_string()),
        );
        map.insert(
            "docs".to_string(),
            Value::string(descriptor.docs.to_string()),
        );
        return Ok(Value::map(map));
    }
    // Script aliases have no descriptor but introspect the same way:
    // the entry names the alias and its canonical target spelling.
    if let Some(target) = cx.state.alias_target(&name) {
        let mut map = BTreeMap::new();
        map.insert("name".to_string(), Value::string(name.clone()));
        map.insert(
            "summary".to_string(),
            Value::string(format!("Script type alias for {target}.")),
        );
        map.insert(
            "docs".to_string(),
            Value::string(format!(
                "Declared with TYPE {name} = {target}. The alias expands structurally at every declaration."
            )),
        );
        return Ok(Value::map(map));
    }
    Err(anyhow::anyhow!("unknown type {name}"))
}

/// Report whether a standard stream is a terminal.
///
/// `IS_TERMINAL("stdin")`, `IS_TERMINAL("stdout")`, or `IS_TERMINAL("stderr")`
/// answers for the step's stream as currently bound, so scripts can adapt
/// prompts, colors, and progress output. Anything diverted from the
/// terminal reports false without touching host handles: `WITH_IO` pipe
/// bindings (script backends and OS pairs), `LET`-capture sinks, staged
/// runner sinks, and any materialized stdin stream (only a directly
/// inherited fd falls back to the process check). A transparent root tee
/// still answers the session question via the process check. The name
/// matches exactly (no case folding): anything else bails. AST-only:
/// reads the step context like the other introspection functions.
///
#[oxdock_func(returns = TypeTag::Bool)]
fn is_terminal<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Stream name: `stdin`, `stdout`, or `stderr` (exact match).
    #[values("stdin", "stdout", "stderr")]
    stream_name: String,
) -> Result<Value> {
    use std::io::IsTerminal;
    let terminal = match stream_name.as_str() {
        "stdin" => {
            // A script-pipe backend is definitive; Null is /dev/null.
            // Only a directly inherited fd answers the process check: a
            // materialized Stream is always a binding (staged input,
            // WITH_IO pipe, or OS half), never the raw fd.
            if cx.stdin_pipe.is_some() {
                false
            } else {
                match &cx.stdin {
                    CommandStdin::Null => false,
                    #[cfg(not(miri))]
                    CommandStdin::OsPipe(_) => false,
                    CommandStdin::Stream(_) => false,
                    CommandStdin::Inherit => std::io::stdin().is_terminal(),
                }
            }
        }
        "stdout" => {
            if cx.out_pipe.is_some() {
                // WITH_IO script-pipe binding: never a terminal.
                false
            } else if cx.state.io.stdout().is_some() {
                // Staged runner sink: the root tee diverts bytes to the
                // sink only, never to real stdout.
                false
            } else {
                match &cx.out {
                    // Unbound: inherited straight through.
                    None => std::io::stdout().is_terminal(),
                    // OS kernel pipe: never a terminal.
                    #[cfg(not(miri))]
                    Some(StreamHandle::Os(_)) => false,
                    // Root tee (transparent: forwards to real stdout when
                    // unstaged, so terminal-ness survives) versus a genuine
                    // diversion. WITH_IO bindings never reach here (script
                    // pipes trip out_pipe, OS pipes trip Os, staged sinks
                    // trip above). LET-capture cannot reach here either:
                    // assign_capture installs no sink for a bare NAME(...)
                    // call, so a direct query always observes the ambient
                    // routing. The process check answers the session
                    // question.
                    Some(StreamHandle::Stream(_)) => std::io::stdout().is_terminal(),
                }
            }
        }
        "stderr" => {
            if cx.state.io.stderr().is_some() {
                // Staged runner sink: diverted, never a terminal.
                false
            } else {
                match &cx.err {
                    // Unbound: inherited straight through.
                    None => std::io::stderr().is_terminal(),
                    // OS kernel pipe: never a terminal.
                    #[cfg(not(miri))]
                    Some(StreamHandle::Os(_)) => false,
                    // Root never tees stderr and LET never captures it,
                    // so a bound handle here is always a WITH_IO binding.
                    Some(StreamHandle::Stream(_)) => false,
                }
            }
        }
        _ => anyhow::bail!(
            // Unreachable through the macro path: the generated
            // extractor rejects non-members before the body runs, and
            // the static pre-pass rejects bad literals earlier still.
            // Kept as a bail (never a panic) for hand-built callers.
            "IS_TERMINAL expects \"stdin\", \"stdout\", or \"stderr\", got {stream_name:?}"
        ),
    };
    Ok(Value::bool(terminal))
}

/// Create a counting semaphore admitting at most `max` concurrent holders.
///
/// Non-positive maxima bail. The word names a shared backend: every clone
/// observes the same count, and admission runs through
/// `SEMAPHORE_TRY_ACQUIRE`, never through the `SEMAPHORE_AVAILABLE`
/// readout.
///
/// ```oxdock
/// # Mint a semaphore admitting at most two holders.
/// IMPORT [STD]
/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
///
/// # A fresh semaphore reports its full cap as available.
/// LET $free: INT = SEMAPHORE_AVAILABLE($sem)
/// ASSERT_EQ $free 2
/// ```
///
#[oxdock_func(returns = TypeTag::Semaphore)]
fn semaphore_new<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Maximum concurrent holders; must be positive.
    max: i64,
) -> Result<Value> {
    let _ = cx;
    if max <= 0 {
        return Err(anyhow::anyhow!(
            "SEMAPHORE_NEW() requires a positive max, got {max}"
        ));
    }
    Ok(Value::semaphore(max as usize))
}

/// Attempt one non-blocking acquire, always answering a MAP.
///
/// `held` is `true` with the permit under the `permit` key, or `false`
/// with no `permit` key: branch on `$m.held` directly. The DSL has no
/// null, so the absent key is the miss shape. Do not read `$m.permit`
/// unless `held`: missing-key access bails strictly.
/// Never waits, so no wait can wedge.
///
/// ```oxdock
/// # First acquire holds with a permit to bind.
/// IMPORT [STD]
/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
/// LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
/// ASSERT_EQ $first.held true
/// LET $permit: PERMIT = $first.permit
///
/// # A capped semaphore answers held false with no permit key.
/// LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
/// ASSERT_EQ $second.held false
/// LET $has_permit: BOOL = HAS_KEY($second, "permit")
/// ASSERT_EQ $has_permit false
/// ```
///
#[oxdock_func(returns = TypeTag::Record(&[Field {
    name: "held",
    ty: TypeTag::Bool,
    docs: "`true` with the permit under `permit`, `false` with no `permit` key.",
    optional: false,
}, Field {
    name: "permit",
    ty: TypeTag::Permit,
    docs: "Permit handle; read only when `held`.",
    optional: true,
}]))]
fn semaphore_try_acquire<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Semaphore handle from `SEMAPHORE_NEW`.
    sem: Arc<SemaphoreState>,
) -> Result<Value> {
    let _ = cx;
    let mut map = BTreeMap::new();
    if sem.try_acquire() {
        map.insert("held".to_string(), Value::bool(true));
        map.insert("permit".to_string(), Value::permit(&sem));
    } else {
        map.insert("held".to_string(), Value::bool(false));
    }
    Ok(Value::map(map))
}

/// Read free permits under the lock, with no mutation.
///
/// Observability only (audit lines, healthchecks: `active = max - free`).
/// Exact at read time and stale the instant the caller acts on it, so it
/// must never drive admission: that is `SEMAPHORE_TRY_ACQUIRE`'s job.
///
/// ```oxdock
/// # Hold one permit on a cap of two.
/// IMPORT [STD]
/// LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
/// LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
/// ASSERT_EQ $acq.held true
///
/// # One held permit leaves exactly one free.
/// LET $free: INT = SEMAPHORE_AVAILABLE($sem)
/// ASSERT_EQ $free 1
/// ```
///
#[oxdock_func(pure, returns = TypeTag::Int)]
fn semaphore_available(
    /// Semaphore handle from `SEMAPHORE_NEW`.
    sem: Arc<SemaphoreState>,
) -> Result<Value> {
    Ok(Value::int(sem.available() as i64))
}

/// True when a pipe sits at end of stream: closed with nothing buffered,
/// so the next `READ_LINE` would bind `""` via EOF rather than a line.
/// Live writers, pinned keepers, and buffered bytes all answer false.
/// Never blocks: a reader already blocked stays blocked, so branch on
/// `EOF` before reading, not after. OS pairs and unbound handles answer
/// best-effort (kernel bytes are invisible there; see `INSPECT`).
/// Non-pipe arguments bail at the boundary: the parameter declares
/// `PIPE`, so the extractor and the static pass reject them before
/// the body runs.
///
/// ```oxdock
/// # Capture two lines, then drain to end of stream with no sentinel line.
/// IMPORT [STD]
/// LET $cap: PIPE
/// WITH_IO [stdout=$cap] {
///     ECHO "one"
///     ECHO "two"
/// }
///
/// # The loop exits on close, and the count proves both lines drained.
/// LET $n: INT = 0
/// WHILE !EOF($cap) {
///     WITH_IO [stdin=$cap] READ_LINE $line
///     $n = $n + 1
/// }
/// ASSERT_EQ $n 2
/// ```
///
#[oxdock_func(returns = TypeTag::Bool)]
fn eof<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    /// Pipe handle to query for end of stream.
    pipe: PipeHandle,
) -> Result<Value> {
    let info = cx.state.io.inspect_pipe(&pipe);
    Ok(Value::bool(info.closed && info.buffered == 0))
}

fn meta_to_value(meta: &FuncMeta) -> Value {
    let mut map = BTreeMap::new();
    map.insert("name".to_string(), Value::string(meta.name.clone()));
    map.insert("module".to_string(), Value::string(meta.module.clone()));
    map.insert(
        "kind".to_string(),
        Value::string(meta.kind.label().to_string()),
    );
    let params = match &meta.params {
        Some(params) => Value::list(
            params
                .iter()
                .map(|p| {
                    let mut entry = BTreeMap::new();
                    entry.insert("name".to_string(), Value::string(p.name.clone()));
                    entry.insert(
                        "param_type".to_string(),
                        Value::string(
                            p.param_type
                                .as_ref()
                                .map(render_structural)
                                .unwrap_or_default(),
                        ),
                    );
                    entry.insert(
                        "allowed".to_string(),
                        Value::string(
                            p.allowed
                                .map(|values| values.join(", "))
                                .unwrap_or_default(),
                        ),
                    );
                    entry.insert("docs".to_string(), Value::string(String::new()));
                    entry.insert("optional".to_string(), Value::bool(p.optional));
                    entry.insert(
                        "options".to_string(),
                        match p.options {
                            Some(keys) => Value::list(
                                keys.iter()
                                    .map(|key| {
                                        let mut option = BTreeMap::new();
                                        option.insert(
                                            "name".to_string(),
                                            Value::string(key.name.to_string()),
                                        );
                                        option.insert(
                                            "value_type".to_string(),
                                            Value::string(render_structural(&key.value)),
                                        );
                                        option.insert(
                                            "required".to_string(),
                                            Value::bool(key.required),
                                        );
                                        option.insert(
                                            "default".to_string(),
                                            Value::string(
                                                key.default.unwrap_or_default().to_string(),
                                            ),
                                        );
                                        Value::map(option)
                                    })
                                    .collect(),
                            ),
                            None => Value::string(String::new()),
                        },
                    );
                    Value::map(entry)
                })
                .collect(),
        ),
        // Parameterless functions mint an empty LIST, never an empty
        // STRING: the `DESCRIBE` return tag promises `LIST<MAP<ANY>>`
        // for every entry, and the boundary enforces it.
        None => Value::list(Vec::new()),
    };
    map.insert("params".to_string(), params);
    map.insert(
        "returns".to_string(),
        Value::string(
            meta.returns
                .as_ref()
                .map(render_structural)
                .unwrap_or_default(),
        ),
    );
    map.insert("rpn".to_string(), Value::bool(meta.rpn));
    map.insert(
        "summary".to_string(),
        Value::string(meta.summary.to_string()),
    );
    Value::map(map)
}

/// One named record schema: a shape host functions produce and scripts
/// bind by name (`LET $s: SSH_SESSION_INFO`). Travels with its module
/// so schemas register exactly when their producer does.
#[derive(Debug, Clone, Copy)]
pub struct RecordSchema {
    pub name: &'static str,
    pub fields: &'static [Field],
}

/// One host library: functions and types registered under a single module
/// name. `Engine::register_module` stages these; runs expose them as
/// `MODULE::NAME` calls with `MODULE` provenance on every entry.
#[derive(Clone)]
pub struct HostModule<P: ProcessManager> {
    pub name: String,
    pub funcs: Vec<HostRegistration<P>>,
    pub types: Vec<&'static TypeDescriptor>,
    pub record_schemas: Vec<RecordSchema>,
}

impl<P: ProcessManager> ExecState<P> {
    /// Register one [`HostModule`]: every function becomes callable as
    /// `MODULE::NAME`, every type joins the run's name directory.
    pub fn register_module(&mut self, module: HostModule<P>) {
        for registration in module.funcs {
            match registration {
                HostRegistration::Stateful { name, meta, func } => {
                    self.functions.register_host(&module.name, name, meta, func);
                }
                HostRegistration::Pure { name, meta, func } => {
                    self.functions
                        .register_pure_host(&module.name, name, meta, func);
                }
            }
        }
        for descriptor in module.types {
            self.register_type(descriptor);
        }
        for schema in module.record_schemas {
            self.register_record_schema(schema.name, schema.fields);
        }
    }

    /// All visible functions: natives plus hosts plus current DSL definitions.
    pub fn list_functions(&self) -> Vec<FuncMeta> {
        let mut out: Vec<FuncMeta> = self.functions.entries_metas().into_iter().collect();
        // TODO: Make a "virtual function" and don't hardcode
        if !out.iter().any(|m| m.name == KEYWORD_INSPECT) {
            out.push(FuncMeta {
                name: KEYWORD_INSPECT.to_string(),
                module: STD_MODULE_NAME.to_string(),
                kind: FuncKind::HostCtx,
                params: None,
                returns: Some(TypeTag::Map),
                rpn: false,
                summary: "Inspect a variable binding.",
                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
            });
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    /// Describe one function by name, or `None` when unknown.
    pub fn describe_function(&self, name: &str) -> Option<Value> {
        if let Some(meta) = self.functions.meta(name) {
            return Some(meta_to_value(&meta));
        }
        // TODO: Make a "virtual function" and don't hardcode
        if name == KEYWORD_INSPECT {
            return Some(meta_to_value(&FuncMeta {
                name: KEYWORD_INSPECT.to_string(),
                module: STD_MODULE_NAME.to_string(),
                kind: FuncKind::HostCtx,
                params: None,
                returns: Some(TypeTag::Map),
                rpn: false,
                summary: "Inspect a variable binding.",
                docs: "INSPECT($var): dedicated AST node taking a variable, not a value.",
            }));
        }
        None
    }

    pub(super) fn clone_native_pure(&self, name: &str) -> Option<PureFn> {
        self.functions.clone_pure_fn(name)
    }

    /// Shared snapshot of every registered pure function for
    /// placeholder and host driven expansion. Public so host crates
    /// resolve calls through the live registry instead of hardcoding
    /// module or function names. Cloning the `Arc` never copies the map.
    pub fn pure_function_table(&self) -> Arc<PureTable> {
        self.functions.pure_shared()
    }

    pub(super) fn clone_native_ctx(&self, name: &str) -> Option<NativeFn<P>> {
        self.functions.clone_ctx_fn(name)
    }

    pub(super) fn native_meta(&self, name: &str) -> Option<FuncMeta> {
        self.functions.meta(name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn describe_entry_carries_optional_flag() {
        // The `optional` key on params entries is the machine-readable
        // half of the `?` rendering: pin both values through the same
        // builder the runtime serves, not through prose.
        let meta = FuncMeta {
            name: "T::F".to_string(),
            module: "T".to_string(),
            kind: FuncKind::HostPure,
            params: Some(vec![
                FuncParam {
                    name: "url".to_string(),
                    param_type: Some(TypeTag::String),
                    allowed: None,
                    docs: "",
                    options: None,
                    optional: false,
                },
                FuncParam {
                    name: "options".to_string(),
                    param_type: Some(TypeTag::Map),
                    allowed: None,
                    docs: "",
                    options: None,
                    optional: true,
                },
            ]),
            returns: Some(TypeTag::String),
            rpn: false,
            summary: "test-only",
            docs: "test-only",
        };
        let value = meta_to_value(&meta);
        let map = value.as_map().expect("describe value is a map");
        let params = map
            .get("params")
            .expect("params key")
            .as_list()
            .expect("params is a list");
        assert_eq!(params.len(), 2);
        let first = params[0].as_map().expect("entry is a map");
        let second = params[1].as_map().expect("entry is a map");
        assert_eq!(
            first.get("optional").and_then(Value::as_bool),
            Some(false),
            "required param must read false"
        );
        assert_eq!(
            second.get("optional").and_then(Value::as_bool),
            Some(true),
            "omittable param must read true"
        );
    }
}