harn-modules 0.7.26

Cross-file module graph and import resolution utilities for Harn
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
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};

use harn_lexer::Span;
use harn_parser::{BindingPattern, Node, Parser, SNode};
use serde::Deserialize;

mod stdlib;

/// Kind of symbol that can be exported by a module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DefKind {
    Function,
    Pipeline,
    Tool,
    Skill,
    Struct,
    Enum,
    Interface,
    Type,
    Variable,
    Parameter,
}

/// A resolved definition site within a module.
#[derive(Debug, Clone)]
pub struct DefSite {
    pub name: String,
    pub file: PathBuf,
    pub kind: DefKind,
    pub span: Span,
}

/// Wildcard import resolution status for a single importing module.
#[derive(Debug, Clone)]
pub enum WildcardResolution {
    /// Resolved all wildcard imports and can expose wildcard exports.
    Resolved(HashSet<String>),
    /// At least one wildcard import could not be resolved.
    Unknown,
}

/// Parsed information for a set of module files.
#[derive(Debug, Default)]
pub struct ModuleGraph {
    modules: HashMap<PathBuf, ModuleInfo>,
}

#[derive(Debug, Default)]
struct ModuleInfo {
    /// All declarations visible in this module (for local symbol lookup and
    /// go-to-definition resolution).
    declarations: HashMap<String, DefSite>,
    /// Public exports exposed by wildcard imports.
    exports: HashSet<String>,
    /// Names introduced by selective imports across this module.
    selective_import_names: HashSet<String>,
    /// Import references encountered in this file.
    imports: Vec<ImportRef>,
    /// True when at least one wildcard import could not be resolved.
    has_unresolved_wildcard_import: bool,
    /// True when at least one selective import could not be resolved
    /// (importing file path missing). Prevents `imported_names_for_file`
    /// from returning a partial answer when any import is broken.
    has_unresolved_selective_import: bool,
    /// Every `fn` declaration at module scope, used to implement the
    /// fallback "no `pub fn` → export everything" rule that matches the
    /// runtime loader's behavior.
    fn_names: Vec<String>,
    /// True when at least one `pub fn` appeared at module scope.
    has_pub_fn: bool,
    /// Top-level type-like declarations that can be imported into a caller's
    /// static type environment.
    type_declarations: Vec<SNode>,
}

#[derive(Debug, Clone)]
struct ImportRef {
    path: Option<PathBuf>,
    selective_names: Option<HashSet<String>>,
}

#[derive(Debug, Default, Deserialize)]
struct PackageManifest {
    #[serde(default)]
    exports: HashMap<String, String>,
}

/// Build a module graph from a set of files.
///
/// Files referenced via `import` statements are loaded recursively so the
/// graph contains every module reachable from the seed set. Cycles and
/// already-loaded files are skipped via a visited set.
pub fn build(files: &[PathBuf]) -> ModuleGraph {
    let mut modules: HashMap<PathBuf, ModuleInfo> = HashMap::new();
    let mut seen: HashSet<PathBuf> = HashSet::new();
    let mut queue: VecDeque<PathBuf> = VecDeque::new();
    for file in files {
        let canonical = normalize_path(file);
        if seen.insert(canonical.clone()) {
            queue.push_back(canonical);
        }
    }
    while let Some(path) = queue.pop_front() {
        if modules.contains_key(&path) {
            continue;
        }
        let module = load_module(&path);
        // Enqueue resolved import targets so the whole reachable graph is
        // discovered without the caller having to pre-walk imports.
        //
        // `resolve_import_path` returns paths as `base.join(import)` —
        // i.e. with `..` segments preserved rather than collapsed. If we
        // dedupe on those raw forms, two files that import each other
        // across sibling dirs (`lib/context/` ↔ `lib/runtime/`) produce a
        // different path spelling on every cycle — `.../context/../runtime/`,
        // then `.../context/../runtime/../context/`, and so on — each of
        // which is treated as a new file. The walk only terminates when
        // `path.exists()` starts failing at the filesystem's `PATH_MAX`,
        // which is 1024 on macOS but 4096 on Linux. Linux therefore
        // re-parses the same handful of files thousands of times, balloons
        // RSS into the multi-GB range, and gets SIGKILL'd by CI runners.
        // Canonicalize once here so `seen` dedupes by the underlying file,
        // not by its path spelling.
        for import in &module.imports {
            if let Some(import_path) = &import.path {
                let canonical = normalize_path(import_path);
                if seen.insert(canonical.clone()) {
                    queue.push_back(canonical);
                }
            }
        }
        modules.insert(path, module);
    }
    ModuleGraph { modules }
}

/// Resolve an import string relative to the importing file.
///
/// Returns the path as-constructed (not canonicalized) so callers that
/// compare against their own `PathBuf::join` result get matching values.
/// The module graph canonicalizes internally via `normalize_path` when
/// keying modules, so call-site canonicalization is not required for
/// dedup.
///
/// `std/<module>` imports resolve to a virtual path (`<std>/<module>`)
/// backed by the embedded stdlib sources in [`stdlib`]. This lets the
/// module graph model stdlib symbols even though they have no on-disk
/// location.
pub fn resolve_import_path(current_file: &Path, import_path: &str) -> Option<PathBuf> {
    if let Some(module) = import_path.strip_prefix("std/") {
        if stdlib::get_stdlib_source(module).is_some() {
            return Some(stdlib::stdlib_virtual_path(module));
        }
        return None;
    }

    let base = current_file.parent().unwrap_or(Path::new("."));
    let mut file_path = base.join(import_path);
    if !file_path.exists() && file_path.extension().is_none() {
        file_path.set_extension("harn");
    }
    if file_path.exists() {
        return Some(file_path);
    }

    if let Some(path) = resolve_package_import(base, import_path) {
        return Some(path);
    }

    None
}

fn resolve_package_import(base: &Path, import_path: &str) -> Option<PathBuf> {
    for anchor in base.ancestors() {
        let packages_root = anchor.join(".harn/packages");
        if !packages_root.is_dir() {
            if anchor.join(".git").exists() {
                break;
            }
            continue;
        }
        if let Some(path) = resolve_from_packages_root(&packages_root, import_path) {
            return Some(path);
        }
        if anchor.join(".git").exists() {
            break;
        }
    }
    None
}

fn resolve_from_packages_root(packages_root: &Path, import_path: &str) -> Option<PathBuf> {
    let pkg_path = packages_root.join(import_path);
    if let Some(path) = finalize_package_target(&pkg_path) {
        return Some(path);
    }

    let (package_name, export_name) = import_path.split_once('/')?;
    let manifest_path = packages_root.join(package_name).join("harn.toml");
    let manifest = read_package_manifest(&manifest_path)?;
    let rel_path = manifest.exports.get(export_name)?;
    finalize_package_target(&packages_root.join(package_name).join(rel_path))
}

fn read_package_manifest(path: &Path) -> Option<PackageManifest> {
    let content = std::fs::read_to_string(path).ok()?;
    toml::from_str::<PackageManifest>(&content).ok()
}

fn finalize_package_target(path: &Path) -> Option<PathBuf> {
    if path.is_dir() {
        let lib = path.join("lib.harn");
        if lib.exists() {
            return Some(lib);
        }
        return Some(path.to_path_buf());
    }
    if path.exists() {
        return Some(path.to_path_buf());
    }
    if path.extension().is_none() {
        let mut with_ext = path.to_path_buf();
        with_ext.set_extension("harn");
        if with_ext.exists() {
            return Some(with_ext);
        }
    }
    None
}

impl ModuleGraph {
    /// Collect every name used in selective imports from all files.
    pub fn all_selective_import_names(&self) -> HashSet<&str> {
        let mut names = HashSet::new();
        for module in self.modules.values() {
            for name in &module.selective_import_names {
                names.insert(name.as_str());
            }
        }
        names
    }

    /// Resolve wildcard imports for `file`.
    ///
    /// Returns `Unknown` when any wildcard import cannot be resolved, because
    /// callers should conservatively disable wildcard-import-sensitive checks.
    pub fn wildcard_exports_for(&self, file: &Path) -> WildcardResolution {
        let file = normalize_path(file);
        let Some(module) = self.modules.get(&file) else {
            return WildcardResolution::Unknown;
        };
        if module.has_unresolved_wildcard_import {
            return WildcardResolution::Unknown;
        }

        let mut names = HashSet::new();
        for import in module
            .imports
            .iter()
            .filter(|import| import.selective_names.is_none())
        {
            let Some(import_path) = &import.path else {
                return WildcardResolution::Unknown;
            };
            let imported = self.modules.get(import_path).or_else(|| {
                let normalized = normalize_path(import_path);
                self.modules.get(&normalized)
            });
            let Some(imported) = imported else {
                return WildcardResolution::Unknown;
            };
            names.extend(imported.exports.iter().cloned());
        }
        WildcardResolution::Resolved(names)
    }

    /// Collect every statically callable/referenceable name introduced into
    /// `file` by its imports.
    ///
    /// Returns `Some` only when **every** import (wildcard or selective) in
    /// `file` is fully resolvable via the graph. Returns `None` when any
    /// import is unresolved, so callers can fall back to conservative
    /// behavior instead of emitting spurious "undefined name" errors.
    ///
    /// The returned set contains:
    /// - all public exports from wildcard-imported modules, and
    /// - selectively imported names that exist as declarations in their
    ///   target module (unresolvable selective names are still included,
    ///   but only if the target file itself resolved — if the file failed
    ///   to parse, the caller will see `None`).
    pub fn imported_names_for_file(&self, file: &Path) -> Option<HashSet<String>> {
        let file = normalize_path(file);
        let module = self.modules.get(&file)?;
        if module.has_unresolved_wildcard_import || module.has_unresolved_selective_import {
            return None;
        }

        let mut names = HashSet::new();
        for import in &module.imports {
            let import_path = import.path.as_ref()?;
            let imported = self
                .modules
                .get(import_path)
                .or_else(|| self.modules.get(&normalize_path(import_path)))?;
            match &import.selective_names {
                None => {
                    names.extend(imported.exports.iter().cloned());
                }
                Some(selective) => {
                    for name in selective {
                        if imported.declarations.contains_key(name) {
                            names.insert(name.clone());
                        }
                    }
                }
            }
        }
        Some(names)
    }

    /// Collect type / struct / enum / interface declarations made visible to
    /// `file` by its imports. Returns `None` when any import is unresolved so
    /// callers can fall back to conservative behavior.
    pub fn imported_type_declarations_for_file(&self, file: &Path) -> Option<Vec<SNode>> {
        let file = normalize_path(file);
        let module = self.modules.get(&file)?;
        if module.has_unresolved_wildcard_import || module.has_unresolved_selective_import {
            return None;
        }

        let mut decls = Vec::new();
        for import in &module.imports {
            let import_path = import.path.as_ref()?;
            let imported = self
                .modules
                .get(import_path)
                .or_else(|| self.modules.get(&normalize_path(import_path)))?;
            match &import.selective_names {
                None => {
                    for decl in &imported.type_declarations {
                        if let Some(name) = type_decl_name(decl) {
                            if imported.exports.contains(name) {
                                decls.push(decl.clone());
                            }
                        }
                    }
                }
                Some(selective) => {
                    for decl in &imported.type_declarations {
                        if let Some(name) = type_decl_name(decl) {
                            if selective.contains(name) {
                                decls.push(decl.clone());
                            }
                        }
                    }
                }
            }
        }
        Some(decls)
    }

    /// Find the definition of `name` visible from `file`.
    pub fn definition_of(&self, file: &Path, name: &str) -> Option<DefSite> {
        let file = normalize_path(file);
        let current = self.modules.get(&file)?;

        if let Some(local) = current.declarations.get(name) {
            return Some(local.clone());
        }

        for import in &current.imports {
            if let Some(selective_names) = &import.selective_names {
                if !selective_names.contains(name) {
                    continue;
                }
            } else {
                continue;
            }

            if let Some(path) = &import.path {
                if let Some(symbol) = self
                    .modules
                    .get(path)
                    .or_else(|| self.modules.get(&normalize_path(path)))
                    .and_then(|module| module.declarations.get(name))
                {
                    return Some(symbol.clone());
                }
            }
        }

        for import in &current.imports {
            if import.selective_names.is_some() {
                continue;
            }
            if let Some(path) = &import.path {
                if let Some(symbol) = self
                    .modules
                    .get(path)
                    .or_else(|| self.modules.get(&normalize_path(path)))
                    .and_then(|module| module.declarations.get(name))
                {
                    return Some(symbol.clone());
                }
            }
        }

        None
    }
}

fn load_module(path: &Path) -> ModuleInfo {
    // `<std>/<name>` virtual paths map to the embedded stdlib source
    // rather than a real file on disk.
    let source = if let Some(stdlib_module) = stdlib_module_from_path(path) {
        match stdlib::get_stdlib_source(stdlib_module) {
            Some(src) => src.to_string(),
            None => return ModuleInfo::default(),
        }
    } else {
        match std::fs::read_to_string(path) {
            Ok(src) => src,
            Err(_) => return ModuleInfo::default(),
        }
    };
    let mut lexer = harn_lexer::Lexer::new(&source);
    let tokens = match lexer.tokenize() {
        Ok(tokens) => tokens,
        Err(_) => return ModuleInfo::default(),
    };
    let mut parser = Parser::new(tokens);
    let program = match parser.parse() {
        Ok(program) => program,
        Err(_) => return ModuleInfo::default(),
    };

    let mut module = ModuleInfo::default();
    for node in &program {
        collect_module_info(path, node, &mut module);
        collect_type_declarations(node, &mut module.type_declarations);
    }
    // Fallback matching the VM loader: if the module declares no
    // `pub fn`, every fn is implicitly exported.
    if !module.has_pub_fn {
        for name in &module.fn_names {
            module.exports.insert(name.clone());
        }
    }
    module
}

/// Extract the stdlib module name when `path` is a `<std>/<name>`
/// virtual path, otherwise `None`.
fn stdlib_module_from_path(path: &Path) -> Option<&str> {
    let s = path.to_str()?;
    s.strip_prefix("<std>/")
}

fn collect_module_info(file: &Path, snode: &SNode, module: &mut ModuleInfo) {
    match &snode.node {
        Node::FnDecl {
            name,
            params,
            is_pub,
            ..
        } => {
            if *is_pub {
                module.exports.insert(name.clone());
                module.has_pub_fn = true;
            }
            module.fn_names.push(name.clone());
            module.declarations.insert(
                name.clone(),
                decl_site(file, snode.span, name, DefKind::Function),
            );
            for param_name in params.iter().map(|param| param.name.clone()) {
                module.declarations.insert(
                    param_name.clone(),
                    decl_site(file, snode.span, &param_name, DefKind::Parameter),
                );
            }
        }
        Node::Pipeline { name, is_pub, .. } => {
            if *is_pub {
                module.exports.insert(name.clone());
            }
            module.declarations.insert(
                name.clone(),
                decl_site(file, snode.span, name, DefKind::Pipeline),
            );
        }
        Node::ToolDecl { name, is_pub, .. } => {
            if *is_pub {
                module.exports.insert(name.clone());
            }
            module.declarations.insert(
                name.clone(),
                decl_site(file, snode.span, name, DefKind::Tool),
            );
        }
        Node::SkillDecl { name, is_pub, .. } => {
            if *is_pub {
                module.exports.insert(name.clone());
            }
            module.declarations.insert(
                name.clone(),
                decl_site(file, snode.span, name, DefKind::Skill),
            );
        }
        Node::StructDecl { name, is_pub, .. } => {
            if *is_pub {
                module.exports.insert(name.clone());
            }
            module.declarations.insert(
                name.clone(),
                decl_site(file, snode.span, name, DefKind::Struct),
            );
        }
        Node::EnumDecl { name, is_pub, .. } => {
            if *is_pub {
                module.exports.insert(name.clone());
            }
            module.declarations.insert(
                name.clone(),
                decl_site(file, snode.span, name, DefKind::Enum),
            );
        }
        Node::InterfaceDecl { name, .. } => {
            module.exports.insert(name.clone());
            module.declarations.insert(
                name.clone(),
                decl_site(file, snode.span, name, DefKind::Interface),
            );
        }
        Node::TypeDecl { name, .. } => {
            module.exports.insert(name.clone());
            module.declarations.insert(
                name.clone(),
                decl_site(file, snode.span, name, DefKind::Type),
            );
        }
        Node::LetBinding { pattern, .. } | Node::VarBinding { pattern, .. } => {
            for name in pattern_names(pattern) {
                module.declarations.insert(
                    name.clone(),
                    decl_site(file, snode.span, &name, DefKind::Variable),
                );
            }
        }
        Node::ImportDecl { path } => {
            let import_path = resolve_import_path(file, path);
            if import_path.is_none() {
                module.has_unresolved_wildcard_import = true;
            }
            module.imports.push(ImportRef {
                path: import_path,
                selective_names: None,
            });
        }
        Node::SelectiveImport { names, path } => {
            let import_path = resolve_import_path(file, path);
            if import_path.is_none() {
                module.has_unresolved_selective_import = true;
            }
            let names: HashSet<String> = names.iter().cloned().collect();
            module.selective_import_names.extend(names.iter().cloned());
            module.imports.push(ImportRef {
                path: import_path,
                selective_names: Some(names),
            });
        }
        Node::AttributedDecl { inner, .. } => {
            collect_module_info(file, inner, module);
        }
        _ => {}
    }
}

fn collect_type_declarations(snode: &SNode, decls: &mut Vec<SNode>) {
    match &snode.node {
        Node::TypeDecl { .. }
        | Node::StructDecl { .. }
        | Node::EnumDecl { .. }
        | Node::InterfaceDecl { .. } => decls.push(snode.clone()),
        Node::AttributedDecl { inner, .. } => collect_type_declarations(inner, decls),
        _ => {}
    }
}

fn type_decl_name(snode: &SNode) -> Option<&str> {
    match &snode.node {
        Node::TypeDecl { name, .. }
        | Node::StructDecl { name, .. }
        | Node::EnumDecl { name, .. }
        | Node::InterfaceDecl { name, .. } => Some(name.as_str()),
        _ => None,
    }
}

fn decl_site(file: &Path, span: Span, name: &str, kind: DefKind) -> DefSite {
    DefSite {
        name: name.to_string(),
        file: file.to_path_buf(),
        kind,
        span,
    }
}

fn pattern_names(pattern: &BindingPattern) -> Vec<String> {
    match pattern {
        BindingPattern::Identifier(name) => vec![name.clone()],
        BindingPattern::Dict(fields) => fields
            .iter()
            .filter_map(|field| field.alias.as_ref().or(Some(&field.key)).cloned())
            .collect(),
        BindingPattern::List(elements) => elements
            .iter()
            .map(|element| element.name.clone())
            .collect(),
        BindingPattern::Pair(a, b) => vec![a.clone(), b.clone()],
    }
}

fn normalize_path(path: &Path) -> PathBuf {
    if stdlib_module_from_path(path).is_some() {
        return path.to_path_buf();
    }
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

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

    fn write_file(dir: &Path, name: &str, contents: &str) -> PathBuf {
        let path = dir.join(name);
        fs::write(&path, contents).unwrap();
        path
    }

    #[test]
    fn recursive_build_loads_transitively_imported_modules() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write_file(root, "leaf.harn", "pub fn leaf_fn() { 1 }\n");
        write_file(
            root,
            "mid.harn",
            "import \"./leaf\"\npub fn mid_fn() { leaf_fn() }\n",
        );
        let entry = write_file(root, "entry.harn", "import \"./mid\"\nmid_fn()\n");

        let graph = build(std::slice::from_ref(&entry));
        let imported = graph
            .imported_names_for_file(&entry)
            .expect("entry imports should resolve");
        // Wildcard import of mid exposes mid_fn (pub) but not leaf_fn.
        assert!(imported.contains("mid_fn"));
        assert!(!imported.contains("leaf_fn"));

        // The transitively loaded module is known to the graph even though
        // the seed only included entry.harn.
        let leaf_path = root.join("leaf.harn");
        assert!(graph.definition_of(&leaf_path, "leaf_fn").is_some());
    }

    #[test]
    fn imported_names_returns_none_when_import_unresolved() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let entry = write_file(root, "entry.harn", "import \"./does_not_exist\"\n");

        let graph = build(std::slice::from_ref(&entry));
        assert!(graph.imported_names_for_file(&entry).is_none());
    }

    #[test]
    fn selective_imports_contribute_only_requested_names() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write_file(root, "util.harn", "pub fn a() { 1 }\npub fn b() { 2 }\n");
        let entry = write_file(root, "entry.harn", "import { a } from \"./util\"\n");

        let graph = build(std::slice::from_ref(&entry));
        let imported = graph
            .imported_names_for_file(&entry)
            .expect("entry imports should resolve");
        assert!(imported.contains("a"));
        assert!(!imported.contains("b"));
    }

    #[test]
    fn stdlib_imports_resolve_to_embedded_sources() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let entry = write_file(root, "entry.harn", "import \"std/math\"\nclamp(5, 0, 10)\n");

        let graph = build(std::slice::from_ref(&entry));
        let imported = graph
            .imported_names_for_file(&entry)
            .expect("std/math should resolve");
        // `clamp` is defined in stdlib_math.harn as `pub fn clamp(...)`.
        assert!(imported.contains("clamp"));
    }

    #[test]
    fn stdlib_imports_expose_type_declarations() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let entry = write_file(
            root,
            "entry.harn",
            "import \"std/triggers\"\nlet provider = \"github\"\n",
        );

        let graph = build(std::slice::from_ref(&entry));
        let decls = graph
            .imported_type_declarations_for_file(&entry)
            .expect("std/triggers type declarations should resolve");
        let names: HashSet<String> = decls
            .iter()
            .filter_map(type_decl_name)
            .map(ToString::to_string)
            .collect();
        assert!(names.contains("TriggerEvent"));
        assert!(names.contains("ProviderPayload"));
        assert!(names.contains("SignatureStatus"));
    }

    #[test]
    fn package_export_map_resolves_declared_module() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let packages = root.join(".harn/packages/acme/runtime");
        fs::create_dir_all(&packages).unwrap();
        fs::write(
            root.join(".harn/packages/acme/harn.toml"),
            "[exports]\ncapabilities = \"runtime/capabilities.harn\"\n",
        )
        .unwrap();
        fs::write(
            packages.join("capabilities.harn"),
            "pub fn exported_capability() { 1 }\n",
        )
        .unwrap();
        let entry = write_file(
            root,
            "entry.harn",
            "import \"acme/capabilities\"\nexported_capability()\n",
        );

        let graph = build(std::slice::from_ref(&entry));
        let imported = graph
            .imported_names_for_file(&entry)
            .expect("package export should resolve");
        assert!(imported.contains("exported_capability"));
    }

    #[test]
    fn package_imports_resolve_from_nested_package_module() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        fs::create_dir_all(root.join(".git")).unwrap();
        fs::create_dir_all(root.join(".harn/packages/acme")).unwrap();
        fs::create_dir_all(root.join(".harn/packages/shared")).unwrap();
        fs::write(
            root.join(".harn/packages/shared/lib.harn"),
            "pub fn shared_helper() { 1 }\n",
        )
        .unwrap();
        fs::write(
            root.join(".harn/packages/acme/lib.harn"),
            "import \"shared\"\npub fn use_shared() { shared_helper() }\n",
        )
        .unwrap();
        let entry = write_file(root, "entry.harn", "import \"acme\"\nuse_shared()\n");

        let graph = build(std::slice::from_ref(&entry));
        let imported = graph
            .imported_names_for_file(&entry)
            .expect("nested package import should resolve");
        assert!(imported.contains("use_shared"));
        let acme_path = root.join(".harn/packages/acme/lib.harn");
        let acme_imports = graph
            .imported_names_for_file(&acme_path)
            .expect("package module imports should resolve");
        assert!(acme_imports.contains("shared_helper"));
    }

    #[test]
    fn unknown_stdlib_import_is_unresolved() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let entry = write_file(root, "entry.harn", "import \"std/does_not_exist\"\n");

        let graph = build(std::slice::from_ref(&entry));
        assert!(
            graph.imported_names_for_file(&entry).is_none(),
            "unknown std module should fail resolution and disable strict check"
        );
    }

    #[test]
    fn import_cycles_do_not_loop_forever() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write_file(root, "a.harn", "import \"./b\"\npub fn a_fn() { 1 }\n");
        write_file(root, "b.harn", "import \"./a\"\npub fn b_fn() { 1 }\n");
        let entry = root.join("a.harn");

        // Just ensuring this terminates and yields sensible names.
        let graph = build(std::slice::from_ref(&entry));
        let imported = graph
            .imported_names_for_file(&entry)
            .expect("cyclic imports still resolve to known exports");
        assert!(imported.contains("b_fn"));
    }

    #[test]
    fn cross_directory_cycle_does_not_explode_module_count() {
        // Regression: two files in sibling directories that import each
        // other produced a fresh path spelling on every round-trip
        // (`../runtime/../context/../runtime/...`), and `build()`'s
        // `seen` set deduped on the raw spelling rather than the
        // canonical path. The walk only terminated when `PATH_MAX` was
        // hit — 1024 on macOS, 4096 on Linux — so Linux re-parsed the
        // same pair thousands of times until it ran out of memory.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let context = root.join("context");
        let runtime = root.join("runtime");
        fs::create_dir_all(&context).unwrap();
        fs::create_dir_all(&runtime).unwrap();
        write_file(
            &context,
            "a.harn",
            "import \"../runtime/b\"\npub fn a_fn() { 1 }\n",
        );
        write_file(
            &runtime,
            "b.harn",
            "import \"../context/a\"\npub fn b_fn() { 1 }\n",
        );
        let entry = context.join("a.harn");

        let graph = build(std::slice::from_ref(&entry));
        // The graph should contain exactly the two real files, keyed by
        // their canonical paths. Pre-fix this was thousands of entries.
        assert_eq!(
            graph.modules.len(),
            2,
            "cross-directory cycle loaded {} modules, expected 2",
            graph.modules.len()
        );
        let imported = graph
            .imported_names_for_file(&entry)
            .expect("cyclic imports still resolve to known exports");
        assert!(imported.contains("b_fn"));
    }
}