domainforge-core 0.18.2

Rust core library implementing the SEA DSL primitives and validation engine.
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
use crate::application::diagnostic::{
    ApplicationDiagnostic, APP014_IMPORT_CYCLE, APP014_NOT_EXPORTED, APP014_SYMBOL_COLLISION,
    APP014_UNRESOLVED_ALIAS, APP014_UNRESOLVED_SPECIFIER,
};
use crate::application::ApplicationDiagnosticCode;
use crate::error::fuzzy::levenshtein_distance;
use crate::parser::ast::{Ast, AstNode, ImportDecl, ImportSpecifier};
use crate::parser::{parse_source, ParseError, ParseOptions, ParseResult};
use crate::registry::{NamespaceBinding, NamespaceRegistry};
use indexmap::IndexMap;
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use unicode_normalization::UnicodeNormalization;

#[cfg(feature = "cli")]
const MAX_FILESYSTEM_IMPORT_DEPTH: usize = 128;
#[cfg(feature = "cli")]
const MAX_FILESYSTEM_MODULES: usize = 1024;

#[derive(Debug, Clone)]
pub struct ModuleInfo {
    pub namespace: String,
    pub exports: HashSet<String>,
    pub ast: Ast,
}

#[derive(Debug)]
pub struct ModuleResolver<'a> {
    registry: &'a NamespaceRegistry,
    bindings: Vec<NamespaceBinding>,
    loaded_modules: HashMap<PathBuf, ModuleInfo>,
    visiting: HashSet<PathBuf>,
}

impl<'a> ModuleResolver<'a> {
    pub fn new(registry: &'a NamespaceRegistry) -> ParseResult<Self> {
        let bindings = registry
            .resolve_files()
            .map_err(|e| ParseError::GrammarError(e.to_string()))?;
        Ok(Self {
            registry,
            bindings,
            loaded_modules: HashMap::new(),
            visiting: HashSet::new(),
        })
    }

    pub fn validate_entry(
        &mut self,
        entry_path: impl AsRef<Path>,
        source: &str,
    ) -> ParseResult<Ast> {
        let path = entry_path
            .as_ref()
            .canonicalize()
            .unwrap_or_else(|_| entry_path.as_ref().to_path_buf());
        let ast = parse_source(source)?;
        self.visit(&path, &ast)?;
        Ok(ast)
    }

    pub fn validate_dependencies(
        &mut self,
        entry_path: impl AsRef<Path>,
        ast: &Ast,
    ) -> ParseResult<()> {
        let path = entry_path
            .as_ref()
            .canonicalize()
            .unwrap_or_else(|_| entry_path.as_ref().to_path_buf());
        self.visit(&path, ast)
    }

    fn visit(&mut self, path: &Path, ast: &Ast) -> ParseResult<()> {
        let canonical = if path.to_string_lossy().starts_with("__std__") {
            path.to_path_buf()
        } else {
            path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
        };

        if self.visiting.contains(&canonical) {
            // Build the cycle path from currently visiting modules
            let cycle: Vec<String> = self
                .visiting
                .iter()
                .map(|p| p.to_string_lossy().to_string())
                .chain(std::iter::once(canonical.to_string_lossy().to_string()))
                .collect();
            return Err(ParseError::circular_dependency(cycle));
        }
        if self.loaded_modules.contains_key(&canonical) {
            return Ok(());
        }

        self.visiting.insert(canonical.clone());
        let namespace = ast.metadata.namespace.clone().unwrap_or_else(|| {
            self.registry
                .namespace_for(path)
                .unwrap_or(self.registry.default_namespace())
                .to_string()
        });
        let exports = collect_exports(ast);

        for import in &ast.metadata.imports {
            let dep_path = self.resolve_module_path(&import.from_module)?;
            let dependency_ast = self.parse_file(&dep_path)?;
            self.visit(&dep_path, &dependency_ast)?;
            self.validate_import_targets(import, &dep_path)?;
        }

        self.loaded_modules.insert(
            canonical.clone(),
            ModuleInfo {
                namespace,
                exports,
                ast: ast.clone(),
            },
        );
        self.visiting.remove(&canonical);
        Ok(())
    }

    fn parse_file(&self, path: &Path) -> ParseResult<Ast> {
        let path_str = path.to_string_lossy();
        if path_str.starts_with("__std__") {
            let namespace = path_str.strip_prefix("__std__").unwrap();
            let content = match namespace {
                "std" | "std:core" => include_str!("../../std/core.sea"),
                "std:http" => include_str!("../../std/http.sea"),
                "std:aws" => include_str!("../../std/aws.sea"),
                _ => {
                    return Err(ParseError::GrammarError(format!(
                        "Unknown std module: {}",
                        namespace
                    )))
                }
            };
            return parse_source(content);
        }

        let content = fs::read_to_string(path).map_err(|e| {
            ParseError::GrammarError(format!("Failed to read module {}: {}", path.display(), e))
        })?;
        parse_source(&content)
    }

    fn resolve_module_path(&self, namespace: &str) -> ParseResult<PathBuf> {
        if namespace == "std" || namespace.starts_with("std:") {
            return Ok(PathBuf::from(format!("__std__{}", namespace)));
        }

        self.bindings
            .iter()
            .find(|binding| binding.namespace == namespace)
            .map(|binding| binding.path.clone())
            .ok_or_else(|| {
                // Find similar namespace for suggestion
                let suggestion = self.suggest_similar_namespace(namespace);
                ParseError::namespace_not_found(namespace, 0, 0, suggestion)
            })
    }

    fn validate_import_targets(&self, import: &ImportDecl, dep_path: &Path) -> ParseResult<()> {
        let canonical = if dep_path.to_string_lossy().starts_with("__std__") {
            dep_path.to_path_buf()
        } else {
            dep_path
                .canonicalize()
                .unwrap_or_else(|_| dep_path.to_path_buf())
        };
        let module = self.loaded_modules.get(&canonical).ok_or_else(|| {
            ParseError::GrammarError(format!(
                "Expected module '{}' to be loaded before validating imports",
                dep_path.display()
            ))
        })?;

        match &import.specifier {
            ImportSpecifier::Wildcard(_) => Ok(()),
            ImportSpecifier::Named(items) => {
                for item in items {
                    if !module.exports.contains(&item.name) {
                        return Err(ParseError::symbol_not_exported(
                            &item.name,
                            &module.namespace,
                            0, // TODO: Extract line from import.location if available
                            0,
                            module.exports.iter().cloned().collect(),
                        ));
                    }
                }
                Ok(())
            }
        }
    }

    /// Find a similar namespace name for error suggestions using Levenshtein distance
    fn suggest_similar_namespace(&self, target: &str) -> Option<String> {
        let available: Vec<&str> = self.bindings.iter().map(|b| b.namespace.as_str()).collect();

        available
            .iter()
            .filter_map(|ns| {
                let distance = levenshtein_distance(target, ns);
                if distance <= 2 {
                    Some((*ns, distance))
                } else {
                    None
                }
            })
            .min_by_key(|(_, d)| *d)
            .map(|(ns, _)| ns.to_string())
    }
}

fn collect_exports(ast: &Ast) -> HashSet<String> {
    let mut exports = HashSet::new();
    for node in &ast.declarations {
        if let AstNode::Export(inner) = &node.node {
            if let Some(name) = declaration_name(&inner.node) {
                exports.insert(name.to_string());
            }
        }
    }
    exports
}

fn declaration_name(node: &AstNode) -> Option<&str> {
    match node {
        AstNode::Entity { name, .. }
        | AstNode::Resource { name, .. }
        | AstNode::Flow {
            resource_name: name,
            ..
        }
        | AstNode::Pattern { name, .. }
        | AstNode::Role { name, .. }
        | AstNode::Relation { name, .. }
        | AstNode::Dimension { name }
        | AstNode::UnitDeclaration { symbol: name, .. }
        | AstNode::Policy { name, .. }
        | AstNode::Instance { name, .. }
        | AstNode::ConceptChange { name, .. }
        | AstNode::Metric { name, .. }
        | AstNode::MappingDecl { name, .. }
        | AstNode::ProjectionDecl { name, .. }
        | AstNode::Cell { name, .. }
        | AstNode::SystemDependency { name, .. }
        | AstNode::Runtime { name, .. }
        | AstNode::Tool { name, .. }
        | AstNode::DependencySet { name, .. }
        | AstNode::Service { name, .. }
        | AstNode::Mount { name, .. }
        | AstNode::Endpoint { name, .. }
        | AstNode::NetworkFlow { name, .. }
        | AstNode::Credential { name, .. } => Some(name),
        // A role binding relates two previously-declared, independently
        // named symbols; it has no name of its own to export or import.
        AstNode::RoleBinding { .. } => None,
        AstNode::Export(inner) => declaration_name(&inner.node),
        AstNode::Record(r) => Some(&r.name),
        AstNode::Enum(e) => Some(&e.name),
        AstNode::Operation(o) => Some(&o.name),
    }
}

// ---- Source-map closure resolution (ADR-013, reference §7/§8) ----
//
// `ResolvedModuleSet` is the single resolver output consumed by both Graph
// and ApplicationContract construction. It stays crate-private; the public
// boundary is `application::resolve`.

#[derive(Debug, Clone, PartialEq, Eq)]
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) struct OriginRef {
    pub logical_module_id: String,
    pub line: usize,
    pub column: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) enum ResolvedDeclarationKind {
    ExistingConcept,
    Record,
    Enum,
    Operation,
}

#[derive(Debug, Clone)]
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) struct ResolvedSymbol {
    pub qualified_id: String,
    pub kind: ResolvedDeclarationKind,
    pub exported: bool,
    pub origin: OriginRef,
    pub module_index: usize,
    pub declaration_index: usize,
}

#[derive(Debug, Clone)]
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) struct ResolvedModule {
    pub logical_id: String,
    pub source_hash: String, // "sha256:<lowercase-hex>"
    pub ast: Ast,
}

#[derive(Debug, Clone, PartialEq, Eq)]
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) struct ImportEdge {
    pub importer: String,
    pub imported: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) struct AliasBinding {
    pub importer: String,
    pub alias: String,
    pub target: String,
}

#[derive(Debug, Clone)]
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) struct ResolvedModuleSet {
    pub modules: Vec<ResolvedModule>,
    pub import_graph: Vec<ImportEdge>,
    pub symbols: IndexMap<String, ResolvedSymbol>,
    pub aliases: Vec<AliasBinding>,
}

/// Ordered, validated in-memory source set keyed by normalized logical path.
#[derive(Debug, Clone)]
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) struct SourceMap(pub(crate) IndexMap<String, String>);

impl SourceMap {
    #[allow(dead_code)]
    /// Parse `sources_json` per reference §7: reject non-object input,
    /// duplicate raw keys, duplicate normalized logical IDs, non-string
    /// values, and invalid logical paths.
    pub(crate) fn parse_json(json: &str) -> Result<Self, Vec<ApplicationDiagnostic>> {
        let pairs = raw_json_object_pairs(json).map_err(|msg| {
            vec![ApplicationDiagnostic::closure_error(
                APP014_UNRESOLVED_SPECIFIER,
                format!("sources_json is not a valid JSON object of strings: {msg}"),
            )]
        })?;
        let mut raw_seen = HashSet::new();
        let mut map = IndexMap::new();
        let mut diags = Vec::new();
        for (raw_key, value) in pairs {
            if !raw_seen.insert(raw_key.clone()) {
                diags.push(ApplicationDiagnostic::closure_error(
                    APP014_SYMBOL_COLLISION,
                    format!("duplicate raw source key '{raw_key}'"),
                ));
                continue;
            }
            let normalized = match normalize_logical_path(&raw_key) {
                Ok(p) => p,
                Err(reason) => {
                    diags.push(ApplicationDiagnostic::closure_error(
                        APP014_UNRESOLVED_SPECIFIER,
                        format!("invalid logical path '{raw_key}': {reason}"),
                    ));
                    continue;
                }
            };
            if map.insert(normalized.clone(), value).is_some() {
                diags.push(ApplicationDiagnostic::closure_error(
                    APP014_SYMBOL_COLLISION,
                    format!("duplicate normalized logical ID '{normalized}'"),
                ));
            }
        }
        if diags.is_empty() {
            Ok(Self(map))
        } else {
            Err(diags)
        }
    }
}

/// Adapt one filesystem entry and its deterministic transitive import closure
/// into the same normalized `SourceMap` consumed by application resolution.
#[cfg(feature = "cli")]
pub(crate) fn source_map_from_filesystem(
    entry_path: &Path,
    entry_source: &str,
    registry: Option<&NamespaceRegistry>,
    default_namespace: Option<&str>,
) -> Result<(String, SourceMap), Vec<ApplicationDiagnostic>> {
    let entry_path = entry_path.canonicalize().map_err(|error| {
        vec![ApplicationDiagnostic::closure_error(
            APP014_UNRESOLVED_SPECIFIER,
            format!(
                "failed to resolve filesystem entry '{}': {error}",
                entry_path.display()
            ),
        )]
    })?;
    let bindings = match registry {
        Some(registry) => registry.resolve_files().map_err(|error| {
            vec![ApplicationDiagnostic::closure_error(
                APP014_UNRESOLVED_SPECIFIER,
                format!("failed to resolve namespace registry files: {error}"),
            )]
        })?,
        None => Vec::new(),
    };
    let mut sources: IndexMap<PathBuf, String> = IndexMap::new();

    #[allow(clippy::too_many_arguments)]
    fn visit(
        path: PathBuf,
        supplied_source: Option<&str>,
        registry: Option<&NamespaceRegistry>,
        default_namespace: Option<&str>,
        bindings: &[NamespaceBinding],
        sources: &mut IndexMap<PathBuf, String>,
        is_entry: bool,
        depth: usize,
    ) -> Result<(), Vec<ApplicationDiagnostic>> {
        if depth > MAX_FILESYSTEM_IMPORT_DEPTH {
            return Err(vec![ApplicationDiagnostic::closure_error(
                APP014_UNRESOLVED_SPECIFIER,
                format!(
                    "filesystem module closure exceeds the maximum import depth of {MAX_FILESYSTEM_IMPORT_DEPTH}"
                ),
            )]);
        }
        let path = path.canonicalize().map_err(|error| {
            vec![ApplicationDiagnostic::closure_error(
                APP014_UNRESOLVED_SPECIFIER,
                format!(
                    "failed to resolve imported module '{}': {error}",
                    path.display()
                ),
            )]
        })?;
        if sources.contains_key(&path) {
            return Ok(());
        }
        if sources.len() >= MAX_FILESYSTEM_MODULES {
            return Err(vec![ApplicationDiagnostic::closure_error(
                APP014_UNRESOLVED_SPECIFIER,
                format!(
                    "filesystem module closure exceeds the maximum of {MAX_FILESYSTEM_MODULES} modules"
                ),
            )]);
        }
        let source = match supplied_source {
            Some(source) => source.to_string(),
            None => fs::read_to_string(&path).map_err(|error| {
                vec![ApplicationDiagnostic::closure_error(
                    APP014_UNRESOLVED_SPECIFIER,
                    format!(
                        "failed to read imported module '{}': {error}",
                        path.display()
                    ),
                )]
            })?,
        };
        let ast = parse_source(&source).map_err(|error| {
            let mut diagnostic = ApplicationDiagnostic::new(
                ApplicationDiagnosticCode::App015,
                format!("module '{}' failed to parse: {error}", path.display()),
            )
            .with_document_kind("authored_source");
            diagnostic.context.logical_module_id = Some(path.display().to_string());
            vec![diagnostic]
        })?;

        // Insert before recursion so cycles terminate here and are diagnosed by
        // the canonical resolver from the complete collected source set.
        let effective_source = if ast.metadata.namespace.is_some() {
            source
        } else {
            let namespace = registry
                .and_then(|registry| registry.namespace_for(&path))
                .or_else(|| is_entry.then_some(default_namespace).flatten())
                .or_else(|| is_entry.then_some("default"))
                .ok_or_else(|| {
                    vec![ApplicationDiagnostic::closure_error(
                        APP014_UNRESOLVED_SPECIFIER,
                        format!(
                            "imported module '{}' has no declared or registry namespace",
                            path.display()
                        ),
                    )]
                })?;
            let namespace = serde_json::to_string(namespace)
                .expect("serializing a Rust string as a SEA string literal cannot fail");
            format!("@namespace {namespace}\n{source}")
        };
        sources.insert(path.clone(), effective_source);

        for import in &ast.metadata.imports {
            let specifier = import.from_module.as_str();
            if specifier == "std" || specifier.starts_with("std:") {
                continue;
            }
            let dependency = if specifier.starts_with("./") || specifier.starts_with("../") {
                path.parent()
                    .unwrap_or_else(|| Path::new("."))
                    .join(specifier)
            } else {
                let mut matches = bindings
                    .iter()
                    .filter(|binding| binding.namespace == specifier);
                let Some(first) = matches.next() else {
                    return Err(vec![ApplicationDiagnostic::closure_error(
                        APP014_UNRESOLVED_SPECIFIER,
                        format!(
                            "namespace import '{specifier}' in '{}' matches no registry module",
                            path.display()
                        ),
                    )]);
                };
                // `resolve_files` is path-sorted; choosing its first exact
                // namespace binding preserves the legacy resolver's deterministic
                // selection while the canonical resolver owns symbol semantics.
                first.path.clone()
            };
            visit(
                dependency,
                None,
                registry,
                default_namespace,
                bindings,
                sources,
                false,
                depth + 1,
            )?;
        }
        Ok(())
    }

    visit(
        entry_path.clone(),
        Some(entry_source),
        registry,
        default_namespace,
        &bindings,
        &mut sources,
        true,
        0,
    )?;

    let mut root = entry_path
        .parent()
        .unwrap_or(entry_path.as_path())
        .to_path_buf();
    while sources.keys().any(|path| !path.starts_with(&root)) {
        if !root.pop() {
            return Err(vec![ApplicationDiagnostic::closure_error(
                APP014_UNRESOLVED_SPECIFIER,
                "filesystem module closure has no common root".to_string(),
            )]);
        }
    }

    let mut ordered: Vec<(String, String)> = sources
        .into_iter()
        .map(|(path, source)| {
            let logical = path
                .strip_prefix(&root)
                .expect("common root contains every collected module")
                .to_string_lossy()
                .replace('\\', "/");
            (logical, source)
        })
        .collect();
    ordered.sort_by(|left, right| left.0.cmp(&right.0));
    let entry_logical = entry_path
        .strip_prefix(&root)
        .expect("common root contains the entry module")
        .to_string_lossy()
        .replace('\\', "/");
    Ok((entry_logical, SourceMap(ordered.into_iter().collect())))
}

/// Deserialize a JSON object into ordered (key, string-value) pairs without
/// silently collapsing duplicate keys the way `serde_json` maps do.
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
fn raw_json_object_pairs(json: &str) -> Result<Vec<(String, String)>, String> {
    struct Pairs;
    impl<'de> serde::de::Visitor<'de> for Pairs {
        type Value = Vec<(String, String)>;
        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a JSON object mapping logical paths to source strings")
        }
        fn visit_map<A: serde::de::MapAccess<'de>>(
            self,
            mut map: A,
        ) -> Result<Self::Value, A::Error> {
            let mut out = Vec::new();
            while let Some((k, v)) = map.next_entry::<String, serde_json::Value>()? {
                match v {
                    serde_json::Value::String(s) => out.push((k, s)),
                    other => {
                        return Err(serde::de::Error::custom(format!(
                            "source '{k}' must be a string, found {other}"
                        )))
                    }
                }
            }
            Ok(out)
        }
    }
    let mut de = serde_json::Deserializer::from_str(json);
    let pairs =
        serde::de::Deserializer::deserialize_map(&mut de, Pairs).map_err(|e| e.to_string())?;
    de.end().map_err(|e| e.to_string())?;
    Ok(pairs)
}

/// Reference §7 logical-path algorithm: NFC, `/` separators, case preserved,
/// `.` segments dropped, `..` resolved without escaping the root; `\`,
/// absolute paths, and empty segments rejected.
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
fn normalize_logical_path(raw: &str) -> Result<String, String> {
    let path: String = raw.nfc().collect();
    if path.is_empty() {
        return Err("empty path".to_string());
    }
    if path.contains('\\') {
        return Err("backslash separators are not allowed".to_string());
    }
    if path.starts_with('/') {
        return Err("absolute paths are not allowed".to_string());
    }
    let mut segments: Vec<&str> = Vec::new();
    for segment in path.split('/') {
        match segment {
            "" => return Err("empty path segment".to_string()),
            "." => {}
            ".." => {
                if segments.pop().is_none() {
                    return Err("path escapes the source-map root".to_string());
                }
            }
            s => segments.push(s),
        }
    }
    if segments.is_empty() {
        return Err("path resolves to the source-map root".to_string());
    }
    Ok(segments.join("/"))
}

/// The logical directory of a module ID ("flagship/a.sea" -> "flagship").
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
fn logical_dir(logical_id: &str) -> &str {
    logical_id.rfind('/').map_or("", |i| &logical_id[..i])
}

// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
fn source_hash(source: &str) -> String {
    format!("sha256:{:x}", Sha256::digest(source.as_bytes()))
}

// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
fn declaration_kind(node: &AstNode) -> ResolvedDeclarationKind {
    match node {
        AstNode::Export(inner) => declaration_kind(&inner.node),
        AstNode::Record(_) => ResolvedDeclarationKind::Record,
        AstNode::Enum(_) => ResolvedDeclarationKind::Enum,
        AstNode::Operation(_) => ResolvedDeclarationKind::Operation,
        _ => ResolvedDeclarationKind::ExistingConcept,
    }
}

// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
fn kind_slug(node: &AstNode) -> &'static str {
    match node {
        AstNode::Export(inner) => kind_slug(&inner.node),
        AstNode::Entity { .. } => "entity",
        AstNode::Resource { .. } => "resource",
        AstNode::Flow { .. } => "flow",
        AstNode::Pattern { .. } => "pattern",
        AstNode::Role { .. } => "role",
        AstNode::Relation { .. } => "relation",
        AstNode::Dimension { .. } => "dimension",
        AstNode::UnitDeclaration { .. } => "unit",
        AstNode::Policy { .. } => "policy",
        AstNode::Instance { .. } => "instance",
        AstNode::ConceptChange { .. } => "concept_change",
        AstNode::Metric { .. } => "metric",
        AstNode::MappingDecl { .. } => "mapping",
        AstNode::ProjectionDecl { .. } => "projection",
        AstNode::Cell { .. } => "cell",
        AstNode::SystemDependency { .. } => "system_dependency",
        AstNode::Runtime { .. } => "runtime",
        AstNode::Tool { .. } => "tool",
        AstNode::DependencySet { .. } => "dependency_set",
        AstNode::Service { .. } => "service",
        AstNode::Mount { .. } => "mount",
        AstNode::Endpoint { .. } => "endpoint",
        AstNode::NetworkFlow { .. } => "network_flow",
        AstNode::Credential { .. } => "credential",
        AstNode::RoleBinding { .. } => "role_binding",
        AstNode::Record(_) => "record",
        AstNode::Enum(_) => "enum",
        AstNode::Operation(_) => "operation",
    }
}

// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
fn builtin_std_source(specifier: &str) -> Option<&'static str> {
    match specifier {
        "std" | "std:core" => Some(include_str!("../../std/core.sea")),
        "std:http" => Some(include_str!("../../std/http.sea")),
        "std:aws" => Some(include_str!("../../std/aws.sea")),
        _ => None,
    }
}

/// Resolve one deterministic semantic closure from an in-memory source map
/// (reference §7). All diagnostics are APP014 with a closed reason value,
/// except parse failures which are APP015 (the module fails its language
/// schema before closure identity exists).
// ponytail: consumed by application resolution in Task 7.
#[allow(dead_code)]
pub(crate) fn resolve_source_map(
    entry_logical_path: &str,
    sources: &SourceMap,
) -> Result<ResolvedModuleSet, Vec<ApplicationDiagnostic>> {
    let mut diags: Vec<ApplicationDiagnostic> = Vec::new();

    // Parse every module up front; the set is closed and namespace imports
    // need every module's declared namespace anyway.
    let mut parsed: IndexMap<String, (String, Ast)> = IndexMap::new();
    for (logical_id, source) in &sources.0 {
        match parse_source(source) {
            Ok(ast) => {
                parsed.insert(logical_id.clone(), (source.clone(), ast));
            }
            Err(e) => {
                let mut d = ApplicationDiagnostic::new(
                    ApplicationDiagnosticCode::App015,
                    format!("module '{logical_id}' failed to parse: {e}"),
                )
                .with_document_kind("authored_source");
                d.context.logical_module_id = Some(logical_id.clone());
                diags.push(d);
            }
        }
    }
    if !diags.is_empty() {
        return Err(diags);
    }

    let entry = normalize_logical_path(entry_logical_path).map_err(|reason| {
        vec![ApplicationDiagnostic::closure_error(
            APP014_UNRESOLVED_SPECIFIER,
            format!("invalid entry logical path '{entry_logical_path}': {reason}"),
        )]
    })?;
    if !parsed.contains_key(&entry) {
        return Err(vec![ApplicationDiagnostic::closure_error(
            APP014_UNRESOLVED_SPECIFIER,
            format!("entry '{entry}' is not present in sources_json"),
        )]);
    }

    // DFS closure walk from the entry.
    let mut std_modules: IndexMap<String, (String, Ast)> = IndexMap::new();
    let mut reachable: HashSet<String> = HashSet::new();
    let mut visiting: Vec<String> = Vec::new();
    let mut import_graph: Vec<ImportEdge> = Vec::new();
    let mut aliases: Vec<AliasBinding> = Vec::new();

    #[allow(clippy::too_many_arguments)]
    fn visit(
        logical_id: &str,
        parsed: &IndexMap<String, (String, Ast)>,
        std_modules: &mut IndexMap<String, (String, Ast)>,
        reachable: &mut HashSet<String>,
        visiting: &mut Vec<String>,
        import_graph: &mut Vec<ImportEdge>,
        aliases: &mut Vec<AliasBinding>,
        diags: &mut Vec<ApplicationDiagnostic>,
    ) {
        if visiting.iter().any(|m| m == logical_id) {
            let cycle: Vec<&str> = visiting
                .iter()
                .map(String::as_str)
                .chain(std::iter::once(logical_id))
                .collect();
            diags.push(ApplicationDiagnostic::closure_error(
                APP014_IMPORT_CYCLE,
                format!("import cycle: {}", cycle.join(" -> ")),
            ));
            return;
        }
        if reachable.contains(logical_id) {
            return;
        }
        reachable.insert(logical_id.to_string());
        let ast = match parsed
            .get(logical_id)
            .or_else(|| std_modules.get(logical_id))
        {
            Some((_, ast)) => ast.clone(),
            None => return,
        };
        visiting.push(logical_id.to_string());
        for import in &ast.metadata.imports {
            let spec = &import.from_module;
            let target: Option<String> = if spec.starts_with("./") || spec.starts_with("../") {
                let joined = if logical_dir(logical_id).is_empty() {
                    spec.clone()
                } else {
                    format!("{}/{}", logical_dir(logical_id), spec)
                };
                match normalize_logical_path(&joined) {
                    Ok(p) if parsed.contains_key(&p) => Some(p),
                    Ok(p) => {
                        diags.push(ApplicationDiagnostic::closure_error(
                            APP014_UNRESOLVED_SPECIFIER,
                            format!(
                                "import '{spec}' in '{logical_id}' resolves to '{p}', which is not in sources_json"
                            ),
                        ));
                        None
                    }
                    Err(reason) => {
                        diags.push(ApplicationDiagnostic::closure_error(
                            APP014_UNRESOLVED_SPECIFIER,
                            format!("import '{spec}' in '{logical_id}' is invalid: {reason}"),
                        ));
                        None
                    }
                }
            } else if spec == "std" || spec.starts_with("std:") {
                match builtin_std_source(spec) {
                    Some(source) => {
                        if !std_modules.contains_key(spec) {
                            // std sources are maintained in-repo and always parse.
                            let ast = parse_source(source).expect("builtin std module parses");
                            std_modules.insert(spec.clone(), (source.to_string(), ast));
                        }
                        Some(spec.clone())
                    }
                    None => {
                        diags.push(ApplicationDiagnostic::closure_error(
                            APP014_UNRESOLVED_SPECIFIER,
                            format!("unknown std module '{spec}' imported by '{logical_id}'"),
                        ));
                        None
                    }
                }
            } else {
                // Namespace import: exactly one source-map module whose declared
                // namespace equals the specifier's exact bytes.
                let matches: Vec<&String> = parsed
                    .iter()
                    .filter(|(_, (_, ast))| ast.metadata.namespace.as_deref() == Some(spec))
                    .map(|(id, _)| id)
                    .collect();
                match matches.as_slice() {
                    [one] => Some((*one).clone()),
                    [] => {
                        diags.push(ApplicationDiagnostic::closure_error(
                            APP014_UNRESOLVED_SPECIFIER,
                            format!(
                                "namespace import '{spec}' in '{logical_id}' matches no source-map module"
                            ),
                        ));
                        None
                    }
                    _ => {
                        diags.push(ApplicationDiagnostic::closure_error(
                            APP014_UNRESOLVED_SPECIFIER,
                            format!(
                                "namespace import '{spec}' in '{logical_id}' matches more than one source-map module"
                            ),
                        ));
                        None
                    }
                }
            };
            let Some(target) = target else { continue };
            import_graph.push(ImportEdge {
                importer: logical_id.to_string(),
                imported: target.clone(),
            });
            if let ImportSpecifier::Wildcard(alias) = &import.specifier {
                aliases.push(AliasBinding {
                    importer: logical_id.to_string(),
                    alias: alias.clone(),
                    target: target.clone(),
                });
            }
            visit(
                &target,
                parsed,
                std_modules,
                reachable,
                visiting,
                import_graph,
                aliases,
                diags,
            );
            // Named import visibility against the resolved target.
            if let ImportSpecifier::Named(items) = &import.specifier {
                if let Some((_, target_ast)) =
                    parsed.get(&target).or_else(|| std_modules.get(&target))
                {
                    let exports = collect_exports(target_ast);
                    let declared: HashSet<&str> = target_ast
                        .declarations
                        .iter()
                        .filter_map(|d| declaration_name(&d.node))
                        .collect();
                    for item in items {
                        if exports.contains(&item.name) {
                            continue;
                        }
                        if declared.contains(item.name.as_str()) {
                            diags.push(ApplicationDiagnostic::closure_error(
                                APP014_NOT_EXPORTED,
                                format!("'{}' exists in '{target}' but is not exported", item.name),
                            ));
                        } else {
                            diags.push(ApplicationDiagnostic::closure_error(
                                APP014_UNRESOLVED_ALIAS,
                                format!(
                                    "named import '{}' in '{logical_id}' binds no declaration in '{target}'",
                                    item.name
                                ),
                            ));
                        }
                    }
                }
            }
        }
        visiting.pop();
    }

    visit(
        &entry,
        &parsed,
        &mut std_modules,
        &mut reachable,
        &mut visiting,
        &mut import_graph,
        &mut aliases,
        &mut diags,
    );

    if !diags.is_empty() {
        crate::application::diagnostic::sort_diagnostics(&mut diags);
        return Err(diags);
    }

    // Deterministic module order: logical ID, bytewise ascending.
    let mut logical_ids: Vec<String> = reachable.into_iter().collect();
    logical_ids.sort();
    let modules: Vec<ResolvedModule> = logical_ids
        .iter()
        .map(|id| {
            let (source, ast) = parsed
                .get(id)
                .or_else(|| std_modules.get(id))
                .expect("reachable module was parsed");
            ResolvedModule {
                logical_id: id.clone(),
                source_hash: source_hash(source),
                ast: ast.clone(),
            }
        })
        .collect();

    import_graph.sort_by(|a, b| (&a.importer, &a.imported).cmp(&(&b.importer, &b.imported)));
    import_graph.dedup();
    aliases.sort_by(|a, b| (&a.importer, &a.alias).cmp(&(&b.importer, &b.alias)));

    // One qualified symbol table across the closure. Application declaration
    // names are NFC-normalized; existing concept names keep exact bytes.
    let mut symbols: IndexMap<String, ResolvedSymbol> = IndexMap::new();
    for (module_index, module) in modules.iter().enumerate() {
        let namespace = module
            .ast
            .metadata
            .namespace
            .clone()
            // ponytail: modules without @namespace use their logical ID as the
            // qualification root; the reference leaves this case to APP014 later.
            .unwrap_or_else(|| module.logical_id.clone());
        let exports = collect_exports(&module.ast);
        for (declaration_index, decl) in module.ast.declarations.iter().enumerate() {
            let Some(name) = declaration_name(&decl.node) else {
                continue;
            };
            // Flows are occurrence-identified (reference §8): equal flows are
            // legal repetitions, not qualified-ID collisions.
            let inner = match &decl.node {
                crate::parser::ast::AstNode::Export(inner) => &inner.node,
                other => other,
            };
            if matches!(inner, crate::parser::ast::AstNode::Flow { .. }) {
                continue;
            }
            let kind = declaration_kind(&decl.node);
            let name = if kind == ResolvedDeclarationKind::ExistingConcept {
                name.to_string()
            } else {
                name.nfc().collect()
            };
            let qualified_id = format!("{namespace}.{}.{name}", kind_slug(&decl.node));
            let symbol = ResolvedSymbol {
                qualified_id: qualified_id.clone(),
                kind,
                exported: exports.contains(name.as_str()),
                origin: OriginRef {
                    logical_module_id: module.logical_id.clone(),
                    line: decl.line,
                    column: decl.column,
                },
                module_index,
                declaration_index,
            };
            if let Some(existing) = symbols.get(&qualified_id) {
                diags.push(ApplicationDiagnostic::closure_error(
                    APP014_SYMBOL_COLLISION,
                    format!(
                        "distinct declarations share qualified ID '{qualified_id}' ('{}' line {} and '{}' line {})",
                        existing.origin.logical_module_id,
                        existing.origin.line,
                        module.logical_id,
                        decl.line
                    ),
                ));
            } else {
                symbols.insert(qualified_id, symbol);
            }
        }
    }

    if diags.is_empty() {
        Ok(ResolvedModuleSet {
            modules,
            import_graph,
            symbols,
            aliases,
        })
    } else {
        crate::application::diagnostic::sort_diagnostics(&mut diags);
        Err(diags)
    }
}

pub fn parse_with_registry(
    path: &Path,
    registry: &NamespaceRegistry,
) -> ParseResult<(Ast, ParseOptions)> {
    let content = fs::read_to_string(path).map_err(|e| {
        ParseError::GrammarError(format!("Failed to read {}: {}", path.display(), e))
    })?;

    // `ParseOptions` are constructed here to be returned to the caller,
    // even though `parse_source` currently doesn't use them. Initialize
    // fields directly in the `ParseOptions` construction to avoid
    // field reassignment lint from clippy (clippy::field-reassign-with-default).
    let options = ParseOptions {
        namespace_registry: Some(registry.clone()),
        entry_path: Some(path.to_path_buf()),
        ..Default::default()
    };

    let ast = parse_source(&content)?;
    Ok((ast, options))
}

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

    fn resolve(
        entry: &str,
        sources_json: &str,
    ) -> Result<ResolvedModuleSet, Vec<ApplicationDiagnostic>> {
        let sources = SourceMap::parse_json(sources_json)?;
        resolve_source_map(entry, &sources)
    }

    fn reason(err: &[ApplicationDiagnostic]) -> &str {
        err[0].context.reason.as_deref().unwrap()
    }

    #[test]
    fn resolves_named_relative_import_into_one_symbol_table() {
        let sources = serde_json::json!({
            "flagship/command-write.sea": include_str!(
                "../../../fixtures/application_generation/flagship/command-write.sea"),
            "flagship/query-read.sea": include_str!(
                "../../../fixtures/application_generation/flagship/query-read.sea"),
        })
        .to_string();
        let set = resolve("flagship/query-read.sea", &sources).unwrap();
        assert_eq!(
            set.modules
                .iter()
                .map(|m| m.logical_id.as_str())
                .collect::<Vec<_>>(),
            ["flagship/command-write.sea", "flagship/query-read.sea"]
        );
        assert!(set.symbols.contains_key("flagship.orders.entity.Order"));
        assert!(set
            .symbols
            .contains_key("flagship.orders.record.PlaceOrderInput"));
        assert!(set
            .symbols
            .contains_key("flagship.orders.operation.get_order_status"));
        assert_eq!(set.import_graph.len(), 1);
        assert!(set
            .modules
            .iter()
            .all(|m| m.source_hash.starts_with("sha256:")));
    }

    #[test]
    fn relative_import_escaping_root_is_unresolved_specifier() {
        let sources = serde_json::json!({
            "a.sea": "@namespace \"ns.a\"\nimport { X } from \"../outside.sea\"\n",
        })
        .to_string();
        let err = resolve("a.sea", &sources).unwrap_err();
        assert_eq!(reason(&err), "unresolved_specifier");
        assert!(err[0].message.contains("escapes"));
    }

    #[test]
    fn duplicate_normalized_source_key_is_rejected() {
        let sources = r#"{"a/./x.sea": "@namespace \"n\"", "a/x.sea": "@namespace \"n\""}"#;
        let err = SourceMap::parse_json(sources).unwrap_err();
        assert_eq!(reason(&err), "symbol_collision");
        assert!(err[0].message.contains("duplicate normalized logical ID"));
    }

    #[test]
    fn duplicate_raw_source_key_is_rejected() {
        let sources = r#"{"a.sea": "x", "a.sea": "y"}"#;
        let err = SourceMap::parse_json(sources).unwrap_err();
        assert_eq!(reason(&err), "symbol_collision");
        assert!(err[0].message.contains("duplicate raw source key"));
    }

    #[test]
    fn named_import_of_unexported_symbol_is_not_exported() {
        let sources = serde_json::json!({
            "a.sea": "@namespace \"ns.a\"\nimport { Hidden } from \"./b.sea\"\n",
            "b.sea": "@namespace \"ns.b\"\nrecord Hidden {\n    x: string\n}\n",
        })
        .to_string();
        let err = resolve("a.sea", &sources).unwrap_err();
        assert_eq!(reason(&err), "not_exported");
    }

    #[test]
    fn named_import_binding_nothing_is_unresolved_alias() {
        let sources = serde_json::json!({
            "a.sea": "@namespace \"ns.a\"\nimport { Ghost } from \"./b.sea\"\n",
            "b.sea": "@namespace \"ns.b\"\nexport record Real {\n    x: string\n}\n",
        })
        .to_string();
        let err = resolve("a.sea", &sources).unwrap_err();
        assert_eq!(reason(&err), "unresolved_alias");
    }

    #[test]
    fn wildcard_import_records_alias_binding() {
        let sources = serde_json::json!({
            "a.sea": "@namespace \"ns.a\"\nimport * as b from \"./b.sea\"\n",
            "b.sea": "@namespace \"ns.b\"\nexport record Real {\n    x: string\n}\n",
        })
        .to_string();
        let set = resolve("a.sea", &sources).unwrap();
        assert_eq!(
            set.aliases,
            vec![AliasBinding {
                importer: "a.sea".to_string(),
                alias: "b".to_string(),
                target: "b.sea".to_string(),
            }]
        );
    }

    #[test]
    fn unresolved_relative_specifier_is_reported() {
        let sources = serde_json::json!({
            "a.sea": "@namespace \"ns.a\"\nimport { X } from \"./missing.sea\"\n",
        })
        .to_string();
        let err = resolve("a.sea", &sources).unwrap_err();
        assert_eq!(reason(&err), "unresolved_specifier");
    }

    #[test]
    fn import_cycle_is_reported() {
        let sources = serde_json::json!({
            "a.sea": "@namespace \"ns.a\"\nimport * as b from \"./b.sea\"\n",
            "b.sea": "@namespace \"ns.b\"\nimport * as a from \"./a.sea\"\n",
        })
        .to_string();
        let err = resolve("a.sea", &sources).unwrap_err();
        assert_eq!(reason(&err), "import_cycle");
    }

    #[test]
    fn distinct_declarations_with_one_qualified_id_collide() {
        let sources = serde_json::json!({
            "a.sea": "@namespace \"ns.shared\"\nimport * as b from \"./b.sea\"\nexport record Same {\n    x: string\n}\n",
            "b.sea": "@namespace \"ns.shared\"\nexport record Same {\n    x: string\n}\n",
        })
        .to_string();
        let err = resolve("a.sea", &sources).unwrap_err();
        assert_eq!(reason(&err), "symbol_collision");
    }

    #[test]
    fn diamond_origin_collapses_to_one_symbol() {
        let sources = serde_json::json!({
            "a.sea": "@namespace \"ns.a\"\nimport * as b from \"./b.sea\"\nimport * as c from \"./c.sea\"\n",
            "b.sea": "@namespace \"ns.b\"\nimport { Shared } from \"./d.sea\"\n",
            "c.sea": "@namespace \"ns.c\"\nimport { Shared } from \"./d.sea\"\n",
            "d.sea": "@namespace \"ns.d\"\nexport record Shared {\n    x: string\n}\n",
        })
        .to_string();
        let set = resolve("a.sea", &sources).unwrap();
        assert_eq!(
            set.symbols
                .values()
                .filter(|s| s.qualified_id.ends_with(".Shared"))
                .count(),
            1
        );
        assert_eq!(set.modules.len(), 4);
    }

    #[test]
    fn entry_missing_from_sources_is_unresolved_specifier() {
        let err = resolve("missing.sea", r#"{"a.sea": "@namespace \"n\""}"#).unwrap_err();
        assert_eq!(reason(&err), "unresolved_specifier");
    }
}