oxdock-core 0.49.0-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
//! Type-system integration for the executor.
//!
//! Name directories (which descriptor answers for `"TAG"`) live per
//! execution state: one `HashMap` seeded with the startup descriptors,
//! extended by the run's host descriptors. Words carry their own vtable,
//! so lifecycle never consults any table; only name resolution (declaration
//! checking, `TYPES()`, `TYPE_DESCRIBE`) reads the state map.

pub use oxdock_parser::{
    Field, HANDLE_TYPE_NAME, LIST_TAG, LIST_TYPE_NAME, MAP_TAG, MAP_TYPE_NAME, OxDockType,
    TypeDescriptor, TypeTag, Value, ValuePayload, check_value, check_value_at, clone_boxed,
    clone_copy, clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared,
    fmt_boxed, fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
    unshare_boxed, unshare_inline, unshare_shared,
};

use std::collections::{HashMap, HashSet};

use oxdock_diagnostics::DiagnosticResult;
use oxdock_parser::{
    MAX_GENERIC_DEPTH, MODULE_SEPARATOR, Spelled, SpelledField, Step, StepKind,
    canonicalize_spelling, intern_rendered, lookup_rendered, parse_spelling, render_structural,
};
use oxdock_process::ProcessManager;

use super::diagnostics as typing_diag;
use super::native::AliasTargets;
use super::state::ExecState;
use super::state::TypeSnapshot;

/// Site label for declaration-position tag validation. Single owner
/// so resolve paths never restate the string.
const DECLARATION_SITE: &str = "declaration";

/// Single owner for bare `LIST`/`MAP`/`HANDLE` rejection. Every bare
/// and qualified-base lookup routes here, so a new bare container
/// spells its error once. Returns `Err` for bare containers, `Ok`
/// otherwise.
fn check_bare_payload(name: &str) -> DiagnosticResult<()> {
    if name == MAP_TYPE_NAME {
        return Err(typing_diag::typing_bare_map());
    }
    if name == LIST_TYPE_NAME {
        return Err(typing_diag::typing_bare_list());
    }
    if name == HANDLE_TYPE_NAME {
        return Err(typing_diag::typing_bare_handle());
    }
    Ok(())
}

/// Check an options map against its declared keys: unknown keys fail
/// listing the known ones, so script typos fail fast instead of
/// silently ignored. Shared by generated extractors and hand-built
/// entries alike: both validate against the same `ParamOption`
/// statics the metadata renders, so the documented keys and the
/// enforced keys cannot drift apart. Present values check against
/// the declared `ParamOption.value` through the single shape path,
/// so a wrong-typed option fails here naming func, key, expected,
/// and actual instead of deeper in the body. Absent keys pass here:
/// defaults, coercion, and cross-key rules stay function logic.
pub fn check_options(
    map: &std::collections::BTreeMap<String, Value>,
    options: &[crate::ParamOption],
    func: &str,
) -> DiagnosticResult<()> {
    for key in map.keys() {
        if !options.iter().any(|known| known.name == key) {
            let known: Vec<&str> = options.iter().map(|known| known.name).collect();
            return Err(typing_diag::check_unknown_option(func, key, &known));
        }
    }
    for (key, value) in map.iter() {
        let option = options
            .iter()
            .find(|known| known.name == *key)
            .expect("unknown keys rejected above");
        crate::check_value_at(&option.value, value, &format!("{func}() option '{key}'"))
            .map_err(|err| typing_diag::check_option_value(&err))?;
    }
    Ok(())
}

/// Pure entry hash for the environment digest: the namespace byte
/// names the collection (`b'a'` aliases, `b's'` schemas, `b't'`
/// custom types), never the action. Set and removal of the same
/// entry hash identically, so removal backs the insertion out
/// exactly and the digest always mirrors current content.
fn hash_env_entry(namespace: u8, name: &str, value: &str) -> u64 {
    use std::hash::{DefaultHasher, Hasher};
    let mut hasher = DefaultHasher::new();
    hasher.write_u8(namespace);
    hasher.write(name.as_bytes());
    hasher.write(value.as_bytes());
    hasher.finish()
}

/// Fresh name directory seeded with the startup descriptors.
pub(super) fn startup_type_map() -> HashMap<String, super::state::HostTypeEntry> {
    startup_descriptors()
        .into_iter()
        .map(|(name, descriptor)| {
            (
                name.to_string(),
                super::state::HostTypeEntry {
                    descriptor,
                    module: String::new(),
                },
            )
        })
        .collect()
}

/// Type exports per file key from live modules: shared helper so
/// both the associated method and static-check single-file paths
/// read the same table without restating the loop.
pub(crate) fn module_type_exports_map<P: ProcessManager>(
    state: &ExecState<P>,
) -> HashMap<String, Vec<String>> {
    let mut out = HashMap::new();
    for (key, record) in &state.modules {
        out.insert(key.clone(), record.exports.types.clone());
    }
    out
}

/// Shared immutable scope for target-explicit type resolution: the
/// resolving unit, its live alias targets, and the per-file
/// type-export table. One param for the whole `*_with_targets`
/// family instead of three restated at every hop, so the recursion
/// stays under the argument-count lint without an `allow`.
struct TargetScope<'a> {
    unit: &'a str,
    alias_targets: &'a AliasTargets,
    exports: &'a HashMap<String, Vec<String>>,
}

impl TypeSnapshot {
    /// Register a host-defined type descriptor (usually `T::descriptor()`
    /// for a `#[oxdock_type]` payload). Makes the name visible to `TYPES()`
    /// and valid for `LET $x: NAME` declarations carrying same-named
    /// payloads. Re-registering a name returns silently when the descriptor
    /// is identical; a different descriptor under a live name panics
    /// instead of aliasing two layouts.
    pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
        if let Some(live) = self.types.get(descriptor.name) {
            if !std::ptr::eq(live.descriptor, descriptor) {
                panic!(
                    "type name `{}` already registered for a different descriptor",
                    descriptor.name
                );
            }
            return;
        }
        self.types.insert(
            descriptor.name.to_string(),
            super::state::HostTypeEntry {
                descriptor,
                module: String::new(),
            },
        );
        self.type_env_digest ^= hash_env_entry(b't', descriptor.name, descriptor.name);
    }

    /// True when `name` names a registered type (startup or host).
    pub fn is_known_type(&self, name: &str) -> bool {
        self.types.contains_key(name)
    }

    /// Register a named record schema for shaped MAP bindings (usually
    /// alongside the module that produces them). Makes the name valid
    /// for `LET $x: NAME` declarations carrying conforming maps. A
    /// different field table under a live name panics instead of
    /// aliasing two shapes.
    pub fn register_record_schema(&mut self, name: &'static str, fields: std::sync::Arc<[Field]>) {
        if let Some(live) = self.record_schemas.get(name) {
            if live.fields.len() != fields.len()
                || live
                    .fields
                    .iter()
                    .zip(fields.iter())
                    .any(|(a, b)| a.name != b.name)
            {
                panic!("record schema `{name}` already registered with different fields");
            }
            return;
        }
        let rendered = render_structural(&TypeTag::Record(fields.clone()));
        self.record_schemas.insert(
            name.to_string(),
            super::state::RecordSchemaEntry {
                fields,
                module: String::new(),
            },
        );
        self.type_env_digest ^= hash_env_entry(b's', name, &rendered);
    }

    /// Every registered schema name, sorted. Backs discovery listings.
    pub fn schema_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.record_schemas.keys().cloned().collect();
        names.sort();
        names
    }

    /// Every script alias name, sorted. Backs discovery listings
    /// and unknown-type errors alongside schemas.
    pub fn alias_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.type_aliases.keys().cloned().collect();
        names.sort();
        names
    }

    /// The canonical target spelling of one script alias, if defined.
    /// Backs `TYPE_DESCRIBE` so aliases introspect like named types.
    pub fn alias_target(&self, name: &str) -> Option<String> {
        self.type_aliases.get(name).cloned()
    }

    /// Resolve a source-level type name to its tag: builtins by closed
    /// match, customs through the type directory, named schemas through
    /// the schema directory, script aliases through the alias directory,
    /// generic spellings (`LIST<MAP>`, `MAP<name: STRING>`) rendered
    /// structurally, and unions (`STRING|PIPE`, including inside
    /// generics) with one interned entry per distinct spelling.
    /// Anything else bails listing every known type, schema, and alias.
    /// Single choke for every `LET`/`FUNC` declaration. Signature is
    /// stable: alias cycles and shared depth accounting thread
    /// internally, so all call sites gain generics with zero edits.
    /// Explicit-target resolution shared by runtime and static check:
    /// runtime passes `unit_alias_targets`, static passes
    /// `effective_alias_targets` (unit-top plus walk frames). Single
    /// owner for the bare/qualified split so the twins cannot drift.
    /// Pure query over a closure snapshot for LSP hover and completion.
    pub fn resolve_tag_with_targets(
        &self,
        unit: &str,
        alias_targets: &AliasTargets,
        exports: &HashMap<String, Vec<String>>,
        name: &str,
    ) -> DiagnosticResult<TypeTag> {
        let canonical = canonicalize_spelling(name);
        let scope = TargetScope {
            unit,
            alias_targets,
            exports,
        };
        if canonical.contains('<') || canonical.contains('|') {
            return self.resolve_spelling_with_targets(&scope, &canonical, &mut Vec::new(), 0);
        }
        self.resolve_named_with_targets(&scope, &canonical, &mut Vec::new(), 0)
    }

    /// Host-owned tag for `HM::T`: builtins always, plus the named
    /// custom or schema when its entry module matches `host` or is
    /// empty. Empty module means global registration (`register_type`,
    /// startup descriptors): globally visible, so any host alias may
    /// serve it. A non-empty foreign module never leaks across hosts.
    /// Ownership lives on the descriptor entry, never a side map.
    /// Single owner for host-module attribution: qualified reads and
    /// harvest roots both run here.
    pub(super) fn host_owned_tag_free(&self, host: &str, name: &str) -> Option<TypeTag> {
        if let Some(tag) = TypeTag::builtin(name) {
            return Some(tag);
        }
        if let Some(entry) = self.types.get(name) {
            if entry.module == host || entry.module.is_empty() {
                return Some(TypeTag::Custom(entry.descriptor));
            }
            return None;
        }
        if let Some(entry) = self.record_schemas.get(name) {
            if entry.module == host || entry.module.is_empty() {
                return Some(TypeTag::Record(entry.fields.clone()));
            }
            return None;
        }
        None
    }

    /// Bare global lookup: builtins, host customs, record schemas.
    /// Single owner for this prefix so scoped and legacy paths plus
    /// the clean resolver never restate it. Returns the raw tag;
    /// callers run `check_tag_known` for records.
    fn bare_builtin_host_schema(&self, name: &str) -> Option<TypeTag> {
        if let Some(tag) = TypeTag::builtin(name) {
            return Some(tag);
        }
        if let Some(entry) = self.types.get(name) {
            return Some(TypeTag::Custom(entry.descriptor));
        }
        if let Some(entry) = self.record_schemas.get(name) {
            return Some(TypeTag::Record(entry.fields.clone()));
        }
        None
    }

    /// Qualified `ALIAS::BASE` through the active `AliasTargets`:
    /// every target exporting `BASE` contributes its tag plus guard;
    /// 0 matches unknown, 1 returns, same-shape collapses, distinct
    /// shapes are ambiguous regardless of guards: types never degrade
    /// to `Any`, so platform-conditional branches must agree on shape.
    fn resolve_qualified_frozen(
        &self,
        scope: &TargetScope<'_>,
        alias: &str,
        base: &str,
    ) -> DiagnosticResult<TypeTag> {
        let Some(entries) = scope.alias_targets.get(alias) else {
            return Err(typing_diag::typing_unknown(
                &format!(
                    "{}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}",
                    scope.unit
                ),
                &self.type_names(),
                &self.schema_names(),
                &self.alias_names(),
            ));
        };
        let mut matches: Vec<(TypeTag, Option<oxdock_parser::GuardExpr>)> = Vec::new();
        for target in entries {
            if let Some(fkey) = &target.file {
                let is_exported = scope
                    .exports
                    .get(fkey)
                    .is_some_and(|v| v.iter().any(|e| e == base));
                if !is_exported {
                    continue;
                }
                if let Some(tag) = self
                    .type_registry
                    .units
                    .get(fkey)
                    .and_then(|m| m.get(base))
                    .cloned()
                {
                    matches.push((tag, target.guard.clone()));
                    continue;
                }
                // Exported but absent from the unit table: a broken
                // export with no local definition. The parser gates
                // `EXPORT TYPE` on a local `TYPE`, so no re-export path
                // exists here; fail closed instead of consulting another
                // unit's harvests.
                return Err(typing_diag::typing_unknown(
                    &format!(
                        "{}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}",
                        scope.unit
                    ),
                    &self.type_names(),
                    &self.schema_names(),
                    &self.alias_names(),
                ));
            } else if let Some(host) = &target.host
                && let Some(tag) = self.host_owned_tag_free(host, base)
            {
                matches.push((tag, target.guard.clone()));
            }
        }
        if matches.is_empty() {
            return Err(typing_diag::typing_unknown(
                &format!(
                    "{}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}",
                    scope.unit
                ),
                &self.type_names(),
                &self.schema_names(),
                &self.alias_names(),
            ));
        }
        let first = render_structural(&matches[0].0);
        if matches.iter().all(|(t, _)| render_structural(t) == first) {
            return Ok(matches.into_iter().next().expect("nonempty checked").0);
        }
        // Distinct shapes never degrade to `Any`: no escape hatch for
        // types. Guards decide which branch runs, never what the name
        // means, so disjoint distinct shapes fail exactly like
        // overlapping ones.
        Err(typing_diag::typing_ambiguous(alias, base))
    }

    /// Resolve one bare name through the frozen registry: unit table,
    /// that unit's harvested imports, builtins and global host types.
    /// When no table covers the unit (direct API without a closure),
    /// falls back to the legacy global alias directory.
    fn resolve_bare_frozen(
        &self,
        scope: &TargetScope<'_>,
        name: &str,
        resolving: &mut Vec<String>,
        depth: usize,
    ) -> DiagnosticResult<TypeTag> {
        if depth > MAX_GENERIC_DEPTH {
            return Err(typing_diag::typing_max_depth(MAX_GENERIC_DEPTH, name));
        }
        check_bare_payload(name)?;
        if let Some(tag) = self
            .type_registry
            .units
            .get(scope.unit)
            .and_then(|m| m.get(name))
            .cloned()
        {
            return Ok(tag);
        }
        if let Some(tag) = self
            .type_registry
            .harvested
            .get(scope.unit)
            .and_then(|m| m.get(name))
            .cloned()
        {
            return Ok(tag);
        }
        if self.type_registry.units.contains_key(scope.unit) {
            if let Some(tag) = self.bare_builtin_host_schema(name) {
                if matches!(tag, TypeTag::Record(_)) {
                    self.check_tag_known(DECLARATION_SITE, &tag, false)?;
                }
                return Ok(tag);
            }
            // Tables built: file-private aliases stay per unit, never
            // global. Qualified handled by caller; bare misses here.
            return Err(typing_diag::typing_unknown(
                name,
                &self.type_names(),
                &self.schema_names(),
                &self.alias_names(),
            ));
        }
        // No table: legacy single-file path with global aliases.
        if let Some(tag) = self.bare_builtin_host_schema(name) {
            if matches!(tag, TypeTag::Record(_)) {
                self.check_tag_known(DECLARATION_SITE, &tag, false)?;
            }
            return Ok(tag);
        }
        if let Some(target) = self.type_aliases.get(name).cloned() {
            if resolving.iter().any(|s| s.as_str() == name) {
                resolving.push(name.to_string());
                return Err(typing_diag::alias_cycle(resolving));
            }
            resolving.push(name.to_string());
            let out = self.resolve_spelling_with_targets(scope, &target, resolving, depth + 1);
            resolving.pop();
            return out;
        }
        Err(typing_diag::typing_unknown(
            name,
            &self.type_names(),
            &self.schema_names(),
            &self.alias_names(),
        ))
    }

    /// Resolve one bare or qualified leaf through the frozen tables.
    /// Alias targets loop back through the spelling path, so
    /// `LIST<PERSON>` combines; each alias hop costs 1 of the shared
    /// depth budget and repeats bail naming the cycle.
    fn resolve_named_with_targets(
        &self,
        scope: &TargetScope<'_>,
        name: &str,
        resolving: &mut Vec<String>,
        depth: usize,
    ) -> DiagnosticResult<TypeTag> {
        if depth > MAX_GENERIC_DEPTH {
            return Err(typing_diag::typing_max_depth(MAX_GENERIC_DEPTH, name));
        }
        if let Some((alias, base)) = name.split_once(MODULE_SEPARATOR) {
            // Bare LIST/MAP/HANDLE never qualified: reject like bare.
            check_bare_payload(base)?;
            return self.resolve_qualified_frozen(scope, alias, base);
        }
        self.resolve_bare_frozen(scope, name, resolving, depth)
    }

    /// Resolve one canonical spelling that may carry `<...>` args.
    /// Frozen units never touch the process-global intern table:
    /// that table keys on spelling plus run digest only, so one
    /// unit's `LIST<INNER>` would poison another unit (or another
    /// function-local `IMPORT` frame) sharing the spelling. Scoped
    /// resolution builds fresh tags per call instead; the legacy
    /// single-file path (empty registry) keeps interning.
    fn resolve_spelling_with_targets(
        &self,
        scope: &TargetScope<'_>,
        canonical: &str,
        resolving: &mut Vec<String>,
        depth: usize,
    ) -> DiagnosticResult<TypeTag> {
        if !self.type_registry.units.is_empty() {
            let spelled = parse_spelling(canonical)?;
            return self.build_rendered_with_targets(scope, &spelled, resolving, depth);
        }
        let key = format!("{}\x1f{:016x}", canonical, self.type_env_digest);
        if let Some(hit) = lookup_rendered(&key) {
            return Ok(hit);
        }
        let spelled = parse_spelling(canonical)?;
        let tag = self.build_rendered_with_targets(scope, &spelled, resolving, depth)?;
        Ok(intern_rendered(key, tag))
    }

    /// Record one alias binding, folding it into the digest. An
    /// overwrite backs the old target out before mixing the new one
    /// in, so the digest always mirrors current content; identical
    /// re-registration folds nothing, so re-importing the same file
    /// shares cache entries instead of forking them.
    pub(super) fn register_alias(&mut self, name: String, target: String) {
        if let Some(old) = self.type_aliases.insert(name.clone(), target.clone()) {
            if old == target {
                return;
            }
            self.type_env_digest ^= hash_env_entry(b'a', &name, &old);
        }
        self.type_env_digest ^= hash_env_entry(b'a', &name, &target);
    }

    /// Drop one alias binding, backing its hash out of the digest.
    /// Absent names change nothing and fold nothing.
    pub(super) fn remove_alias(&mut self, name: &str) {
        if let Some(old) = self.type_aliases.remove(name) {
            self.type_env_digest ^= hash_env_entry(b'a', name, &old);
        }
    }

    /// Replace the whole alias directory (save/restore paths). Backs
    /// the entire current directory out and mixes the entire next
    /// one in: swaps are bounded and infrequent next to lookups, and
    /// the digest stays an exact mirror of content either way.
    pub(super) fn restore_aliases(&mut self, next: HashMap<String, String>) {
        for (name, target) in &self.type_aliases {
            self.type_env_digest ^= hash_env_entry(b'a', name, target);
        }
        for (name, target) in &next {
            self.type_env_digest ^= hash_env_entry(b'a', name, target);
        }
        self.type_aliases = next;
    }

    /// Target-explicit rendering shared by runtime and static check.
    fn build_rendered_with_targets(
        &self,
        scope: &TargetScope<'_>,
        spelled: &Spelled,
        resolving: &mut Vec<String>,
        depth: usize,
    ) -> DiagnosticResult<TypeTag> {
        if depth > MAX_GENERIC_DEPTH {
            return Err(typing_diag::typing_max_depth_spelled(
                MAX_GENERIC_DEPTH,
                spelled,
            ));
        }
        match spelled {
            Spelled::Named(name) => self.resolve_named_with_targets(scope, name, resolving, depth),
            Spelled::Generic { name, args } => {
                self.build_generic_with_targets(scope, name, args, resolving, depth)
            }
            Spelled::Union(members) => {
                let mut resolved = Vec::with_capacity(members.len());
                for member in members {
                    resolved
                        .push(self.build_rendered_with_targets(scope, member, resolving, depth)?);
                }
                Ok(finish_union(resolved)?)
            }
        }
    }

    /// Target-explicit generic builder shared by runtime and static.
    #[allow(clippy::disallowed_methods)]
    fn build_generic_with_targets(
        &self,
        scope: &TargetScope<'_>,
        name: &str,
        args: &[SpelledField],
        resolving: &mut Vec<String>,
        depth: usize,
    ) -> DiagnosticResult<TypeTag> {
        // Qualified `ALIAS::BASE` heads never build builtins and never
        // strip `ALIAS` blindly. Multi-separator names fail unknown;
        // `LIST`/`MAP`/`HANDLE` heads resolve to name the real problem
        // then fail `no_args`: file-owned `BASE` is a custom type taking
        // no args, and host aliases never own builtin constructors, so
        // the bare `LIST<...>` spelling is the only builder. Single
        // owner with `CleanResolver::resolve_spelled` below.
        if let Some((_alias, base)) = name.split_once(MODULE_SEPARATOR) {
            if base.contains(MODULE_SEPARATOR) {
                return Err(typing_diag::typing_unknown(
                    name,
                    &self.type_names(),
                    &self.schema_names(),
                    &self.alias_names(),
                ));
            }
            self.resolve_named_with_targets(scope, name, resolving, depth)?;
            return Err(typing_diag::typing_no_args(name));
        }
        if name != LIST_TYPE_NAME && name != MAP_TYPE_NAME && name != HANDLE_TYPE_NAME {
            self.resolve_named_with_targets(scope, name, resolving, depth)?;
            return Err(typing_diag::typing_no_args(name));
        }
        if name == HANDLE_TYPE_NAME {
            let [
                SpelledField {
                    name: None,
                    ty: payload,
                    ..
                },
            ] = args
            else {
                return Err(typing_diag::typing_handle_arity());
            };
            let payload = self.build_rendered_with_targets(scope, payload, resolving, depth + 1)?;
            return Ok(TypeTag::HandleOf(std::sync::Arc::new(payload)));
        }
        if name == LIST_TYPE_NAME {
            let [
                SpelledField {
                    name: None,
                    ty: element,
                    ..
                },
            ] = args
            else {
                return Err(typing_diag::typing_list_arity());
            };
            let element = self.build_rendered_with_targets(scope, element, resolving, depth + 1)?;
            return Ok(TypeTag::ListOf(std::sync::Arc::new(element)));
        }
        if name == MAP_TYPE_NAME
            && let [
                SpelledField {
                    name: None,
                    ty: inner,
                    ..
                },
            ] = args
        {
            // Homogeneous map: a single bare value type (`MAP<INT>`,
            // `MAP<STRING>`, `MAP<ANY>`) is the unknown-key map with
            // that value type. Named `name: TYPE` fields still build
            // records below; plain `MAP` never resolves.
            let value_tag = self.build_rendered_with_targets(scope, inner, resolving, depth + 1)?;
            return Ok(TypeTag::MapOf(std::sync::Arc::new(value_tag)));
        }
        let mut fields = Vec::with_capacity(args.len());
        for arg in args {
            let Some(field_name) = arg.name.as_ref() else {
                return Err(typing_diag::typing_map_bare(name));
            };
            let ty = self.build_rendered_with_targets(scope, &arg.ty, resolving, depth + 1)?;
            let default = match &arg.default {
                None => None,
                Some(lit) => {
                    let value = lit.to_value();
                    check_value(&ty, &value).map_err(|_| {
                        typing_diag::typing_default_mismatch(
                            field_name,
                            &oxdock_parser::render_structural(&ty),
                        )
                    })?;
                    Some(value)
                }
            };
            fields.push(Field {
                name: field_name.clone(),
                ty,
                docs: "",
                optional: arg.optional,
                default,
                alias: arg.alias.clone(),
            });
        }
        // Alias uniqueness: one spelling maps to one field. Canonical
        // names and aliases share one namespace, so a clash fails here
        // naming both sides instead of shadowing at parse time.
        // Owner: typing. Single constructors, stable keys, no ad hoc
        // strings at call sites.
        {
            use std::collections::HashMap;
            let mut seen: HashMap<&str, &str> = HashMap::new();
            for field in &fields {
                if let Some(prev) = seen.insert(field.name.as_str(), field.name.as_str()) {
                    let _ = prev;
                    return Err(typing_diag::map_duplicate_field(&field.name));
                }
                if let Some(alias) = field.alias.as_ref() {
                    if alias == &field.name {
                        return Err(typing_diag::alias_self(&field.name, alias));
                    }
                    if let Some(owner) = seen.insert(alias.as_str(), field.name.as_str()) {
                        return Err(typing_diag::alias_clash(alias, &field.name, owner));
                    }
                }
            }
        }
        Ok(TypeTag::Record(std::sync::Arc::from(fields)))
    }
}

/// Normalize resolved union members into one tag: flatten nested
/// unions, absorb on `ANY`, deduplicate, collapse lone survivors.
/// Members keep written order while every comparison stays
/// order-free, so all spellings behave identically. The tag owns
/// everything through `Arc`: shared on clone, freed with the last
/// owner, never leaked.
fn finish_union(members: Vec<TypeTag>) -> DiagnosticResult<TypeTag> {
    let mut flat: Vec<TypeTag> = Vec::with_capacity(members.len());
    for member in members {
        // Nested unions splice flat: members never nest, so every
        // comparison stays one level deep by construction.
        if let TypeTag::Union(_, nested) = member {
            flat.extend(nested.iter().cloned());
        } else {
            flat.push(member);
        }
    }
    if flat.is_empty() {
        return Err(typing_diag::typing_empty_union());
    }
    // `ANY` absorbs the set: admitting everything is `ANY`.
    if flat.iter().any(|member| matches!(member, TypeTag::Any)) {
        return Ok(TypeTag::Any);
    }
    // Full (not just consecutive) deduplication: order-free
    // comparisons make every permutation behave identically.
    let mut unique: Vec<TypeTag> = Vec::with_capacity(flat.len());
    for member in flat {
        if !unique
            .iter()
            .any(|seen| super::static_check::tags_equal(seen, &member))
        {
            unique.push(member);
        }
    }
    if unique.len() == 1 {
        return Ok(unique.pop().expect("single survivor checked above"));
    }
    Ok(TypeTag::union(unique))
}

/// Collect top-level `TYPE` alias definitions into the run's
/// alias directory: name to canonical target spelling. Runs
/// before the static pass so forward references resolve
/// run-wide. Duplicates and collisions with builtin, host,
/// schema, and top-level `FUNC` names are static errors
/// naming the offender. Nested `TYPE` steps cannot occur
/// (the parser rejects them); hand-built ones never resolve.
/// Takes only the snapshot so LSP builds aliases without an
/// `ExecState`.
pub fn collect_type_aliases(
    steps: &[Step],
    type_env: &TypeSnapshot,
) -> DiagnosticResult<HashMap<String, String>> {
    let mut func_names = HashSet::new();
    for step in steps {
        if let StepKind::FuncDef { name, .. } = &step.kind {
            func_names.insert(name.clone());
        }
    }
    let mut aliases = HashMap::new();
    for step in steps {
        let StepKind::TypeAlias { name, target } = &step.kind else {
            continue;
        };
        if aliases.contains_key(name) {
            return Err(typing_diag::alias_already_defined(name));
        }
        if TypeTag::builtin(name).is_some() {
            return Err(typing_diag::alias_builtin_collision(name));
        }
        if type_env.types.contains_key(name) {
            return Err(typing_diag::alias_host_collision(name));
        }
        if type_env.record_schemas.contains_key(name) {
            return Err(typing_diag::alias_schema_collision(name));
        }
        if func_names.contains(name) {
            return Err(typing_diag::alias_func_collision(name));
        }
        aliases.insert(name.clone(), canonicalize_spelling(target));
    }
    Ok(aliases)
}

/// One bare `IMPORT [TYPE T FROM "file"]` harvest request: the
/// importing unit, the defining file key and the host module name
/// (`None` for file harvests, `Some` for host harvests; exactly one
/// is set). Bare names collide closure-wide across units (mirroring the
/// runtime bare-global merge) while resolution stays per importing unit.
pub struct HarvestRequest {
    pub importer: String,
    pub defining: Option<String>,
    pub host: Option<String>,
    pub name: String,
}

/// Clean per-unit resolver: resolves a bare name in its defining
/// unit's namespace (locals plus that unit's own qualified imports
/// plus harvested globals plus host/builtins), never caller entries.
/// Stores `TypeTag` directly so defaults and field aliases survive.
/// Every failure propagates: broken exports fail the closure even
/// when unused, so no dead code hides a bad shape.
struct CleanResolver<'a> {
    state: &'a TypeSnapshot,
    raw_bare: &'a HashMap<String, HashMap<String, String>>,
    targets: &'a HashMap<String, super::native::AliasTargets>,
    exports: &'a HashMap<String, Vec<String>>,
    harvests: HashMap<(String, String), (Option<String>, Option<String>)>,
    bare_cache: HashMap<(String, String), TypeTag>,
    stack: Vec<(String, String)>,
    harvested: HashMap<(String, String), TypeTag>,
}

impl<'a> CleanResolver<'a> {
    fn builtin_or_host(&self, name: &str) -> Option<TypeTag> {
        // Bare LIST/MAP/HANDLE never resolve here: they need payloads.
        // Returning them would let `TYPE H = HANDLE` slip through the
        // per-unit tables and pass the declaration gate later.
        if check_bare_payload(name).is_err() {
            return None;
        }
        self.state.bare_builtin_host_schema(name)
    }

    /// Host-owned tag for the resolver: the shared
    /// [`TypeSnapshot::host_owned_tag_free`] rule, minus bare
    /// `LIST`/`MAP`/`HANDLE`, which need payloads and fail with their
    /// declaration errors instead of resolving here.
    fn host_owned_tag(&self, host: &str, name: &str) -> Option<TypeTag> {
        // Bare LIST/MAP/HANDLE need payloads: fail with the
        // declaration error downstream instead of resolving here.
        if check_bare_payload(name).is_err() {
            return None;
        }
        self.state.host_owned_tag_free(host, name)
    }

    /// Resolve one bare harvest request in its home namespace:
    /// file harvests resolve in the defining file (recursing through
    /// further harvests with cycle detection). Host harvests resolve
    /// through the shared host-ownership rule, so `HOST_A` can never
    /// lift a type owned by `HOST_B`, while empty-module (global)
    /// registrations stay visible everywhere. Single owner for
    /// harvest roots: the build pre-pass and the on-demand use-site
    /// path both run here, so eager and lazy harvests cannot drift.
    /// Anything unresolvable fails closed.
    fn harvest_tag(
        &mut self,
        defining: &Option<String>,
        host: &Option<String>,
        name: &str,
    ) -> DiagnosticResult<TypeTag> {
        if let Some(fkey) = defining {
            // Export gate: a bare harvest only serves exported types,
            // mirroring the runtime import gate. Unexported names fail
            // closed here instead of leaking file-private aliases.
            let exported = self
                .exports
                .get(fkey)
                .is_some_and(|v| v.iter().any(|e| e == name));
            if !exported {
                return Err(typing_diag::typing_unknown(
                    name,
                    &self.state.type_names(),
                    &self.state.schema_names(),
                    &self.state.alias_names(),
                ));
            }
            return self.resolve_bare(fkey, name);
        }
        if let Some(host_name) = host
            && let Some(tag) = self.host_owned_tag(host_name, name)
        {
            return Ok(tag);
        }
        // No defining file and no owning host answers: fail closed.
        // (Unresolvable bare harvest lines with no referencing
        // definition never reach here; the runtime import gate reports
        // those naming the host.)
        Err(typing_diag::typing_unknown(
            name,
            &self.state.type_names(),
            &self.state.schema_names(),
            &self.state.alias_names(),
        ))
    }

    fn resolve_bare(&mut self, unit: &str, name: &str) -> DiagnosticResult<TypeTag> {
        let key = (unit.to_string(), name.to_string());
        if let Some(hit) = self.bare_cache.get(&key) {
            return Ok(hit.clone());
        }
        if self.stack.iter().any(|(u, n)| u == unit && n == name) {
            let mut chain: Vec<String> = self
                .stack
                .iter()
                .map(|(u, n)| format!("{u}{MODULE_SEPARATOR}{n}"))
                .collect();
            chain.push(format!("{unit}{MODULE_SEPARATOR}{name}"));
            return Err(typing_diag::alias_cycle(&chain));
        }
        if let Some(target) = self.raw_bare.get(unit).and_then(|m| m.get(name)).cloned() {
            self.stack.push((unit.to_string(), name.to_string()));
            let spelled = parse_spelling(&target)?;
            let out = self.resolve_spelled(unit, &spelled, 0);
            self.stack.pop();
            let tag = out?;
            self.bare_cache.insert(key, tag.clone());
            return Ok(tag);
        }
        if let Some(tag) = self.harvested.get(&key).cloned() {
            return Ok(tag);
        }
        // Bare harvests resolve on demand in the importing unit's
        // namespace (single pass: no build-then-lift-then-rebuild).
        // Cycles thread through `self.stack` like every other alias
        // hop; genuinely unknown names fail closed below with zero
        // suppression. Harvests stay per-unit, so one file's bare
        // import never leaks into a sibling.
        if let Some((defining, host)) = self.harvests.get(&key).cloned() {
            self.stack.push((unit.to_string(), name.to_string()));
            let out = self.harvest_tag(&defining, &host, name);
            self.stack.pop();
            let tag = out?;
            self.harvested.insert(key.clone(), tag.clone());
            return Ok(tag);
        }
        // Bare LIST/MAP/HANDLE need payloads: fail here with the
        // declaration error so `TYPE H = HANDLE` names the rule
        // instead of falling through to `unknown type`.
        check_bare_payload(name)?;
        if let Some(tag) = self.builtin_or_host(name) {
            // Bare host/builtins are global; collapsing across units is
            // intended (they are not file-private). Every composite
            // tag validates like the frozen path, so unknown nested
            // customs fail here instead of slipping through.
            self.state.check_tag_known(DECLARATION_SITE, &tag, false)?;
            return Ok(tag);
        }
        // Missing bare name fails closed here; the closure propagates
        // it even when unused, so no broken export hides. Cycles use
        // `alias_cycle` above and propagate the same way.
        Err(typing_diag::typing_unknown(
            &format!("{unit}{MODULE_SEPARATOR}{name}"),
            &self.state.type_names(),
            &self.state.schema_names(),
            &self.state.alias_names(),
        ))
    }

    fn resolve_spelled(
        &mut self,
        unit: &str,
        spelled: &Spelled,
        depth: usize,
    ) -> DiagnosticResult<TypeTag> {
        if depth > MAX_GENERIC_DEPTH {
            return Err(typing_diag::typing_max_depth_spelled(
                MAX_GENERIC_DEPTH,
                spelled,
            ));
        }
        match spelled {
            Spelled::Named(name) => {
                if let Some((alias, base)) = name.split_once(MODULE_SEPARATOR) {
                    self.resolve_qualified(unit, alias, base)
                } else {
                    self.resolve_bare(unit, name)
                }
            }
            Spelled::Generic { name, args } => {
                if name == LIST_TYPE_NAME {
                    let [field] = args.as_slice() else {
                        return Err(typing_diag::typing_list_arity());
                    };
                    if field.name.is_some() {
                        return Err(typing_diag::typing_list_arity());
                    }
                    let inner = self.resolve_spelled(unit, &field.ty, depth + 1)?;
                    return Ok(TypeTag::ListOf(std::sync::Arc::new(inner)));
                }
                if name == HANDLE_TYPE_NAME {
                    let [field] = args.as_slice() else {
                        return Err(typing_diag::typing_handle_arity());
                    };
                    if field.name.is_some() {
                        return Err(typing_diag::typing_handle_arity());
                    }
                    let inner = self.resolve_spelled(unit, &field.ty, depth + 1)?;
                    return Ok(TypeTag::HandleOf(std::sync::Arc::new(inner)));
                }
                if name == MAP_TYPE_NAME {
                    if let [field] = args.as_slice()
                        && field.name.is_none()
                    {
                        let inner = self.resolve_spelled(unit, &field.ty, depth + 1)?;
                        return Ok(TypeTag::MapOf(std::sync::Arc::new(inner)));
                    }
                    let mut fields = Vec::with_capacity(args.len());
                    for arg in args {
                        let Some(fname) = arg.name.as_ref() else {
                            return Err(typing_diag::typing_map_bare(name));
                        };
                        let ty = self.resolve_spelled(unit, &arg.ty, depth + 1)?;
                        let default = match &arg.default {
                            None => None,
                            Some(lit) => {
                                let v = lit.to_value();
                                check_value(&ty, &v).map_err(|_| {
                                    typing_diag::typing_default_mismatch(
                                        fname,
                                        &render_structural(&ty),
                                    )
                                })?;
                                Some(v)
                            }
                        };
                        fields.push(Field {
                            name: fname.clone(),
                            ty,
                            docs: "",
                            optional: arg.optional,
                            default,
                            alias: arg.alias.clone(),
                        });
                    }
                    // Alias uniqueness mirrors `build_rendered`.
                    {
                        use std::collections::HashSet;
                        let mut seen = HashSet::new();
                        for f in &fields {
                            if !seen.insert(f.name.clone()) {
                                return Err(typing_diag::alias_func_collision(&f.name));
                            }
                            if let Some(a) = &f.alias
                                && !seen.insert(a.clone())
                            {
                                return Err(typing_diag::alias_func_collision(a));
                            }
                        }
                    }
                    return Ok(TypeTag::Record(std::sync::Arc::from(fields)));
                }
                // Any other head resolves to name the real problem.
                // Qualified heads never strip `ALIAS` blindly and never
                // build builtins: multi-separator names fail unknown, and
                // `LIST`/`MAP`/`HANDLE` heads resolve to name the real
                // problem then fail `no_args`. Host aliases never own
                // builtin constructors, so bare `LIST<...>` is the only
                // builder. Single owner with
                // `ExecState::build_generic_with_targets` above.
                if let Some((alias, base)) = name.split_once(MODULE_SEPARATOR) {
                    if base.contains(MODULE_SEPARATOR) {
                        return Err(typing_diag::typing_unknown(
                            name,
                            &self.state.type_names(),
                            &self.state.schema_names(),
                            &self.state.alias_names(),
                        ));
                    }
                    let _ = self.resolve_qualified(unit, alias, base)?;
                    return Err(typing_diag::typing_no_args(name));
                }
                let _ = self.resolve_bare(unit, name)?;
                Err(typing_diag::typing_no_args(name))
            }
            Spelled::Union(members) => {
                let mut out = Vec::with_capacity(members.len());
                for m in members {
                    out.push(self.resolve_spelled(unit, m, depth)?);
                }
                finish_union(out)
            }
        }
    }

    fn resolve_qualified(
        &mut self,
        importer_unit: &str,
        alias: &str,
        base: &str,
    ) -> DiagnosticResult<TypeTag> {
        let targets = self.targets.get(importer_unit);
        let Some(entries) = targets.and_then(|m| m.get(alias)) else {
            return Err(typing_diag::typing_unknown(
                &format!("{importer_unit}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}"),
                &self.state.type_names(),
                &self.state.schema_names(),
                &self.state.alias_names(),
            ));
        };
        // Collect every target exporting FOO: 0 matches unknown,
        // 1 match returns, same-shape collapses, distinct shapes are
        // ambiguous regardless of guards (no `Any` escape hatch for
        // types). Every failure propagates: no poison, no silent
        // skips, so broken exports fail the closure even when unused.
        // Same-shape matches collapse regardless of guards.
        let mut matches: Vec<(TypeTag, Option<oxdock_parser::GuardExpr>)> = Vec::new();
        for target in entries {
            if let Some(fkey) = &target.file {
                let exported = self.exports.get(fkey);
                let is_exported = exported.is_some_and(|v| v.iter().any(|e| e == base));
                if !is_exported {
                    continue;
                }
                let tag = self.resolve_bare(fkey, base)?;
                matches.push((tag, target.guard.clone()));
            } else if let Some(host) = &target.host
                && let Some(tag) = self.host_owned_tag(host, base)
            {
                matches.push((tag, target.guard.clone()));
            }
        }
        if matches.is_empty() {
            return Err(typing_diag::typing_unknown(
                &format!("{importer_unit}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}"),
                &self.state.type_names(),
                &self.state.schema_names(),
                &self.state.alias_names(),
            ));
        }
        // Same shape everywhere: one tag regardless of guards.
        let first_render = render_structural(&matches[0].0);
        if matches
            .iter()
            .all(|(tag, _)| render_structural(tag) == first_render)
        {
            return Ok(matches.into_iter().next().expect("nonempty checked").0);
        }
        // Distinct shapes never degrade to `Any`: no escape hatch for
        // types. Guards decide which branch runs, never what the name
        // means, so disjoint distinct shapes fail exactly like
        // overlapping ones.
        Err(typing_diag::typing_ambiguous(alias, base))
    }
}

/// Frozen per-unit type registry: each unit's bare names resolve to
/// `TypeTag` directly in the defining file's namespace (never the
/// importer's), preserving defaults and field aliases without string
/// round-tripping. Built once per closure in a single pass:
/// `harvests` lets bare `IMPORT [TYPE T FROM "f"]` names resolve on
/// demand in their defining file's namespace, so no
/// build-then-lift-then-rebuild race. Qualified `ALIAS::NAME`
/// resolves on demand through live `AliasTargets`, never from a
/// precomputed table. Every failure propagates: broken exports fail
/// the closure even when unused, so no dead code hides a bad shape.
fn describe_harvest_source(defining: &Option<String>, host: &Option<String>) -> String {
    if let Some(defining) = defining {
        defining.clone()
    } else if let Some(host) = host {
        host.clone()
    } else {
        String::new()
    }
}

/// Build per-unit bare tables directly on a snapshot so LSP can
/// construct type environments without an `ExecState`.
pub fn build_unit_tables(
    type_env: &mut TypeSnapshot,
    raw_bare: &HashMap<String, HashMap<String, String>>,
    targets: &HashMap<String, super::native::AliasTargets>,
    exports: &HashMap<String, Vec<String>>,
    harvests: &[HarvestRequest],
) -> DiagnosticResult<()> {
    let mut bare_tags: HashMap<String, HashMap<String, TypeTag>> = HashMap::new();
    // Bare namespace is global at runtime (`type_aliases` merges bare
    // harvests globally, collision-checked). Static mirrors that: the
    // same bare name from distinct sources collides closure-wide,
    // even across units. Resolution stays per-unit below so qualified
    // reads never leak through unrelated harvests.
    let mut harvest_sources: HashMap<String, (Option<String>, Option<String>)> = HashMap::new();
    for req in harvests {
        match harvest_sources.get(&req.name) {
            None => {
                harvest_sources.insert(req.name.clone(), (req.defining.clone(), req.host.clone()));
            }
            Some((defining, host)) if defining == &req.defining && host == &req.host => {
                // Same source harvested twice: idempotent.
            }
            Some((defining, host)) => {
                return Err(typing_diag::typing_harvest_collision(
                    &req.name,
                    &describe_harvest_source(defining, host),
                    &describe_harvest_source(&req.defining, &req.host),
                ));
            }
        }
    }
    let mut harvest_map: HashMap<(String, String), (Option<String>, Option<String>)> =
        HashMap::new();
    for req in harvests {
        harvest_map.insert(
            (req.importer.clone(), req.name.clone()),
            (req.defining.clone(), req.host.clone()),
        );
    }
    let mut resolver = CleanResolver {
        state: &*type_env,
        raw_bare,
        targets,
        exports,
        harvests: harvest_map,
        bare_cache: HashMap::new(),
        stack: Vec::new(),
        harvested: type_env
            .type_registry
            .harvested
            .iter()
            .flat_map(|(unit, map)| {
                map.iter()
                    .map(|(name, tag)| ((unit.clone(), name.clone()), tag.clone()))
            })
            .collect(),
    };
    // Eager file-harvest roots first: every file harvest resolves up
    // front through the same `harvest_tag` owner the on-demand path
    // uses, so both `TYPE` definitions referencing harvests and later
    // use sites (`LET`, params) see them in this single pass. Nested
    // harvests recurse with cycle detection; anything unresolvable
    // fails the closure here even when unused. Host harvests skip
    // this pass: the runtime import gate owns their "no such TYPE"
    // report, and use sites resolve them per-unit on demand.
    for req in harvests {
        if req.defining.is_none() {
            continue;
        }
        let key = (req.importer.clone(), req.name.clone());
        if resolver.harvested.contains_key(&key) {
            continue;
        }
        let tag = resolver.harvest_tag(&req.defining, &req.host, &req.name)?;
        resolver.harvested.insert(key, tag);
    }
    for (unit, names) in raw_bare {
        for name in names.keys() {
            // Every failure propagates: broken exports fail the closure
            // even when unused. No poison, no silent skips.
            let tag = resolver.resolve_bare(unit, name)?;
            bare_tags
                .entry(unit.clone())
                .or_default()
                .insert(name.clone(), tag);
        }
    }
    let harvested = std::mem::take(&mut resolver.harvested);
    // Ensure every unit has an entry (even empty) so scoped lookup
    // fails closed instead of falling back to global aliases.
    for unit in raw_bare.keys() {
        bare_tags.entry(unit.clone()).or_default();
    }
    for importer in targets.keys() {
        bare_tags.entry(importer.clone()).or_default();
    }
    // Entry unit always present for the `None` path.
    bare_tags
        .entry(super::import::ENTRY_UNIT.to_string())
        .or_default();
    drop(resolver);
    type_env.type_registry.units = bare_tags;
    // Merge per-unit harvested imports back into the registry.
    for ((unit, name), tag) in harvested {
        type_env
            .type_registry
            .harvested
            .entry(unit)
            .or_default()
            .insert(name, tag);
    }
    Ok(())
}

impl TypeSnapshot {
    /// Check one tag against the directories: customs must name a
    /// registered descriptor, shaped tags recurse into fields and
    /// elements, builtins are variants and cannot be misspelled.
    /// Unknown names bail naming the use site and every known type.
    /// Single choke for declaration validity: known customs plus
    /// the VOID position rule. VOID is legal only as a bare function
    /// return (`top_void` covers exactly that call) or as the direct
    /// payload of HANDLE (`HANDLE<VOID>`). Every other position is a
    /// static error naming the site: variable, parameter, record
    /// field, union member, container element, or anything nested
    /// deeper. One recursion serves all declaration sites, so the
    /// rule cannot drift between LET, params, returns, schemas, and
    /// aliases: resolve first, then validate here.
    fn check_tag_known(&self, what: &str, tag: &TypeTag, top_void: bool) -> DiagnosticResult<()> {
        match tag {
            TypeTag::Custom(descriptor) => {
                if !self.types.contains_key(descriptor.name) {
                    return Err(typing_diag::typing_unregistered(
                        what,
                        descriptor.name,
                        &self.type_names(),
                    ));
                }
            }
            TypeTag::Void if !top_void => {
                return Err(typing_diag::typing_void_position(what));
            }
            TypeTag::Void => {}
            TypeTag::ListOf(element) => self.check_tag_known(what, element, false)?,
            TypeTag::HandleOf(payload) => self.check_tag_known(what, payload, true)?,
            TypeTag::MapOf(values) => self.check_tag_known(what, values, false)?,
            TypeTag::Record(fields) => {
                for field in fields.iter() {
                    self.check_tag_known(what, &field.ty, false)?;
                }
            }
            // Union members recurse like shaped tags: every member
            // must name a known type, so no unknown hides in a set.
            // A VOID member is never admitted: unions of handles stay
            // inside the payload (HANDLE<INT|STRING>), never at the
            // root or beside a value type.
            TypeTag::Union(_, members) => {
                for member in members.iter() {
                    self.check_tag_known(what, member, false)?;
                }
            }
            // Bare words are variants and cannot be misspelled: every
            // builtin is listed so a new word kind fails here until
            // its directory rule is explicit.
            TypeTag::String
            | TypeTag::Int
            | TypeTag::Float
            | TypeTag::Bool
            | TypeTag::List
            | TypeTag::Map
            | TypeTag::Pipe
            | TypeTag::Handle
            | TypeTag::Duration
            | TypeTag::Path
            | TypeTag::Semaphore
            | TypeTag::Permit
            | TypeTag::Any => {}
        }
        Ok(())
    }

    /// Declaration-site gate for everything that is not a function
    /// return: LET bindings, parameters, schemas, aliases at use.
    /// Single choke so the VOID position rule cannot drift between
    /// the static checker and runtime definition paths.
    pub fn check_declaration_tag(&self, what: &str, tag: &TypeTag) -> DiagnosticResult<()> {
        self.check_tag_known(what, tag, false)
    }

    /// Return-position gate: bare VOID is legal here (and only
    /// here, besides HANDLE payloads). Same single recursion as
    /// every other declaration site.
    pub fn check_return_tag(&self, what: &str, tag: &TypeTag) -> DiagnosticResult<()> {
        self.check_tag_known(what, tag, true)
    }

    /// Resolve a descriptor by name, or `None` when unregistered.
    pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
        self.types.get(name).map(|e| e.descriptor)
    }

    /// Every registered type name: startup descriptors first, then hosts in
    /// registration order, then script aliases.
    pub fn type_names(&self) -> Vec<String> {
        let mut names: Vec<String> = startup_descriptors()
            .into_iter()
            .map(|(name, _)| name.to_string())
            .collect();
        for name in self.types.keys() {
            if !names.iter().any(|n| n == name) {
                names.push(name.clone());
            }
        }
        for name in self.alias_names() {
            if !names.contains(&name) {
                names.push(name);
            }
        }
        names
    }
}

impl<P: ProcessManager> ExecState<P> {
    /// Resolve a source-level type name via live alias targets.
    /// Impure wrapper around the pure snapshot query: derives
    /// targets from import state, then delegates to
    /// `TypeSnapshot::resolve_tag_with_targets` so LSP and runtime
    /// share one owner.
    pub fn resolve_tag(&self, name: &str) -> DiagnosticResult<TypeTag> {
        let unit = super::import::active_unit_key(self);
        let alias_targets = super::import::unit_alias_targets(self, &unit);
        let exports = Self::module_type_exports(self);
        self.type_env
            .resolve_tag_with_targets(&unit, &alias_targets, &exports, name)
    }

    /// Unit-scoped resolution for checkers holding only `&ExecState`.
    /// Derives live targets for `unit`, then delegates to the snapshot.
    pub fn resolve_tag_for_unit(&self, unit: &str, name: &str) -> DiagnosticResult<TypeTag> {
        let alias_targets = super::import::unit_alias_targets(self, unit);
        let exports = Self::module_type_exports(self);
        self.type_env
            .resolve_tag_with_targets(unit, &alias_targets, &exports, name)
    }

    /// Type exports per file key from live modules.
    pub(crate) fn module_type_exports(state: &ExecState<P>) -> HashMap<String, Vec<String>> {
        module_type_exports_map(state)
    }

    /// Explicit delegation to the embedded snapshot: `ExecState` is
    /// not a smart pointer to `TypeSnapshot`, so each forwarded query
    /// names its owner instead of relying on `Deref` coercion.
    pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
        self.type_env.register_type(descriptor);
    }

    pub fn is_known_type(&self, name: &str) -> bool {
        self.type_env.is_known_type(name)
    }

    pub fn register_record_schema(&mut self, name: &'static str, fields: std::sync::Arc<[Field]>) {
        self.type_env.register_record_schema(name, fields);
    }

    pub fn schema_names(&self) -> Vec<String> {
        self.type_env.schema_names()
    }

    pub fn alias_names(&self) -> Vec<String> {
        self.type_env.alias_names()
    }

    pub fn alias_target(&self, name: &str) -> Option<String> {
        self.type_env.alias_target(name)
    }

    pub fn resolve_tag_with_targets(
        &self,
        unit: &str,
        alias_targets: &AliasTargets,
        exports: &HashMap<String, Vec<String>>,
        name: &str,
    ) -> DiagnosticResult<TypeTag> {
        self.type_env
            .resolve_tag_with_targets(unit, alias_targets, exports, name)
    }

    pub(super) fn register_alias(&mut self, name: String, target: String) {
        self.type_env.register_alias(name, target);
    }

    pub(super) fn remove_alias(&mut self, name: &str) {
        self.type_env.remove_alias(name);
    }

    pub(super) fn restore_aliases(&mut self, next: HashMap<String, String>) {
        self.type_env.restore_aliases(next);
    }

    pub fn check_declaration_tag(&self, what: &str, tag: &TypeTag) -> DiagnosticResult<()> {
        self.type_env.check_declaration_tag(what, tag)
    }

    pub fn check_return_tag(&self, what: &str, tag: &TypeTag) -> DiagnosticResult<()> {
        self.type_env.check_return_tag(what, tag)
    }

    pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
        self.type_env.describe_type(name)
    }

    pub fn type_names(&self) -> Vec<String> {
        self.type_env.type_names()
    }

    /// Fail fast when any registered function declares param or return
    /// type names outside the type directory. Runs once per run before
    /// the first step executes: param arity and `LET` coercion already
    /// check values at use time, but a typo'd `returns` label otherwise
    /// lives forever as a lie in `DESCRIBE` output and generated
    /// references. Unknown names bail listing every known type. A
    /// closed `allowed` set without a type is rejected too: the set
    /// only means something alongside the `STRING` check that enforces
    /// it, so hand-built entries cannot render a set they never check.
    pub fn validate_function_type_tags(&self) -> DiagnosticResult<()> {
        for meta in self.functions.all_metas() {
            if let Some(params) = meta.params.as_deref() {
                for (position, param) in params.iter().enumerate() {
                    if let Some(expected) = param.param_type.as_ref() {
                        let what = format!("param '{}' of '{}'", param.name, meta.name);
                        self.type_env.check_tag_known(&what, expected, false)?;
                    }
                    if param.param_type.is_none() && param.allowed.is_some() {
                        return Err(typing_diag::func_param_values_without_type(
                            &param.name,
                            &meta.name,
                        ));
                    }
                    if param.optional {
                        // Omission fills an empty MAP, so only trailing
                        // MAP params qualify: anything else would fill a
                        // value the caller never chose.
                        let trails = params[position..].iter().all(|later| later.optional);
                        if !trails {
                            return Err(typing_diag::func_optional_before_required(
                                &param.name,
                                &meta.name,
                            ));
                        }
                        // Omission fills an empty MAP, so the param type
                        // must admit one: checked semantically (empty MAP
                        // against the type) instead of naming admissible
                        // constructors, so defaulted shapes and unions
                        // qualify exactly when the fill verifies.
                        let fills = param.param_type.as_ref().is_some_and(|expected| {
                            check_value(expected, &Value::map(std::collections::BTreeMap::new()))
                                .is_ok()
                        });
                        if !fills {
                            return Err(typing_diag::func_optional_without_map(
                                &param.name,
                                &meta.name,
                            ));
                        }
                    }
                }
            }
            if let Some(returns) = meta.returns.as_ref() {
                let what = format!("return of '{}'", meta.name);
                self.type_env.check_tag_known(&what, returns, true)?;
            }
        }
        Ok(())
    }
}