Skip to main content

vibe/
module_system.rs

1//! Module system — `import <iri> as name` with a module graph (T63).
2//!
3//! No npm. No `vibe.toml` dependency solver in 0.x. The catalog IS
4//! the module graph — modules declare their IRI, exports, and
5//! dependencies, and the resolver walks the graph to find them.
6//!
7//! ## Design
8//!
9//! - **ModuleId**: An IRI that uniquely identifies a module
10//!   (e.g. `https://qualiadb.org/modules/math`).
11//! - **ModuleEntry**: Metadata for a module — IRI, version, exports
12//!   (function names and types), dependencies (other module IRIs).
13//! - **ModuleCatalog**: The module graph — a collection of ModuleEntries
14//!   with dependency edges. Supports cycle detection.
15//! - **ModuleResolver**: Resolves an import IRI to a ModuleEntry,
16//!   checking the catalog first, then falling back to the host.
17//!
18//! The catalog is built at host startup from the modules the host
19//! has available. Scripts import modules by IRI; the resolver checks
20//! the catalog and returns the entry (or an error if not found).
21//!
22//! Reference: `docs/vibescript-full-impl-PLAN.md` §8.13 T63,
23//! excellence-first §2.7, ecosystem §3.4.
24
25use std::collections::BTreeMap;
26
27/// A module identifier — an IRI that uniquely identifies a module (T63).
28#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
29pub struct ModuleId(pub String);
30
31impl ModuleId {
32    /// Creates a new `ModuleId`.
33    pub fn new(iri: &str) -> Self {
34        Self(iri.into())
35    }
36
37    /// `str` form.
38    pub fn as_str(&self) -> &str {
39        &self.0
40    }
41}
42
43impl std::fmt::Display for ModuleId {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        write!(f, "{}", self.0)
46    }
47}
48
49/// A module export — a function or capability the module provides (T63).
50#[derive(Debug, Clone, PartialEq)]
51pub struct ModuleExport {
52    /// The exported name (e.g. "abs", "max", "sha256").
53    pub name: String,
54    /// The export kind — function, capability, or type.
55    pub kind: ExportKind,
56    /// Optional type signature (for machine schema).
57    pub signature: Option<String>,
58}
59
60/// The kind of module export (T63).
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum ExportKind {
63    /// A function export.
64    Function,
65    /// A capability export.
66    Capability,
67    /// A type export.
68    Type,
69}
70
71impl ExportKind {
72    /// `str` form.
73    pub fn as_str(&self) -> &'static str {
74        match self {
75            Self::Function => "function",
76            Self::Capability => "capability",
77            Self::Type => "type",
78        }
79    }
80}
81
82/// A module entry — metadata for a module in the catalog (T63).
83#[derive(Debug, Clone, PartialEq)]
84pub struct ModuleEntry {
85    /// The module's IRI — its unique identifier.
86    pub id: ModuleId,
87    /// The module's version (semver-ish, e.g. "0.1.0").
88    pub version: String,
89    /// What the module exports.
90    pub exports: Vec<ModuleExport>,
91    /// What the module depends on (other module IRIs).
92    pub dependencies: Vec<ModuleId>,
93    /// Optional description.
94    pub description: String,
95    /// Whether this is a built-in module (shipped with the host).
96    pub is_builtin: bool,
97}
98
99impl ModuleEntry {
100    /// Create a new module entry.
101    pub fn new(id: &str, version: &str) -> Self {
102        Self {
103            id: ModuleId::new(id),
104            version: version.into(),
105            exports: Vec::new(),
106            dependencies: Vec::new(),
107            description: String::new(),
108            is_builtin: false,
109        }
110    }
111
112    /// Add an export.
113    pub fn with_export(mut self, export: ModuleExport) -> Self {
114        self.exports.push(export);
115        self
116    }
117
118    /// Add a dependency.
119    pub fn with_dependency(mut self, dep: &str) -> Self {
120        self.dependencies.push(ModuleId::new(dep));
121        self
122    }
123
124    /// Add a description.
125    pub fn with_description(mut self, desc: &str) -> Self {
126        self.description = desc.into();
127        self
128    }
129
130    /// Mark as built-in.
131    pub fn builtin(mut self) -> Self {
132        self.is_builtin = true;
133        self
134    }
135
136    /// Check if this module exports a given name.
137    pub fn exports_name(&self, name: &str) -> bool {
138        self.exports.iter().any(|e| e.name == name)
139    }
140
141    /// Get all function exports.
142    pub fn functions(&self) -> Vec<&ModuleExport> {
143        self.exports
144            .iter()
145            .filter(|e| e.kind == ExportKind::Function)
146            .collect()
147    }
148
149    /// Get all capability exports.
150    pub fn capabilities(&self) -> Vec<&ModuleExport> {
151        self.exports
152            .iter()
153            .filter(|e| e.kind == ExportKind::Capability)
154            .collect()
155    }
156}
157
158/// A module catalog — the module graph (T63).
159///
160/// Tracks all known modules and their dependency edges. Supports
161/// cycle detection and topological ordering for loading.
162#[derive(Debug, Clone, Default)]
163pub struct ModuleCatalog {
164    modules: BTreeMap<String, ModuleEntry>,
165}
166
167impl ModuleCatalog {
168    /// Creates a new `ModuleCatalog`.
169    pub fn new() -> Self {
170        Self::default()
171    }
172
173    /// Register a module in the catalog.
174    pub fn register(&mut self, entry: ModuleEntry) -> &mut Self {
175        self.modules.insert(entry.id.as_str().into(), entry);
176        self
177    }
178
179    /// Get a module by IRI.
180    pub fn get(&self, iri: &str) -> Option<&ModuleEntry> {
181        self.modules.get(iri)
182    }
183
184    /// Get all modules.
185    pub fn all(&self) -> Vec<&ModuleEntry> {
186        self.modules.values().collect()
187    }
188
189    /// Get all built-in modules.
190    pub fn builtins(&self) -> Vec<&ModuleEntry> {
191        self.modules.values().filter(|m| m.is_builtin).collect()
192    }
193
194    /// Number of modules.
195    pub fn len(&self) -> usize {
196        self.modules.len()
197    }
198
199    /// Is the catalog empty?
200    pub fn is_empty(&self) -> bool {
201        self.modules.is_empty()
202    }
203
204    /// Check if a dependency cycle exists starting from the given module.
205    /// Returns the cycle path if found, or None if no cycle.
206    pub fn detect_cycle(&self, start: &str) -> Option<Vec<String>> {
207        let mut visited = std::collections::HashSet::new();
208        let mut path = Vec::new();
209        self.dfs_cycle(start, &mut visited, &mut path)
210    }
211
212    fn dfs_cycle(
213        &self,
214        current: &str,
215        visited: &mut std::collections::HashSet<String>,
216        path: &mut Vec<String>,
217    ) -> Option<Vec<String>> {
218        if path.contains(&current.to_string()) {
219            // Found a cycle — extract the cycle portion
220            let cycle_start = path.iter().position(|p| p == current).unwrap();
221            let mut cycle = path[cycle_start..].to_vec();
222            cycle.push(current.into());
223            return Some(cycle);
224        }
225        if visited.contains(current) {
226            return None;
227        }
228        visited.insert(current.into());
229        path.push(current.into());
230        if let Some(entry) = self.modules.get(current) {
231            for dep in &entry.dependencies {
232                if let Some(cycle) = self.dfs_cycle(dep.as_str(), visited, path) {
233                    return Some(cycle);
234                }
235            }
236        }
237        path.pop();
238        None
239    }
240
241    /// Get the topological order of all modules (for loading).
242    /// Returns Err with the cycle path if a cycle is detected.
243    pub fn topological_order(&self) -> Result<Vec<String>, Vec<String>> {
244        let mut order = Vec::new();
245        let mut visited = std::collections::HashSet::new();
246        let mut in_progress = std::collections::HashSet::new();
247
248        for iri in self.modules.keys() {
249            if !visited.contains(iri) {
250                self.topo_dfs(iri, &mut visited, &mut in_progress, &mut order)?;
251            }
252        }
253        Ok(order)
254    }
255
256    fn topo_dfs(
257        &self,
258        current: &str,
259        visited: &mut std::collections::HashSet<String>,
260        in_progress: &mut std::collections::HashSet<String>,
261        order: &mut Vec<String>,
262    ) -> Result<(), Vec<String>> {
263        if visited.contains(current) {
264            return Ok(());
265        }
266        if in_progress.contains(current) {
267            // Cycle detected
268            return Err(vec![current.into()]);
269        }
270        in_progress.insert(current.into());
271        if let Some(entry) = self.modules.get(current) {
272            for dep in &entry.dependencies {
273                self.topo_dfs(dep.as_str(), visited, in_progress, order)?;
274            }
275        }
276        in_progress.remove(current);
277        visited.insert(current.into());
278        order.push(current.into());
279        Ok(())
280    }
281}
282
283/// A module resolver — resolves an import IRI to a module entry (T63).
284pub struct ModuleResolver<'a> {
285    catalog: &'a ModuleCatalog,
286}
287
288impl<'a> ModuleResolver<'a> {
289    /// Creates a new `ModuleResolver`.
290    pub fn new(catalog: &'a ModuleCatalog) -> Self {
291        Self { catalog }
292    }
293
294    /// Resolve an import IRI to a module entry.
295    pub fn resolve(&self, iri: &str) -> Result<&ModuleEntry, String> {
296        self.catalog
297            .get(iri)
298            .ok_or_else(|| format!("module not found in catalog: {iri}"))
299    }
300
301    /// Resolve an import with a stripped `vibe:0.1/` prefix (T64).
302    pub fn resolve_import(&self, path: &str) -> Result<&ModuleEntry, String> {
303        // Strip optional vibe:0.1/ prefix (T64)
304        let stripped = path.strip_prefix("vibe:0.1/").unwrap_or(path);
305        self.resolve(stripped)
306    }
307
308    /// Check if all dependencies of a module are in the catalog.
309    pub fn check_dependencies(&self, iri: &str) -> Result<(), Vec<String>> {
310        let entry = self.resolve(iri).map_err(|e| vec![e])?;
311        let mut missing = Vec::new();
312        for dep in &entry.dependencies {
313            if self.catalog.get(dep.as_str()).is_none() {
314                missing.push(dep.as_str().into());
315            }
316        }
317        if missing.is_empty() {
318            Ok(())
319        } else {
320            Err(missing)
321        }
322    }
323}
324
325/// Create a default catalog with built-in modules (T63).
326pub fn default_catalog() -> ModuleCatalog {
327    let mut catalog = ModuleCatalog::new();
328
329    // Math module
330    catalog.register(
331        ModuleEntry::new("math", "0.1.0")
332            .builtin()
333            .with_description(
334                "Pure math functions: abs, min, max, floor, ceil, round, sqrt, sin, cos, log, exp",
335            )
336            .with_export(ModuleExport {
337                name: "abs".into(),
338                kind: ExportKind::Function,
339                signature: Some("(x: number) -> number".into()),
340            })
341            .with_export(ModuleExport {
342                name: "max".into(),
343                kind: ExportKind::Function,
344                signature: Some("(a: number, b: number) -> number".into()),
345            })
346            .with_export(ModuleExport {
347                name: "min".into(),
348                kind: ExportKind::Function,
349                signature: Some("(a: number, b: number) -> number".into()),
350            })
351            .with_export(ModuleExport {
352                name: "sqrt".into(),
353                kind: ExportKind::Function,
354                signature: Some("(x: number) -> f64".into()),
355            })
356            .with_export(ModuleExport {
357                name: "pow".into(),
358                kind: ExportKind::Function,
359                signature: Some("(base: number, exp: number) -> f64".into()),
360            })
361            .with_export(ModuleExport {
362                name: "log10".into(),
363                kind: ExportKind::Function,
364                signature: Some("(x: number) -> f64".into()),
365            })
366            .with_export(ModuleExport {
367                name: "tan".into(),
368                kind: ExportKind::Function,
369                signature: Some("(x: number) -> f64".into()),
370            })
371            .with_export(ModuleExport {
372                name: "atan".into(),
373                kind: ExportKind::Function,
374                signature: Some("(x: number) -> f64".into()),
375            })
376            .with_export(ModuleExport {
377                name: "atan2".into(),
378                kind: ExportKind::Function,
379                signature: Some("(y: number, x: number) -> f64".into()),
380            }),
381    );
382
383    // Time module
384    catalog.register(
385        ModuleEntry::new("time", "0.1.0")
386            .builtin()
387            .with_description("Time primitives: now, monotonic_nanos, proper_time")
388            .with_export(ModuleExport {
389                name: "now".into(),
390                kind: ExportKind::Function,
391                signature: Some("() -> Instant".into()),
392            }),
393    );
394
395    // Graph module
396    catalog.register(
397        ModuleEntry::new("graph", "0.1.0")
398            .builtin()
399            .with_description("Graph operations: query, stage, commit, snapshot")
400            .with_export(ModuleExport {
401                name: "query".into(),
402                kind: ExportKind::Function,
403                signature: Some("(query: string) -> Value".into()),
404            })
405            .with_export(ModuleExport {
406                name: "commit".into(),
407                kind: ExportKind::Function,
408                signature: Some("() -> Value".into()),
409            }),
410    );
411
412    // Crypto module
413    catalog.register(
414        ModuleEntry::new("crypto", "0.1.0")
415            .builtin()
416            .with_description(
417                "Cryptographic operations: sha256, sha512, blake3, hkdf, aead, sign, verify",
418            )
419            .with_export(ModuleExport {
420                name: "sha256".into(),
421                kind: ExportKind::Function,
422                signature: Some("(data: bytes) -> HashResult".into()),
423            }),
424    );
425
426    // ZK module
427    catalog.register(
428        ModuleEntry::new("zk", "0.1.0")
429            .builtin()
430            .with_description("Zero-knowledge proofs: threshold, range, matmul")
431            .with_export(ModuleExport {
432                name: "prove_threshold".into(),
433                kind: ExportKind::Function,
434                signature: Some("(value: f64, threshold: f64) -> ZkProof".into()),
435            }),
436    );
437
438    // HID module
439    catalog.register(
440        ModuleEntry::new("hid", "0.1.0")
441            .builtin()
442            .with_description("HID events: poll, wait")
443            .with_export(ModuleExport {
444                name: "poll".into(),
445                kind: ExportKind::Function,
446                signature: Some("() -> Value".into()),
447            }),
448    );
449
450    catalog
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456
457    #[test]
458    fn t63_default_catalog_has_builtins() {
459        let catalog = default_catalog();
460        assert!(catalog.len() >= 5);
461        assert!(catalog.get("math").is_some());
462        assert!(catalog.get("time").is_some());
463        assert!(catalog.get("graph").is_some());
464        assert!(catalog.get("crypto").is_some());
465        assert!(catalog.get("zk").is_some());
466    }
467
468    #[test]
469    fn t63_module_entry_exports() {
470        let entry = ModuleEntry::new("math", "0.1.0").with_export(ModuleExport {
471            name: "abs".into(),
472            kind: ExportKind::Function,
473            signature: None,
474        });
475        assert!(entry.exports_name("abs"));
476        assert!(!entry.exports_name("nonexistent"));
477        assert_eq!(entry.functions().len(), 1);
478    }
479
480    #[test]
481    fn t63_resolver_resolves_builtin() {
482        let catalog = default_catalog();
483        let resolver = ModuleResolver::new(&catalog);
484        let entry = resolver.resolve("math").unwrap();
485        assert_eq!(entry.id.as_str(), "math");
486        assert!(entry.is_builtin);
487    }
488
489    #[test]
490    fn t63_resolver_strips_vibe_prefix() {
491        let catalog = default_catalog();
492        let resolver = ModuleResolver::new(&catalog);
493        let entry = resolver.resolve_import("vibe:0.1/math").unwrap();
494        assert_eq!(entry.id.as_str(), "math");
495    }
496
497    #[test]
498    fn t63_resolver_fails_for_unknown() {
499        let catalog = default_catalog();
500        let resolver = ModuleResolver::new(&catalog);
501        assert!(resolver.resolve("nonexistent").is_err());
502    }
503
504    #[test]
505    fn t63_check_dependencies_ok() {
506        let mut catalog = ModuleCatalog::new();
507        catalog.register(ModuleEntry::new("a", "0.1.0").with_dependency("b"));
508        catalog.register(ModuleEntry::new("b", "0.1.0"));
509        let resolver = ModuleResolver::new(&catalog);
510        assert!(resolver.check_dependencies("a").is_ok());
511    }
512
513    #[test]
514    fn t63_check_dependencies_missing() {
515        let mut catalog = ModuleCatalog::new();
516        catalog.register(ModuleEntry::new("a", "0.1.0").with_dependency("b"));
517        // b is not registered
518        let resolver = ModuleResolver::new(&catalog);
519        let result = resolver.check_dependencies("a");
520        assert!(result.is_err());
521        assert_eq!(result.unwrap_err(), vec!["b"]);
522    }
523
524    #[test]
525    fn t63_detect_cycle_no_cycle() {
526        let mut catalog = ModuleCatalog::new();
527        catalog.register(ModuleEntry::new("a", "0.1.0").with_dependency("b"));
528        catalog.register(ModuleEntry::new("b", "0.1.0"));
529        assert!(catalog.detect_cycle("a").is_none());
530    }
531
532    #[test]
533    fn t63_detect_cycle_with_cycle() {
534        let mut catalog = ModuleCatalog::new();
535        catalog.register(ModuleEntry::new("a", "0.1.0").with_dependency("b"));
536        catalog.register(ModuleEntry::new("b", "0.1.0").with_dependency("c"));
537        catalog.register(ModuleEntry::new("c", "0.1.0").with_dependency("a"));
538        let cycle = catalog.detect_cycle("a");
539        assert!(cycle.is_some());
540        let cycle = cycle.unwrap();
541        assert!(cycle.len() >= 3);
542    }
543
544    #[test]
545    fn t63_topological_order() {
546        let mut catalog = ModuleCatalog::new();
547        catalog.register(ModuleEntry::new("a", "0.1.0").with_dependency("b"));
548        catalog.register(ModuleEntry::new("b", "0.1.0").with_dependency("c"));
549        catalog.register(ModuleEntry::new("c", "0.1.0"));
550        let order = catalog.topological_order().unwrap();
551        // c should come before b, b before a
552        let c_pos = order.iter().position(|x| x == "c").unwrap();
553        let b_pos = order.iter().position(|x| x == "b").unwrap();
554        let a_pos = order.iter().position(|x| x == "a").unwrap();
555        assert!(c_pos < b_pos);
556        assert!(b_pos < a_pos);
557    }
558
559    #[test]
560    fn t63_topological_order_with_cycle_fails() {
561        let mut catalog = ModuleCatalog::new();
562        catalog.register(ModuleEntry::new("a", "0.1.0").with_dependency("b"));
563        catalog.register(ModuleEntry::new("b", "0.1.0").with_dependency("a"));
564        assert!(catalog.topological_order().is_err());
565    }
566
567    #[test]
568    fn t63_module_id_display() {
569        let id = ModuleId::new("https://qualiadb.org/modules/math");
570        assert_eq!(id.to_string(), "https://qualiadb.org/modules/math");
571    }
572
573    #[test]
574    fn t63_export_kind_as_str() {
575        assert_eq!(ExportKind::Function.as_str(), "function");
576        assert_eq!(ExportKind::Capability.as_str(), "capability");
577        assert_eq!(ExportKind::Type.as_str(), "type");
578    }
579
580    #[test]
581    fn t63_catalog_builtins() {
582        let catalog = default_catalog();
583        let builtins = catalog.builtins();
584        assert!(builtins.len() >= 5);
585        for b in builtins {
586            assert!(b.is_builtin);
587        }
588    }
589
590    #[test]
591    fn t63_module_entry_capabilities() {
592        let entry = ModuleEntry::new("graph", "0.1.0")
593            .with_export(ModuleExport {
594                name: "query".into(),
595                kind: ExportKind::Function,
596                signature: None,
597            })
598            .with_export(ModuleExport {
599                name: "graph.write".into(),
600                kind: ExportKind::Capability,
601                signature: None,
602            });
603        assert_eq!(entry.functions().len(), 1);
604        assert_eq!(entry.capabilities().len(), 1);
605    }
606}