Skip to main content

harn_vm/vm/
modules.rs

1use std::collections::BTreeMap;
2use std::future::Future;
3use std::hash::{Hash, Hasher};
4use std::path::{Path, PathBuf};
5use std::pin::Pin;
6use std::sync::{Arc, Mutex, OnceLock};
7
8use harn_modules::DefKind;
9
10use crate::bytecode_cache;
11use crate::module_artifact::compile_module_artifact_from_source;
12use crate::module_source::{self, ModuleSource};
13use crate::prepared_module::PreparedModuleArtifact;
14use crate::value::{ModuleFunctionRegistry, VmClosure, VmEnv, VmError, VmValue};
15
16use super::{ScopeSpan, Vm};
17
18static STDLIB_MODULE_ARTIFACT_CACHE: OnceLock<
19    Mutex<BTreeMap<String, Arc<PreparedModuleArtifact>>>,
20> = OnceLock::new();
21
22fn stdlib_module_artifact_cache() -> &'static Mutex<BTreeMap<String, Arc<PreparedModuleArtifact>>> {
23    STDLIB_MODULE_ARTIFACT_CACHE.get_or_init(|| Mutex::new(BTreeMap::new()))
24}
25
26fn verified_package_source(bytes: Vec<u8>, path: &Path) -> Result<String, VmError> {
27    String::from_utf8(bytes).map_err(|error| {
28        VmError::Runtime(format!(
29            "installed package source {} is not valid UTF-8: {error}",
30            path.display()
31        ))
32    })
33}
34
35fn exported_function_closures(
36    loaded: &LoadedModule,
37    display_path: &Path,
38) -> Result<BTreeMap<String, Arc<VmClosure>>, VmError> {
39    let mut exports = BTreeMap::new();
40    for name in loaded
41        .public_exports
42        .keys()
43        .filter(|name| loaded.functions.contains_key(*name))
44    {
45        let Some(closure) = loaded.functions.get(name) else {
46            return Err(VmError::Runtime(format!(
47                "Import error: exported function '{name}' is missing from {}",
48                display_path.display()
49            )));
50        };
51        exports.insert(name.clone(), Arc::clone(closure));
52    }
53    Ok(exports)
54}
55
56#[cfg(test)]
57fn reset_stdlib_module_artifact_cache() {
58    stdlib_module_artifact_cache().lock().unwrap().clear();
59}
60
61#[cfg(test)]
62fn stdlib_module_artifact_cache_ptr(module: &str, source: &str) -> Option<usize> {
63    let key = stdlib_artifact_cache_key(module, source);
64    stdlib_module_artifact_cache()
65        .lock()
66        .unwrap()
67        .get(&key)
68        .map(|artifact| Arc::as_ptr(artifact) as usize)
69}
70
71pub(crate) struct LoadedModule {
72    pub(crate) functions: BTreeMap<String, Arc<VmClosure>>,
73    /// Shared public declaration contract copied from the artifact and
74    /// extended by explicit re-exports.
75    pub(crate) public_exports: BTreeMap<String, DefKind>,
76    /// Evaluated values of exported declarations whose runtime binding is
77    /// produced by module initialization, including structs and enums.
78    pub(crate) public_values: BTreeMap<String, VmValue>,
79    /// Decoded JSON-Schema dict for each `pub type` alias that lowers to a
80    /// schema. Importers bind the alias name to this value so
81    /// expression-position uses (`output: ImportedAlias`) work.
82    pub(crate) public_type_schemas: BTreeMap<String, VmValue>,
83    /// Guard under which this filesystem module and its transitive closure were
84    /// instantiated. A guarded execution cannot reuse an unguarded module even
85    /// when the entry bytes currently match: its closures may retain imports
86    /// compiled from earlier, unverified bytes.
87    package_execution_guard: Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
88    pub(crate) _module_functions: crate::value::ModuleFunctionRegistry,
89    pub(crate) _module_state: crate::value::ModuleState,
90}
91
92/// Runtime module cache shared by child VMs within one execution tree.
93///
94/// The map stays copy-on-write so a child can add modules without mutating its
95/// parent. Cache entries are never replaced after instantiation, so cache hits
96/// and map copies share their export maps plus their existing shared
97/// registries/state through a cheap outer [`Arc`] instead of cloning the whole
98/// module.
99pub(crate) type ModuleCache = Arc<BTreeMap<PathBuf, Arc<LoadedModule>>>;
100
101/// An import whose target module was still mid-load (an import cycle) when the
102/// importing module reached it. The target's function closures don't exist yet
103/// at that point, so the binding can't happen inline. We record it here and
104/// resolve it once both modules are fully loaded — see
105/// [`Vm::flush_deferred_cyclic_imports`].
106#[derive(Clone, Debug)]
107pub(crate) struct DeferredCyclicImport {
108    /// Canonical path of the module that issued the import.
109    pub(crate) importer: PathBuf,
110    /// Canonical path of the cyclically-imported target module.
111    pub(crate) target: PathBuf,
112    /// Selectively-imported names, or `None` for a wildcard/side-effect import.
113    pub(crate) selected_names: Option<Vec<String>>,
114    /// When set, bind a namespace dict under this alias instead of flattening.
115    pub(crate) namespace_alias: Option<String>,
116}
117
118#[derive(Clone, Copy)]
119enum ImportProjection<'a> {
120    BindCaller(Option<&'a [String]>),
121    /// Bind `import * as alias` as a single namespace dict.
122    BindNamespace(&'a str),
123    MaterializeOnly,
124}
125
126impl ImportProjection<'_> {
127    fn package_rejection_kind(self) -> &'static str {
128        match self {
129            Self::BindCaller(_) | Self::BindNamespace(_) => "import",
130            Self::MaterializeOnly => "execution",
131        }
132    }
133}
134
135/// Resolve the names an import may introduce from one loaded module. The
136/// artifact's typed export contract is authoritative for ordinary imports,
137/// re-exports, and delayed cycle binding alike.
138fn module_import_names(
139    module_name: &str,
140    loaded: &LoadedModule,
141    selected_names: Option<&[String]>,
142) -> Result<Vec<String>, VmError> {
143    if let Some(names) = selected_names {
144        for name in names {
145            if !loaded.public_exports.contains_key(name) {
146                let hint = if loaded.functions.contains_key(name) {
147                    " — it is defined there but not `pub`; mark it `pub` to export it"
148                } else {
149                    ""
150                };
151                return Err(VmError::Runtime(format!(
152                    "Import error: '{name}' is not exported by {module_name}{hint}"
153                )));
154            }
155        }
156        return Ok(names.to_vec());
157    }
158
159    Ok(loaded.public_exports.keys().cloned().collect())
160}
161
162/// Build the closed namespace dict for `import * as alias from path`.
163///
164/// Includes `"_namespace" → module path` so `call_dict_method` dispatches
165/// callable fields, plus every public export that has a runtime value.
166/// Type/interface-only exports are omitted (no runtime binding).
167fn build_namespace_dict(module_path: &str, loaded: &LoadedModule) -> VmValue {
168    let mut map = BTreeMap::new();
169    map.insert(
170        "_namespace".to_string(),
171        VmValue::String(arcstr::ArcStr::from(module_path)),
172    );
173    for (name, kind) in &loaded.public_exports {
174        if !kind.has_runtime_value() {
175            // Still project schema-capable type aliases when present.
176            if let Some(schema) = loaded.public_type_schemas.get(name) {
177                map.insert(name.clone(), schema.clone());
178            }
179            continue;
180        }
181        if let Some(value) = loaded.public_values.get(name) {
182            map.insert(name.clone(), value.clone());
183            continue;
184        }
185        if let Some(schema) = loaded.public_type_schemas.get(name) {
186            map.insert(name.clone(), schema.clone());
187            continue;
188        }
189        if let Some(closure) = loaded.functions.get(name) {
190            map.insert(name.clone(), VmValue::Closure(Arc::clone(closure)));
191        }
192    }
193    VmValue::dict(map)
194}
195
196pub fn resolve_module_import_path(base: &Path, path: &str) -> PathBuf {
197    let synthetic_current_file = base.join("__harn_import_base__.harn");
198    if let Some(resolved) = harn_modules::resolve_import_path(&synthetic_current_file, path) {
199        return resolved;
200    }
201
202    let mut file_path = base.join(path);
203
204    if !file_path.exists() && file_path.extension().is_none() {
205        file_path.set_extension("harn");
206    }
207
208    file_path
209}
210
211fn stdlib_artifact_cache_key(module: &str, source: &str) -> String {
212    let mut hasher = std::collections::hash_map::DefaultHasher::new();
213    module.hash(&mut hasher);
214    source.hash(&mut hasher);
215    format!("{module}:{:016x}", hasher.finish())
216}
217
218fn stdlib_module_artifact(
219    module: &str,
220    synthetic: &Path,
221    source: &'static str,
222    recorder: Option<&super::ModulePhaseRecorder>,
223) -> Result<Arc<PreparedModuleArtifact>, VmError> {
224    let key = stdlib_artifact_cache_key(module, source);
225    {
226        let cache = stdlib_module_artifact_cache().lock().unwrap();
227        if let Some(cached) = cache.get(&key) {
228            return Ok(Arc::clone(cached));
229        }
230    }
231
232    // Stdlib modules are embedded in the binary so their content cannot
233    // legitimately change between processes; that means the disk cache
234    // for stdlib can use a synthetic source_path. The harn_version field
235    // of the cache key gates correctness across releases.
236    let embedded = ModuleSource::from_text(source);
237    let lookup = {
238        let _load_span = recorder.map(super::ModulePhaseRecorder::load_span);
239        bytecode_cache::load_module(synthetic, &embedded)
240    };
241    let artifact = if let Some(artifact) = lookup.artifact {
242        artifact
243    } else {
244        let mut compile_span = recorder.map(super::ModulePhaseRecorder::compile_span);
245        let compiled = compile_module_artifact_from_source(synthetic, source)?;
246        if let Some(span) = &mut compile_span {
247            span.mark_compile_succeeded();
248        }
249        drop(compile_span);
250        if let Err(err) = bytecode_cache::store_module(&lookup.key, &compiled) {
251            if std::env::var_os("HARN_BYTECODE_CACHE_DEBUG").is_some() {
252                eprintln!("[harn] stdlib module cache write skipped for {module}: {err}");
253            }
254        }
255        compiled
256    };
257
258    let compiled = {
259        let _load_span = recorder.map(super::ModulePhaseRecorder::load_span);
260        Arc::new(PreparedModuleArtifact::from_cached(artifact))
261    };
262    let mut cache = stdlib_module_artifact_cache().lock().unwrap();
263    if let Some(cached) = cache.get(&key) {
264        return Ok(Arc::clone(cached));
265    }
266    cache.insert(key, Arc::clone(&compiled));
267    Ok(compiled)
268}
269
270pub(crate) fn prepare_stdlib_module_artifact(
271    path: &Path,
272    recorder: Option<&super::ModulePhaseRecorder>,
273) -> Result<(), VmError> {
274    let Some(module) = path.to_str().and_then(|path| path.strip_prefix("<std>/")) else {
275        return Ok(());
276    };
277    let Some(source) = crate::stdlib_modules::get_stdlib_source(module) else {
278        return Ok(());
279    };
280    let synthetic = PathBuf::from(format!("<stdlib>/{module}.harn"));
281    stdlib_module_artifact(module, &synthetic, source, recorder).map(|_| ())
282}
283
284impl Vm {
285    fn resolve_module_import_path(&self, base: &Path, path: &str) -> Result<PathBuf, VmError> {
286        if let Some(guard) = &self.package_execution_guard {
287            let synthetic_current_file = base.join("__harn_import_base__.harn");
288            if let Some(resolved) =
289                harn_modules::resolve_import_path_with_guard(&synthetic_current_file, path, guard)
290                    .map_err(|error| {
291                    VmError::Runtime(format!("installed package import rejected: {error}"))
292                })?
293            {
294                return Ok(resolved);
295            }
296            let mut file_path = base.join(path);
297            if !file_path.exists() && file_path.extension().is_none() {
298                file_path.set_extension("harn");
299            }
300            return Ok(file_path);
301        }
302        Ok(resolve_module_import_path(base, path))
303    }
304
305    /// Resolve a callable against this VM. Lazy callables initialize once per
306    /// VM execution tree, then retain that module scope for later child VMs in
307    /// the same tree. Fresh VM roots remain isolated.
308    pub async fn resolve_callable(
309        &mut self,
310        callable: &crate::value::VmCallable,
311    ) -> Result<Arc<crate::value::VmClosure>, VmError> {
312        self.ensure_execution_available()?;
313        match callable {
314            crate::value::VmCallable::Eager(closure) => Ok(Arc::clone(closure)),
315            crate::value::VmCallable::Lazy(lazy) => {
316                let (cache_key, module_path) = self.lazy_callable_module_path(lazy);
317                let next_guard = lazy
318                    .package_execution_guard_handle()
319                    .or_else(|| self.package_execution_guard.clone());
320                if let Some(guard) = &next_guard {
321                    guard.verify_entry_source(&module_path).map_err(|error| {
322                        VmError::Runtime(format!("installed package execution rejected: {error}"))
323                    })?;
324                }
325                let resolution = {
326                    let mut modules = self.lazy_callable_modules.lock();
327                    let slots = modules.entry(cache_key).or_default();
328                    if let Some(slot) = slots.iter().find(|slot| slot.execution_guard == next_guard)
329                    {
330                        Arc::clone(&slot.resolution)
331                    } else {
332                        let resolution = Arc::new(tokio::sync::OnceCell::new());
333                        slots.push(crate::vm::state::LazyCallableCacheSlot {
334                            execution_guard: next_guard.clone(),
335                            resolution: Arc::clone(&resolution),
336                        });
337                        resolution
338                    }
339                };
340                let previous_package_execution_guard =
341                    std::mem::replace(&mut self.package_execution_guard, next_guard);
342                let resolved = resolution
343                    .get_or_try_init(|| async {
344                        let exports = self.load_module_exports(&module_path).await?;
345                        let exports = exports
346                            .into_iter()
347                            .map(|(name, closure)| (name, closure.retained_for_host_registry()))
348                            .collect();
349                        // Pin the complete module graph loaded above so that a
350                        // handler's transitively imported callees keep their
351                        // home-module registries/state alive for later child
352                        // VMs that hit this cache without re-importing.
353                        Ok::<_, VmError>(Arc::new(crate::vm::state::ResolvedLazyCallable {
354                            exports,
355                            retained_module_graph: Arc::clone(&self.module_cache),
356                        }))
357                    })
358                    .await;
359                self.package_execution_guard = previous_package_execution_guard;
360                let resolved = resolved?;
361                resolved
362                    .exports
363                    .get(&lazy.function_name)
364                    .cloned()
365                    .ok_or_else(|| {
366                        VmError::Runtime(format!(
367                            "function '{}' is not exported by module '{}'",
368                            lazy.function_name,
369                            lazy.module_path.display()
370                        ))
371                    })
372            }
373            crate::value::VmCallable::Pipeline(_) => Err(VmError::TypeError(
374                "pipeline callable requires execute_callable".to_string(),
375            )),
376        }
377    }
378
379    pub async fn execute_callable(
380        &mut self,
381        callable: &crate::value::VmCallable,
382        args: &[crate::value::VmValue],
383    ) -> Result<crate::value::VmValue, VmError> {
384        let crate::value::VmCallable::Pipeline(pipeline) = callable else {
385            let closure = self.resolve_callable(callable).await?;
386            return self.call_closure_pub(&closure, args).await;
387        };
388
389        let (_, module_path) = self.lazy_module_path(&pipeline.module_path);
390        let next_guard = pipeline
391            .package_execution_guard_handle()
392            .or_else(|| self.package_execution_guard.clone());
393        let previous_package_execution_guard =
394            std::mem::replace(&mut self.package_execution_guard, next_guard);
395        let result = async {
396            let closure = self
397                .load_public_module_callable(&module_path, &pipeline.pipeline_name)
398                .await?;
399            self.call_closure_pub(&closure, args).await
400        }
401        .await;
402        self.package_execution_guard = previous_package_execution_guard;
403        result
404    }
405
406    fn lazy_callable_module_path(&self, lazy: &crate::value::LazyVmCallable) -> (PathBuf, PathBuf) {
407        self.lazy_module_path(&lazy.module_path)
408    }
409
410    fn lazy_module_path(&self, path: &std::path::Path) -> (PathBuf, PathBuf) {
411        let mut module_path = if path.is_absolute() {
412            path.to_path_buf()
413        } else {
414            self.source_dir
415                .clone()
416                .unwrap_or_else(|| PathBuf::from("."))
417                .join(path)
418        };
419        if !module_path.exists() && module_path.extension().is_none() {
420            module_path.set_extension("harn");
421        }
422        let cache_key = module_path
423            .canonicalize()
424            .unwrap_or_else(|_| module_path.clone());
425        (cache_key, module_path)
426    }
427
428    async fn load_module_from_source(
429        &mut self,
430        synthetic: PathBuf,
431        source: &str,
432    ) -> Result<Arc<LoadedModule>, VmError> {
433        if let Some(loaded) = self.module_cache.get(&synthetic).cloned() {
434            return Ok(loaded);
435        }
436        Arc::make_mut(&mut self.source_cache).insert(synthetic.clone(), Arc::from(source));
437
438        let mut compile_span = self.module_compile_span();
439        let compiled = compile_module_artifact_from_source(&synthetic, source)?;
440        if let Some(span) = &mut compile_span {
441            span.mark_compile_succeeded();
442        }
443        drop(compile_span);
444        let artifact = {
445            let _load_span = self.module_load_span();
446            PreparedModuleArtifact::from_cached(compiled)
447        };
448
449        self.imported_paths.push(synthetic.clone());
450        let loaded = Arc::new(self.instantiate_module(None, &artifact).await?);
451        self.imported_paths.pop();
452        {
453            let _load_span = self.module_load_span();
454            Arc::make_mut(&mut self.module_cache).insert(synthetic, Arc::clone(&loaded));
455        }
456        self.record_module_loaded();
457        Ok(loaded)
458    }
459
460    /// Widen a stdlib module's export surface with the builtins it re-exports
461    /// (see [`harn_stdlib::builtin_reexports`]), so a Rust-implemented member of
462    /// the module imports exactly like a Harn-implemented one.
463    ///
464    /// The name binds to a [`VmValue::BuiltinRef`], which is what a bare mention
465    /// of a builtin already evaluates to — so an imported `assert_eq` and a
466    /// global `assert_eq` are the same function reached two ways, not two
467    /// implementations that can drift.
468    fn add_builtin_reexports(module: &str, loaded: &mut LoadedModule) {
469        for name in harn_stdlib::builtin_reexports(module) {
470            // A `pub fn` in the module's Harn source wins: it is the more
471            // specific declaration, and silently shadowing it here would make
472            // the source of an export unguessable from reading the module.
473            if loaded.public_exports.contains_key(*name) {
474                continue;
475            }
476            loaded
477                .public_exports
478                .insert((*name).to_string(), DefKind::Function);
479            loaded.public_values.insert(
480                (*name).to_string(),
481                VmValue::BuiltinRef(arcstr::ArcStr::from(*name)),
482            );
483        }
484    }
485
486    async fn load_stdlib_module_from_source(
487        &mut self,
488        module: &str,
489        synthetic: PathBuf,
490        source: &'static str,
491    ) -> Result<Arc<LoadedModule>, VmError> {
492        if let Some(loaded) = self.module_cache.get(&synthetic).cloned() {
493            return Ok(loaded);
494        }
495        Arc::make_mut(&mut self.source_cache).insert(synthetic.clone(), Arc::from(source));
496
497        let artifact = stdlib_module_artifact(
498            module,
499            &synthetic,
500            source,
501            self.module_phase_recorder.as_ref(),
502        )?;
503        self.imported_paths.push(synthetic.clone());
504        let mut loaded = self.instantiate_stdlib_module(artifact.as_ref()).await?;
505        self.imported_paths.pop();
506        Self::add_builtin_reexports(module, &mut loaded);
507        let loaded = Arc::new(loaded);
508        {
509            let _load_span = self.module_load_span();
510            Arc::make_mut(&mut self.module_cache).insert(synthetic, Arc::clone(&loaded));
511        }
512        self.record_module_loaded();
513        Ok(loaded)
514    }
515
516    async fn instantiate_stdlib_module(
517        &mut self,
518        artifact: &PreparedModuleArtifact,
519    ) -> Result<LoadedModule, VmError> {
520        self.instantiate_module(None, artifact).await
521    }
522
523    /// Instantiate a previously-hydrated [`PreparedModuleArtifact`] into a
524    /// [`LoadedModule`]. Re-runs nested imports, replays the init chunk
525    /// into a fresh module env, mints a [`VmClosure`] for each compiled
526    /// function (stamped with `module_source_dir` so imports from inside
527    /// those functions resolve against the originating file), and
528    /// applies the re-export pass. Used by both stdlib and user-import
529    /// code paths.
530    async fn instantiate_module(
531        &mut self,
532        module_source_dir: Option<PathBuf>,
533        artifact: &PreparedModuleArtifact,
534    ) -> Result<LoadedModule, VmError> {
535        let caller_env = self.env.clone();
536        let old_source_dir = self.source_dir.clone();
537        self.env = VmEnv::new();
538        self.source_dir = module_source_dir.clone();
539
540        for import in &artifact.imports {
541            if let Some(alias) = &import.namespace_alias {
542                self.execute_namespace_import_bind(&import.path, alias)
543                    .await?;
544            } else {
545                self.execute_import(&import.path, import.selected_names.as_deref())
546                    .await?;
547            }
548        }
549
550        // Nested modules own their own load spans. Start this module's span
551        // only after those imports finish so aggregate load time is additive.
552        let _load_span = self.module_load_span();
553
554        let module_state: crate::value::ModuleState = {
555            let mut init_env = self.env.clone();
556            if artifact.type_schema_init_chunk.is_some() || artifact.init_chunk.is_some() {
557                let saved_env = std::mem::replace(&mut self.env, init_env);
558                let saved_frames = std::mem::take(&mut self.frames);
559                let saved_handlers = std::mem::take(&mut self.exception_handlers);
560                let saved_iterators = std::mem::take(&mut self.iterators);
561                let saved_deadlines = std::mem::take(&mut self.deadlines);
562                // STEP_STACK / PERSONA_STACK are thread-locals shared with
563                // the calling frame. Emptying `self.frames` above means
564                // any `prune_below_frame(0)` triggered while the init
565                // chunk's bytecode runs — including the inevitable
566                // frame-pop prune at end-of-chunk — would wipe active
567                // steps owned by the *caller* (e.g., a `@step`-decorated
568                // function whose body lazily imports a module). Snapshot
569                // the persona/step context here and restore it after init
570                // so module loading is invisible to the step-tracking
571                // surface.
572                let active_context = crate::step_runtime::suspend_active_context();
573                let init_result: Result<(), VmError> = async {
574                    if let Some(chunk) = &artifact.type_schema_init_chunk {
575                        self.run_chunk(Arc::clone(chunk)).await?;
576                    }
577                    if let Some(chunk) = &artifact.init_chunk {
578                        self.run_chunk(Arc::clone(chunk)).await?;
579                    }
580                    Ok(())
581                }
582                .await;
583                drop(active_context);
584                init_env = std::mem::replace(&mut self.env, saved_env);
585                self.frames = saved_frames;
586                self.exception_handlers = saved_handlers;
587                self.iterators = saved_iterators;
588                self.deadlines = saved_deadlines;
589                init_result?;
590            }
591            Arc::new(crate::value::VmMutex::new(init_env))
592        };
593
594        let module_env = self.env.clone();
595        let registry: ModuleFunctionRegistry =
596            Arc::new(crate::value::VmMutex::new(BTreeMap::new()));
597        let mut functions: BTreeMap<String, Arc<VmClosure>> = BTreeMap::new();
598        let mut public_exports = artifact.public_exports.clone();
599        // The init chunk already ran into `module_state`, so init-backed public
600        // values are live there. Read only the names identified by the artifact
601        // contract and publish their evaluated values for importers.
602        let mut public_values: BTreeMap<String, VmValue> = BTreeMap::new();
603        {
604            let state = module_state.lock();
605            for name in &artifact.public_value_names {
606                if let Some(value) = state.get(name) {
607                    public_values.insert(name.clone(), value);
608                }
609            }
610        }
611        let public_type_names = artifact.public_type_names.clone();
612        let mut public_type_schemas: BTreeMap<String, VmValue> = {
613            let state = module_state.lock();
614            public_type_names
615                .iter()
616                .filter_map(|name| state.get(name).map(|schema| (name.clone(), schema)))
617                .collect()
618        };
619
620        for (name, compiled) in &artifact.functions {
621            let closure = Arc::new(VmClosure {
622                func: Arc::clone(compiled),
623                env: module_env.clone(),
624                source_dir: module_source_dir.clone(),
625                module_functions: Some(Arc::downgrade(&registry)),
626                module_state: Some(Arc::downgrade(&module_state)),
627                retained_module_scope: None,
628            });
629            registry.lock().insert(name.clone(), Arc::clone(&closure));
630            self.env
631                .define(name, VmValue::Closure(Arc::clone(&closure)), false)?;
632            module_state
633                .lock()
634                .define(name, VmValue::Closure(Arc::clone(&closure)), false)?;
635            functions.insert(name.clone(), Arc::clone(&closure));
636        }
637
638        for import in artifact.imports.iter().filter(|import| import.is_pub) {
639            let cache_key = self.cache_key_for_import(&import.path)?;
640            let Some(loaded) = self.module_cache.get(&cache_key).cloned() else {
641                // A plain `import`/`import {...}` across a cycle is bound late
642                // by `flush_deferred_cyclic_imports`, but a `pub import`
643                // re-export has to publish the names into *this* module's
644                // public surface right now — and the target is still mid-load,
645                // so its surface does not exist yet. Name the cycle explicitly
646                // instead of the misleading "was not loaded".
647                if self.imported_paths.contains(&cache_key) {
648                    return Err(VmError::Runtime(format!(
649                        "Re-export error: cannot `pub import` from '{}' because it forms an \
650                         import cycle with this module (its public surface is still being \
651                         built). Use a plain `import` here, or re-export from a module that is \
652                         not part of the cycle.",
653                        import.path
654                    )));
655                }
656                return Err(VmError::Runtime(format!(
657                    "Re-export error: imported module '{}' was not loaded",
658                    import.path
659                )));
660            };
661            // `pub import * as alias` publishes the alias namespace object —
662            // never flatten target members into this module's public surface.
663            if let Some(alias) = &import.namespace_alias {
664                if public_exports.contains_key(alias) || functions.contains_key(alias) {
665                    return Err(VmError::Runtime(format!(
666                        "Re-export collision: '{alias}' is defined here and also \
667                         re-exported as a namespace from '{}'",
668                        import.path
669                    )));
670                }
671                let dict = build_namespace_dict(&import.path, &loaded);
672                public_values.insert(alias.clone(), dict);
673                public_exports.insert(alias.clone(), DefKind::Variable);
674                continue;
675            }
676            let names_to_reexport =
677                module_import_names(&import.path, &loaded, import.selected_names.as_deref())?;
678            for name in names_to_reexport {
679                let Some(kind) = loaded.public_exports.get(&name).copied() else {
680                    return Err(VmError::Runtime(format!(
681                        "Re-export error: '{name}' is not exported by '{}'",
682                        import.path
683                    )));
684                };
685                let Some(closure) = loaded.functions.get(&name) else {
686                    // Init-backed declarations carry their evaluated value
687                    // directly, including struct constructors and enum
688                    // namespaces.
689                    if let Some(value) = loaded.public_values.get(&name) {
690                        public_values.insert(name.clone(), value.clone());
691                        public_exports.insert(name, kind);
692                        continue;
693                    }
694                    // Type-only declarations carry no runtime binding. Preserve
695                    // an optional schema lowering and the contract entry.
696                    if let Some(schema) = loaded.public_type_schemas.get(&name) {
697                        public_type_schemas.insert(name.clone(), schema.clone());
698                    }
699                    public_exports.insert(name, kind);
700                    continue;
701                };
702                if let Some(existing) = functions.get(&name) {
703                    if !Arc::ptr_eq(existing, closure) {
704                        return Err(VmError::Runtime(format!(
705                            "Re-export collision: '{name}' is defined here and also \
706                             re-exported from '{}'",
707                            import.path
708                        )));
709                    }
710                }
711                functions.insert(name.clone(), Arc::clone(closure));
712                public_exports.insert(name, kind);
713            }
714        }
715
716        self.env = caller_env;
717        self.source_dir = old_source_dir;
718
719        Ok(LoadedModule {
720            functions,
721            public_exports,
722            public_values,
723            public_type_schemas,
724            package_execution_guard: module_source_dir
725                .as_ref()
726                .and(self.package_execution_guard.clone()),
727            _module_functions: registry,
728            _module_state: module_state,
729        })
730    }
731
732    fn export_namespace_module(
733        &mut self,
734        module_path: &Path,
735        loaded: &LoadedModule,
736        alias: &str,
737    ) -> Result<(), VmError> {
738        let module_name = module_path.display().to_string();
739        if self.env.get(alias).is_some() {
740            return Err(VmError::Runtime(format!(
741                "Import collision: '{alias}' is already defined when importing {module_name}. \
742                 Use a different namespace alias: import * as <name> from \"...\""
743            )));
744        }
745        let dict = build_namespace_dict(&module_name, loaded);
746        self.env.define(alias, dict, false)?;
747        Ok(())
748    }
749
750    fn export_loaded_module(
751        &mut self,
752        module_path: &Path,
753        loaded: &LoadedModule,
754        selected_names: Option<&[String]>,
755    ) -> Result<(), VmError> {
756        let module_name = module_path.display().to_string();
757        let export_names = module_import_names(&module_name, loaded, selected_names)?;
758
759        for name in export_names {
760            // `pub const` / `pub let` values: bind by value.
761            if let Some(value) = loaded.public_values.get(&name) {
762                if self.env.get(&name).is_some() {
763                    return Err(VmError::Runtime(format!(
764                        "Import collision: '{name}' is already defined when importing \
765                         {module_name}. Use selective imports to disambiguate: \
766                         import {{ {name} }} from \"...\""
767                    )));
768                }
769                self.env.define(&name, value.clone(), false)?;
770                continue;
771            }
772            // Type and interface declarations are valid imports without a
773            // runtime value. Schema-capable aliases still bind their schema so
774            // expression-position uses match local alias lowering.
775            if let Some(schema) = loaded.public_type_schemas.get(&name) {
776                self.env.define(&name, schema.clone(), false)?;
777                continue;
778            }
779            if loaded
780                .public_exports
781                .get(&name)
782                .is_some_and(|kind| !kind.has_runtime_value())
783            {
784                continue;
785            }
786            let Some(closure) = loaded.functions.get(&name) else {
787                return Err(VmError::Runtime(format!(
788                    "Import error: '{name}' is not defined in {module_name}"
789                )));
790            };
791            if let Some(VmValue::Closure(_)) = self.env.get(&name) {
792                return Err(VmError::Runtime(format!(
793                    "Import collision: '{name}' is already defined when importing {module_name}. \
794                     Use selective imports to disambiguate: import {{ {name} }} from \"...\""
795                )));
796            }
797            self.env
798                .define(&name, VmValue::Closure(Arc::clone(closure)), false)?;
799        }
800        Ok(())
801    }
802
803    /// Execute an import, reading and running the file's declarations.
804    pub(super) fn execute_import<'a>(
805        &'a mut self,
806        path: &'a str,
807        selected_names: Option<&'a [String]>,
808    ) -> Pin<Box<dyn Future<Output = Result<(), VmError>> + Send + 'a>> {
809        self.execute_import_with_projection(path, ImportProjection::BindCaller(selected_names))
810    }
811
812    /// Bind `import * as alias from path` as a closed namespace dict.
813    pub(super) fn execute_namespace_import_bind<'a>(
814        &'a mut self,
815        path: &'a str,
816        alias: &'a str,
817    ) -> Pin<Box<dyn Future<Output = Result<(), VmError>> + Send + 'a>> {
818        self.execute_import_with_projection(path, ImportProjection::BindNamespace(alias))
819    }
820
821    fn materialize_import<'a>(
822        &'a mut self,
823        path: &'a str,
824    ) -> Pin<Box<dyn Future<Output = Result<(), VmError>> + Send + 'a>> {
825        self.execute_import_with_projection(path, ImportProjection::MaterializeOnly)
826    }
827
828    fn apply_import_projection(
829        &mut self,
830        module_path: &Path,
831        loaded: &LoadedModule,
832        projection: ImportProjection<'_>,
833    ) -> Result<(), VmError> {
834        match projection {
835            ImportProjection::BindCaller(selected_names) => {
836                self.export_loaded_module(module_path, loaded, selected_names)
837            }
838            ImportProjection::BindNamespace(alias) => {
839                self.export_namespace_module(module_path, loaded, alias)
840            }
841            ImportProjection::MaterializeOnly => Ok(()),
842        }
843    }
844
845    fn execute_import_with_projection<'a>(
846        &'a mut self,
847        path: &'a str,
848        projection: ImportProjection<'a>,
849    ) -> Pin<Box<dyn Future<Output = Result<(), VmError>> + Send + 'a>> {
850        Box::pin(async move {
851            let _import_span = ScopeSpan::new(crate::tracing::SpanKind::Import, path.to_string());
852
853            let stdlib_module = path
854                .strip_prefix("std/")
855                .or_else(|| (path == "observability").then_some("observability"));
856            if let Some(module) = stdlib_module {
857                if let Some(source) = crate::stdlib_modules::get_stdlib_source(module) {
858                    let synthetic = PathBuf::from(format!("<stdlib>/{module}.harn"));
859                    if self.imported_paths.contains(&synthetic) {
860                        return Ok(());
861                    }
862                    if let Some(loaded) = self.module_cache.get(&synthetic).cloned() {
863                        return self.apply_import_projection(&synthetic, &loaded, projection);
864                    }
865                    let loaded = self
866                        .load_stdlib_module_from_source(module, synthetic.clone(), source)
867                        .await?;
868                    if !matches!(projection, ImportProjection::MaterializeOnly) {
869                        let _load_span = self.module_load_span();
870                        self.apply_import_projection(&synthetic, &loaded, projection)?;
871                    }
872                    return Ok(());
873                }
874                return Err(VmError::Runtime(format!(
875                    "Unknown stdlib module: std/{module}"
876                )));
877            }
878
879            let base = self
880                .source_dir
881                .clone()
882                .unwrap_or_else(|| PathBuf::from("."));
883            let file_path = self.resolve_module_import_path(&base, path)?;
884            let verified_source = if let Some(guard) = &self.package_execution_guard {
885                let bytes = guard.verify_entry_source(&file_path).map_err(|error| {
886                    VmError::Runtime(format!(
887                        "installed package {} rejected: {error}",
888                        projection.package_rejection_kind()
889                    ))
890                })?;
891                Some(verified_package_source(bytes, &file_path)?)
892            } else {
893                None
894            };
895
896            let canonical = file_path
897                .canonicalize()
898                .unwrap_or_else(|_| file_path.clone());
899            if self.imported_paths.contains(&canonical) {
900                // Import cycle: `canonical` is still mid-load (it sits on the
901                // import stack), so its function closures don't exist yet and
902                // we cannot bind the requested names inline. Record the import
903                // and resolve it once both modules finish loading — otherwise
904                // whichever module happens to close the cycle silently loses
905                // these bindings and fails with `Undefined builtin` at call
906                // time, in a load-order-dependent way.
907                match projection {
908                    ImportProjection::BindCaller(selected_names) => {
909                        if let Some(importer) = self.imported_paths.last().cloned() {
910                            if importer != canonical {
911                                self.deferred_cyclic_imports.push(DeferredCyclicImport {
912                                    importer,
913                                    target: canonical.clone(),
914                                    selected_names: selected_names.map(<[String]>::to_vec),
915                                    namespace_alias: None,
916                                });
917                            }
918                        }
919                    }
920                    ImportProjection::BindNamespace(alias) => {
921                        if let Some(importer) = self.imported_paths.last().cloned() {
922                            if importer != canonical {
923                                self.deferred_cyclic_imports.push(DeferredCyclicImport {
924                                    importer,
925                                    target: canonical.clone(),
926                                    selected_names: None,
927                                    namespace_alias: Some(alias.to_string()),
928                                });
929                            }
930                        }
931                    }
932                    ImportProjection::MaterializeOnly => {}
933                }
934                return Ok(());
935            }
936            if let Some(loaded) = self.module_cache.get(&canonical).cloned() {
937                if let Some(source) = &verified_source {
938                    let cached_source = self.source_cache.get(&canonical).map(Arc::as_ref);
939                    if cached_source != Some(source.as_str()) {
940                        return Err(VmError::Runtime(format!(
941                            "installed package {} rejected: cached module {} was not compiled from the verified package bytes",
942                            projection.package_rejection_kind(),
943                            canonical.display()
944                        )));
945                    }
946                    let active_guard = self
947                        .package_execution_guard
948                        .as_deref()
949                        .expect("verified package source requires an active guard");
950                    if loaded.package_execution_guard.as_deref() != Some(active_guard) {
951                        return Err(VmError::Runtime(format!(
952                            "installed package {} rejected: cached module {} was not instantiated under the active package execution guard",
953                            projection.package_rejection_kind(),
954                            canonical.display()
955                        )));
956                    }
957                }
958                return self.apply_import_projection(&canonical, &loaded, projection);
959            }
960            self.imported_paths.push(canonical.clone());
961
962            // The link table, when this graph has one, names this module's
963            // artifact from a digest the entry walk already recorded — so the
964            // file is never read. Guard-verified package bytes are excluded:
965            // they are their own authority and deliberately bypass every memo,
966            // and `verified_source` is `Some` exactly when a guard is active.
967            let linked = verified_source
968                .is_none()
969                .then(|| {
970                    let content_hash = self
971                        .graph_link_table
972                        .as_ref()?
973                        .content_hash(canonical.as_path())?;
974                    let _load_span = self.module_load_span();
975                    self.linked_module_artifact(&file_path, &canonical, content_hash)
976                })
977                .flatten();
978
979            let artifact = if let Some(linked) = linked {
980                linked
981            } else {
982                let source = {
983                    let _load_span = self.module_load_span();
984                    match verified_source {
985                        // Guard-verified package bytes are their own authority
986                        // and never come from the shared on-disk memo.
987                        Some(source) => Arc::new(ModuleSource::from_text(source)),
988                        None => module_source::read(&file_path).map_err(|e| {
989                            // Name the resolution base: relative imports resolve against
990                            // the importing file's dir (or CWD when unset), so an error
991                            // that prints only the joined path leaves the author guessing
992                            // which base was used.
993                            VmError::Runtime(format!(
994                                "Import error: cannot read '{}' (resolved '{path}' relative to {}): {e}",
995                                file_path.display(),
996                                base.display()
997                            ))
998                        })?,
999                    }
1000                };
1001                {
1002                    let source_cache = Arc::make_mut(&mut self.source_cache);
1003                    source_cache.insert(canonical.clone(), Arc::clone(source.text()));
1004                    source_cache.insert(file_path.clone(), Arc::clone(source.text()));
1005                }
1006
1007                self.prepared_module_cache.prepare(
1008                    &file_path,
1009                    &canonical,
1010                    &source,
1011                    None,
1012                    self.module_phase_recorder.as_ref(),
1013                )?
1014            };
1015
1016            let module_source_dir = file_path.parent().map(|p| p.to_path_buf());
1017            let loaded = Arc::new(
1018                self.instantiate_module(module_source_dir, artifact.as_ref())
1019                    .await?,
1020            );
1021            self.imported_paths.pop();
1022            {
1023                let _load_span = self.module_load_span();
1024                Arc::make_mut(&mut self.module_cache)
1025                    .insert(canonical.clone(), Arc::clone(&loaded));
1026            }
1027            self.record_module_loaded();
1028            if !matches!(projection, ImportProjection::MaterializeOnly) {
1029                let _load_span = self.module_load_span();
1030                self.apply_import_projection(&canonical, &loaded, projection)?;
1031            }
1032
1033            // Once the import stack fully unwinds, every module reachable from
1034            // this top-level import is cached, so any deferred cyclic imports
1035            // can now bind against fully-loaded modules.
1036            if self.imported_paths.is_empty() {
1037                let _load_span = self.module_load_span();
1038                self.flush_deferred_cyclic_imports()?;
1039            }
1040
1041            Ok(())
1042        })
1043    }
1044
1045    /// Resolve a module the link table names, without reading its source.
1046    ///
1047    /// `content_hash` comes from a manifest that was re-checked before the table
1048    /// was built, so it describes the bytes currently on disk. That is the whole
1049    /// licence for skipping the read: the digest is not being trusted about the
1050    /// file's identity, only reused instead of recomputed from bytes already
1051    /// proven unchanged.
1052    ///
1053    /// `None` means the table could not be honoured — most often the artifact was
1054    /// evicted from a shared cache directory between spawns. The caller then reads
1055    /// and compiles as usual, which is correct, just slower.
1056    fn linked_module_artifact(
1057        &self,
1058        file_path: &Path,
1059        canonical: &Path,
1060        content_hash: [u8; 32],
1061    ) -> Option<Arc<PreparedModuleArtifact>> {
1062        if !bytecode_cache::cache_enabled() {
1063            return None;
1064        }
1065        if let Some(prepared) = self.prepared_module_cache.get(canonical, content_hash) {
1066            return Some(prepared);
1067        }
1068        let key = bytecode_cache::CacheKey::from_module_content_hash(content_hash);
1069        let artifact = bytecode_cache::load_module_for_key(file_path, key).artifact?;
1070        Some(self.prepared_module_cache.insert(
1071            canonical.to_path_buf(),
1072            content_hash,
1073            Arc::new(PreparedModuleArtifact::from_cached(artifact)),
1074        ))
1075    }
1076
1077    /// Bind imports that were deferred because their target module was still
1078    /// mid-load (an import cycle). By the time the import stack has unwound,
1079    /// both the importing and target modules are fully instantiated and cached,
1080    /// so we can resolve the requested names against the target and define them
1081    /// into the importer's shared, mutable `module_state`. That env is the one
1082    /// every closure from the importing module consults (after its local env)
1083    /// at call time, so the late binding becomes visible without needing to
1084    /// rewrite the closures' captured lexical snapshots.
1085    fn flush_deferred_cyclic_imports(&mut self) -> Result<(), VmError> {
1086        if self.deferred_cyclic_imports.is_empty() {
1087            return Ok(());
1088        }
1089        let deferred = std::mem::take(&mut self.deferred_cyclic_imports);
1090        let mut still_pending = Vec::new();
1091        for import in deferred {
1092            let (Some(importer), Some(target)) = (
1093                self.module_cache.get(&import.importer).cloned(),
1094                self.module_cache.get(&import.target).cloned(),
1095            ) else {
1096                // One endpoint is not cached yet (a lazy import inside a
1097                // function body can defer before the other side loads). Keep
1098                // it for a later flush.
1099                still_pending.push(import);
1100                continue;
1101            };
1102
1103            let mut module_state = importer._module_state.lock();
1104            if let Some(alias) = &import.namespace_alias {
1105                if module_state.get(alias).is_none() {
1106                    let dict = build_namespace_dict(&import.target.display().to_string(), &target);
1107                    module_state.define(alias, dict, false)?;
1108                }
1109                continue;
1110            }
1111
1112            let export_names = module_import_names(
1113                &import.target.display().to_string(),
1114                &target,
1115                import.selected_names.as_deref(),
1116            )?;
1117
1118            for name in export_names {
1119                // A real local declaration (or an already-bound non-cyclic
1120                // import) wins over the cyclic re-binding.
1121                if module_state.get(&name).is_some() {
1122                    continue;
1123                }
1124                if let Some(closure) = target.functions.get(&name) {
1125                    module_state.define(&name, VmValue::Closure(Arc::clone(closure)), false)?;
1126                } else if let Some(value) = target.public_values.get(&name) {
1127                    // Init-backed public declarations imported across a cycle.
1128                    module_state.define(&name, value.clone(), false)?;
1129                } else if target
1130                    .public_exports
1131                    .get(&name)
1132                    .is_some_and(|kind| !kind.has_runtime_value())
1133                {
1134                    // Type-only public declarations carry no runtime binding.
1135                    continue;
1136                } else {
1137                    return Err(VmError::Runtime(format!(
1138                        "Import error: '{name}' is not defined in {}",
1139                        import.target.display()
1140                    )));
1141                }
1142            }
1143        }
1144        self.deferred_cyclic_imports = still_pending;
1145        Ok(())
1146    }
1147
1148    /// Return the path key that `execute_import` would use to cache the
1149    /// LoadedModule for this import string. Used by the re-export pass to
1150    /// look up the already-loaded source module after `execute_import`
1151    /// has populated [`Vm::module_cache`].
1152    fn cache_key_for_import(&self, path: &str) -> Result<PathBuf, VmError> {
1153        if let Some(module) = path
1154            .strip_prefix("std/")
1155            .or_else(|| (path == "observability").then_some("observability"))
1156        {
1157            return Ok(PathBuf::from(format!("<stdlib>/{module}.harn")));
1158        }
1159        let base = self
1160            .source_dir
1161            .clone()
1162            .unwrap_or_else(|| PathBuf::from("."));
1163        let file_path = self.resolve_module_import_path(&base, path)?;
1164        Ok(file_path.canonicalize().unwrap_or(file_path))
1165    }
1166
1167    async fn loaded_module_for_path(
1168        &mut self,
1169        path: &Path,
1170    ) -> Result<(PathBuf, Arc<LoadedModule>), VmError> {
1171        self.ensure_execution_available()?;
1172        let path_str = path.to_string_lossy().into_owned();
1173        self.materialize_import(&path_str).await?;
1174
1175        let mut file_path = if path.is_absolute() {
1176            path.to_path_buf()
1177        } else {
1178            self.source_dir
1179                .clone()
1180                .unwrap_or_else(|| PathBuf::from("."))
1181                .join(path)
1182        };
1183        if !file_path.exists() && file_path.extension().is_none() {
1184            file_path.set_extension("harn");
1185        }
1186
1187        let canonical = file_path
1188            .canonicalize()
1189            .unwrap_or_else(|_| file_path.clone());
1190        let loaded = self.module_cache.get(&canonical).cloned().ok_or_else(|| {
1191            VmError::Runtime(format!(
1192                "Import error: failed to cache loaded module '{}'",
1193                canonical.display()
1194            ))
1195        })?;
1196        Ok((canonical, loaded))
1197    }
1198
1199    /// Load one explicitly public callable from a module.
1200    pub async fn load_public_module_callable(
1201        &mut self,
1202        path: &Path,
1203        name: &str,
1204    ) -> Result<Arc<VmClosure>, VmError> {
1205        let (canonical, loaded) = self.loaded_module_for_path(path).await?;
1206        if !loaded.public_exports.contains_key(name) {
1207            let hint = if loaded.functions.contains_key(name) {
1208                "; it is defined there but not `pub`"
1209            } else {
1210                ""
1211            };
1212            return Err(VmError::Runtime(format!(
1213                "callable '{name}' is not exported by module '{}'{hint}",
1214                canonical.display()
1215            )));
1216        }
1217        loaded.functions.get(name).cloned().ok_or_else(|| {
1218            VmError::Runtime(format!(
1219                "Import error: exported callable '{name}' is missing from {}",
1220                canonical.display()
1221            ))
1222        })
1223    }
1224
1225    /// Load a module file and return the exported function closures that
1226    /// would be visible to a wildcard import.
1227    pub async fn load_module_exports(
1228        &mut self,
1229        path: &Path,
1230    ) -> Result<BTreeMap<String, Arc<VmClosure>>, VmError> {
1231        let (canonical, loaded) = self.loaded_module_for_path(path).await?;
1232        exported_function_closures(&loaded, &canonical)
1233    }
1234
1235    /// Load synthetic source keyed by a synthetic module path and return
1236    /// the exported function closures that a wildcard import would expose.
1237    pub async fn load_module_exports_from_source(
1238        &mut self,
1239        source_key: impl Into<PathBuf>,
1240        source: &str,
1241    ) -> Result<BTreeMap<String, Arc<VmClosure>>, VmError> {
1242        self.ensure_execution_available()?;
1243        let synthetic = source_key.into();
1244        let loaded = self
1245            .load_module_from_source(synthetic.clone(), source)
1246            .await?;
1247        exported_function_closures(&loaded, &synthetic)
1248    }
1249
1250    /// Load one callable from synthetic source for a host dispatch surface
1251    /// that has already selected the callable through its own policy. This is
1252    /// deliberately separate from module exports: script imports must
1253    /// continue to see only declarations in the typed public export contract.
1254    pub async fn load_module_callable_from_source(
1255        &mut self,
1256        source_key: impl Into<PathBuf>,
1257        source: &str,
1258        name: &str,
1259    ) -> Result<Option<Arc<VmClosure>>, VmError> {
1260        self.ensure_execution_available()?;
1261        let synthetic = source_key.into();
1262        let loaded = self.load_module_from_source(synthetic, source).await?;
1263        Ok(loaded.functions.get(name).cloned())
1264    }
1265
1266    /// Load a module by import path (`std/foo`, relative module path, or
1267    /// package import) and return the exported function closures that a
1268    /// wildcard import would expose.
1269    pub async fn load_module_exports_from_import(
1270        &mut self,
1271        import_path: &str,
1272    ) -> Result<BTreeMap<String, Arc<VmClosure>>, VmError> {
1273        self.ensure_execution_available()?;
1274        self.materialize_import(import_path).await?;
1275
1276        if let Some(module) = import_path
1277            .strip_prefix("std/")
1278            .or_else(|| (import_path == "observability").then_some("observability"))
1279        {
1280            let synthetic = PathBuf::from(format!("<stdlib>/{module}.harn"));
1281            let loaded = self.module_cache.get(&synthetic).cloned().ok_or_else(|| {
1282                VmError::Runtime(format!(
1283                    "Import error: failed to cache loaded module '{}'",
1284                    synthetic.display()
1285                ))
1286            })?;
1287            return exported_function_closures(&loaded, &synthetic);
1288        }
1289
1290        let base = self
1291            .source_dir
1292            .clone()
1293            .unwrap_or_else(|| PathBuf::from("."));
1294        let file_path = self.resolve_module_import_path(&base, import_path)?;
1295        self.load_module_exports(&file_path).await
1296    }
1297}
1298
1299#[cfg(test)]
1300#[path = "modules_tests.rs"]
1301mod tests;