Skip to main content

ggen_core/
pack_resolver.rs

1//! μ₀: Pack Resolution Stage
2//!
3//! This module implements the μ₀ stage of the generation pipeline, which resolves
4//! packs from the lockfile, expands bundles to atomic packs, checks compatibility,
5//! merges pack ontologies, and builds ownership maps for conflict detection.
6//!
7//! ## μ₀ Stage Responsibilities
8//!
9//! 1. **Read lockfile** - Load requested packs/bundles from `.ggen/packs.lock`
10//! 2. **Expand bundles** - Convert bundle aliases to atomic pack IDs
11//! 3. **Resolve dependencies** - Transitively resolve all pack dependencies
12//! 4. **Check compatibility** - Multi-dimensional conflict detection
13//! 5. **Merge ontologies** - Combine RDF graphs from all packs
14//! 6. **Build ownership map** - Track artifact ownership for conflict detection
15//!
16//! ## Output
17//!
18//! The μ₀ stage produces `ResolvedPacks`, which contains:
19//! - `atomic_packs`: The complete set of atomic pack IDs
20//! - `merged_ontology`: Combined RDF graph from all packs
21//! - `ownership_map`: Ownership declarations for conflict detection
22//! - `queries` / `templates`: Contributed SPARQL (CONSTRUCT) and Tera sources for μ₂ / staging
23//!
24//! ## Integration
25//!
26//! This stage runs **before** μ₁ (normalization) in the pipeline:
27//!
28//! ```text
29//! μ₀ (pack resolution) → μ₁ (normalization) → μ₂ (extraction) → μ₃ (emission) → μ₄ (canonicalization) → μ₅ (receipt)
30//! ```
31use crate::bail;
32
33use crate::graph::Graph;
34use crate::marketplace::atomic::{foundation_packs, AtomicPackId};
35use crate::marketplace::bundle::Bundle;
36use crate::marketplace::metadata::load_pack_metadata;
37use crate::marketplace::ownership::{
38    MergeStrategy, OwnershipClass, OwnershipDeclaration, OwnershipMap, OwnershipTarget,
39};
40use crate::marketplace::policy::{PackContext, PolicyEnforcer};
41use crate::marketplace::profile::get_profile;
42use crate::packs::lockfile::PackLockfile;
43use crate::utils::error::{Error, Result};
44use serde::{Deserialize, Serialize};
45use std::collections::{HashMap, HashSet};
46use std::path::{Path, PathBuf};
47use std::sync::Arc;
48
49/// SPARQL query contributed by a pack.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct SparqlQuery {
52    /// Query name (for binding lookup)
53    pub name: String,
54    /// SPARQL query string
55    pub sparql: String,
56}
57
58/// Tera template contributed by a pack.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct TemplateDef {
61    /// Relative path to template file
62    pub path: PathBuf,
63    /// Template content
64    pub content: String,
65}
66
67/// Resolution result from μ₀ stage.
68///
69/// Contains the complete set of resolved atomic packs, their merged ontology,
70/// and ownership information for conflict detection.
71#[derive(Clone)]
72pub struct ResolvedPacks {
73    /// Complete set of atomic pack IDs (after bundle expansion and dependency resolution)
74    pub atomic_packs: Vec<AtomicPackId>,
75
76    /// Merged RDF ontology from all packs
77    pub merged_ontology: Graph,
78
79    /// Ownership declarations for conflict detection
80    pub ownership_map: OwnershipMap,
81
82    /// Bundle expansions performed (for provenance)
83    pub bundle_expansions: Vec<BundleExpansion>,
84
85    /// Pack versions resolved (for lockfile updates)
86    pub pack_versions: HashMap<String, String>,
87
88    /// Policy profile used for enforcement
89    pub profile: String,
90
91    /// SPARQL queries loaded from packs (μ₂; CONSTRUCT-only — see `PACK_QUERY_CONTRACT.md`)
92    pub queries: Vec<SparqlQuery>,
93
94    /// Tera templates loaded from packs (staged under `.ggen/pack-stage/` during sync)
95    pub templates: Vec<TemplateDef>,
96
97    /// Ed25519 signatures per pack (hex strings), loaded from pack metadata.
98    pub pack_signatures: HashMap<String, String>,
99
100    /// SHA-256 checksums per pack, loaded from pack metadata.
101    pub pack_checksums: HashMap<String, String>,
102
103    /// Registry types per pack (e.g., "npm", "crates.io"), loaded from pack metadata.
104    pub pack_registry_types: HashMap<String, String>,
105
106    /// Origin URLs per pack, loaded from pack metadata.
107    pub pack_origin_urls: HashMap<String, String>,
108}
109
110/// Record of a bundle expansion (for provenance in receipts).
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct BundleExpansion {
113    /// Bundle ID that was expanded
114    pub bundle_id: String,
115
116    /// Atomic packs it expanded to
117    pub expanded_to: Vec<String>,
118}
119
120impl ResolvedPacks {
121    /// Deterministic digest of pack queries + templates for one atomic pack (receipt provenance).
122    pub fn digest_for_pack(&self, pack: &AtomicPackId) -> String {
123        use sha2::{Digest, Sha256};
124        let pid = pack.to_string();
125        let prefix_q = format!("{}::", pid);
126        let mut h = Sha256::new();
127        for q in &self.queries {
128            if q.name.starts_with(&prefix_q) {
129                h.update(q.name.as_bytes());
130                h.update([0_u8]);
131                h.update(q.sparql.as_bytes());
132            }
133        }
134        let path_prefix = format!("{}/", pid);
135        for t in &self.templates {
136            let ps = t.path.display().to_string();
137            if ps.starts_with(&path_prefix) {
138                h.update(ps.as_bytes());
139                h.update([0_u8]);
140                h.update(t.content.as_bytes());
141            }
142        }
143        format!("sha256:{:x}", h.finalize())
144    }
145
146    /// Query names contributed by `pack` (`<pack>::<stem>`).
147    pub fn query_names_for_pack(&self, pack: &AtomicPackId) -> Vec<String> {
148        let p = format!("{}::", pack);
149        self.queries
150            .iter()
151            .filter(|q| q.name.starts_with(&p))
152            .map(|q| q.name.clone())
153            .collect()
154    }
155
156    /// Template relative paths for `pack` under the pack cache layout.
157    pub fn template_paths_for_pack(&self, pack: &AtomicPackId) -> Vec<String> {
158        let prefix = format!("{}/", pack);
159        self.templates
160            .iter()
161            .filter(|t| t.path.display().to_string().starts_with(&prefix))
162            .map(|t| t.path.display().to_string())
163            .collect()
164    }
165}
166
167/// μ₀ Pack Resolver
168///
169/// Resolves packs from lockfile, expands bundles, checks compatibility,
170/// merges ontologies, and builds ownership maps.
171pub struct PackResolver {
172    /// Lockfile path (.ggen/packs.lock)
173    #[allow(dead_code)]
174    lockfile_path: PathBuf,
175
176    /// Registry for loading pack metadata
177    registry: Arc<PackRegistry>,
178}
179
180impl PackResolver {
181    /// Create a new pack resolver for the given project.
182    ///
183    /// # Arguments
184    ///
185    /// * `project_dir` - Path to project directory (contains `.ggen/`)
186    ///
187    /// # Errors
188    ///
189    /// Returns error if project directory doesn't exist.
190    pub fn new(project_dir: &Path) -> Result<Self> {
191        let project_dir = project_dir
192            .canonicalize()
193            .map_err(|e| Error::new(&format!("Invalid project directory: {}", e)))?;
194
195        let lockfile_path = project_dir.join(".ggen").join("packs.lock");
196        let cache_dir = std::env::var_os("GGEN_PACK_CACHE_DIR")
197            .map(PathBuf::from)
198            .or_else(|| dirs::home_dir().map(|h| h.join(".ggen").join("packs")))
199            .ok_or_else(|| {
200                Error::new("Cannot resolve pack cache directory: set HOME or GGEN_PACK_CACHE_DIR")
201            })?;
202
203        Ok(Self {
204            lockfile_path,
205            registry: Arc::new(PackRegistry::new(cache_dir)?),
206        })
207    }
208
209    /// Resolve packs from lockfile (μ₀ stage).
210    ///
211    /// This is the main entry point for μ₀. It performs the complete
212    /// pack resolution pipeline:
213    ///
214    /// 1. Read lockfile
215    /// 2. Expand bundles to atomic packs
216    /// 3. Resolve dependencies transitively
217    /// 4. Check multi-dimensional compatibility
218    /// 5. Enforce policy profiles
219    /// 6. Merge pack ontologies
220    /// 7. Build ownership map
221    ///
222    /// # Errors
223    ///
224    /// Returns error if:
225    /// - Lockfile not found or invalid
226    /// - Bundle expansion fails
227    /// - Dependency resolution fails
228    /// - Compatibility check fails
229    /// - Policy enforcement fails (error-level violations)
230    /// - Ontology merge fails
231    /// - Ownership conflict detected
232    pub fn resolve(&self) -> Result<ResolvedPacks> {
233        // Step 1: Read lockfile
234        let lockfile = self.read_lockfile()?;
235
236        // Step 2: Expand bundles to atomic packs
237        let (atomic_packs, bundle_expansions) = self.expand_bundles(&lockfile)?;
238
239        // Step 3: Resolve dependencies transitively
240        let resolved_packs = self.resolve_dependencies(&atomic_packs)?;
241
242        // Step 4: Check compatibility (multi-dimensional)
243        self.check_compatibility(&resolved_packs)?;
244
245        // Step 5: Enforce policy profiles
246        let profile = self.enforce_policies(&resolved_packs, &lockfile)?;
247
248        // Step 6: Merge pack ontologies
249        let merged_ontology = self.merge_ontologies(&resolved_packs)?;
250
251        // Step 7: Build ownership map
252        let ownership_map = self.build_ownership_map(&resolved_packs)?;
253
254        // Step 8: Load pack queries (μ₂) and templates (μ₃ staging)
255        let mut all_queries = Vec::new();
256        let mut all_templates = Vec::new();
257        for pack in &resolved_packs {
258            let pack_queries = self.registry.get_pack_queries(pack)?;
259            all_queries.extend(pack_queries);
260            let pack_templates = self.registry.get_pack_templates(pack)?;
261            all_templates.extend(pack_templates);
262        }
263
264        // Extract pack versions for lockfile updates
265        let pack_versions = self.extract_pack_versions(&lockfile);
266
267        // Load pack signatures and checksums from metadata for receipt provenance
268        let mut pack_signatures = HashMap::new();
269        let mut pack_checksums = HashMap::new();
270        let mut pack_registry_types = HashMap::new();
271        let mut pack_origin_urls = HashMap::new();
272        for pack in &resolved_packs {
273            let pack_dir = self.registry.pack_dir(pack);
274            let metadata = load_pack_metadata(&pack_dir).unwrap_or_default();
275            let pid = pack.to_string();
276            pack_signatures.insert(
277                pid.clone(),
278                metadata
279                    .signature
280                    .unwrap_or_else(|| "local:unsigned".to_string()),
281            );
282            if let Some(checksum) = metadata.checksum {
283                pack_checksums.insert(pid.clone(), checksum);
284            }
285            if let Some(reg_type) = metadata.registry_type {
286                pack_registry_types.insert(pid.clone(), reg_type.to_string());
287            }
288            if let Some(url) = metadata.origin_url {
289                pack_origin_urls.insert(pid.clone(), url);
290            }
291        }
292
293        Ok(ResolvedPacks {
294            atomic_packs: resolved_packs,
295            merged_ontology,
296            ownership_map,
297            bundle_expansions,
298            pack_versions,
299            profile,
300            queries: all_queries,
301            templates: all_templates,
302            pack_signatures,
303            pack_checksums,
304            pack_registry_types,
305            pack_origin_urls,
306        })
307    }
308
309    /// Read the lockfile from `.ggen/packs.lock`.
310    fn read_lockfile(&self) -> Result<PackLockfile> {
311        if !self.lockfile_path.exists() {
312            bail!(
313                "Lockfile not found at {}. Run 'ggen packs install' first.",
314                self.lockfile_path.display()
315            );
316        }
317
318        PackLockfile::from_file(&self.lockfile_path)
319    }
320
321    /// Expand bundles to atomic packs.
322    ///
323    /// For each entry in the lockfile:
324    /// - If it's a bundle, expand it to atomic packs
325    /// - If it's an atomic pack, use it directly
326    ///
327    /// Returns the expanded atomic pack IDs and bundle expansion records.
328    fn expand_bundles(
329        &self, lockfile: &PackLockfile,
330    ) -> Result<(Vec<AtomicPackId>, Vec<BundleExpansion>)> {
331        let mut atomic_packs = Vec::new();
332        let mut bundle_expansions = Vec::new();
333        let mut seen = HashSet::new();
334
335        for pack_id in lockfile.packs.keys() {
336            // Check if this is a bundle or atomic pack
337            if let Some(bundle) = self.registry.get_bundle(pack_id)? {
338                // Expand bundle to atomic packs
339                let expanded = bundle.expand();
340
341                // Record expansion for provenance
342                bundle_expansions.push(BundleExpansion {
343                    bundle_id: pack_id.clone(),
344                    expanded_to: expanded.iter().map(|p| p.to_string()).collect(),
345                });
346
347                // Add atomic packs (avoid duplicates)
348                for pack in expanded {
349                    if seen.insert(pack.clone()) {
350                        atomic_packs.push(pack);
351                    }
352                }
353            } else if let Some(atomic_pack) = self.parse_atomic_pack_id(pack_id)? {
354                // Direct atomic pack
355                if seen.insert(atomic_pack.clone()) {
356                    atomic_packs.push(atomic_pack);
357                }
358            } else {
359                bail!("Unknown pack or bundle: {}", pack_id);
360            }
361        }
362
363        Ok((atomic_packs, bundle_expansions))
364    }
365
366    /// Resolve dependencies transitively.
367    ///
368    /// Loads dependency metadata for each pack and recursively resolves
369    /// all transitive dependencies. Returns the complete set of atomic packs.
370    fn resolve_dependencies(&self, atomic_packs: &[AtomicPackId]) -> Result<Vec<AtomicPackId>> {
371        let mut resolved = HashSet::new();
372        let mut to_resolve = atomic_packs.to_vec();
373
374        while let Some(pack) = to_resolve.pop() {
375            if resolved.contains(&pack) {
376                continue;
377            }
378
379            // Add pack to resolved set
380            resolved.insert(pack.clone());
381
382            // Load pack dependencies
383            let dependencies = self.registry.get_pack_dependencies(&pack)?;
384
385            // Add dependencies to resolution queue
386            for dep in dependencies {
387                if !resolved.contains(&dep) {
388                    to_resolve.push(dep);
389                }
390            }
391        }
392
393        // Convert to deterministic order (sort for reproducibility)
394        let mut sorted: Vec<_> = resolved.into_iter().collect();
395        sorted.sort_by_key(|p| p.to_string());
396
397        Ok(sorted)
398    }
399
400    /// Check multi-dimensional compatibility.
401    ///
402    /// Performs compatibility checks across multiple dimensions:
403    /// - Ontology namespace conflicts
404    /// - Protocol field conflicts
405    /// - Emitted file path conflicts
406    /// - Runtime compatibility
407    /// - Validator contradictions
408    /// - Policy contradictions
409    ///
410    /// Returns error if any conflicts are detected.
411    fn check_compatibility(&self, packs: &[AtomicPackId]) -> Result<()> {
412        // For now, implement basic conflict detection
413        // Full multi-dimensional checking will be added in Phase 5
414
415        // Check for duplicate packs (shouldn't happen after dependency resolution)
416        let mut seen = HashSet::new();
417        for pack in packs {
418            if !seen.insert(pack) {
419                bail!("Duplicate pack detected: {}", pack);
420            }
421        }
422
423        // Load and check ownership declarations
424        let mut ownership_map = OwnershipMap::new();
425        for pack in packs {
426            let declarations = self.registry.get_ownership_declarations(pack)?;
427            for decl in declarations {
428                ownership_map.add(decl)?;
429            }
430        }
431
432        // Check for conflicts
433        let conflicts = ownership_map.check_conflicts();
434        if !conflicts.is_empty() {
435            let mut error_msg = "Pack compatibility check failed:\n".to_string();
436            for conflict in conflicts {
437                error_msg.push_str(&format!("  - {}\n", conflict));
438            }
439            bail!("{}", error_msg);
440        }
441
442        Ok(())
443    }
444
445    /// Enforce policy profiles against resolved packs.
446    ///
447    /// Loads the profile from the lockfile (or uses "development" as default),
448    /// converts packs to policy context, and enforces all profile policies.
449    ///
450    /// Returns the profile ID that was enforced.
451    ///
452    /// # Errors
453    ///
454    /// Returns error if profile not found or policy enforcement fails.
455    fn enforce_policies(&self, packs: &[AtomicPackId], lockfile: &PackLockfile) -> Result<String> {
456        // Determine profile from lockfile or use default
457        let profile_id = lockfile.profile.clone().unwrap_or_else(|| {
458            // Default to "development" profile if not specified
459            "development".to_string()
460        });
461
462        // Load profile
463        let profile = get_profile(&profile_id)
464            .map_err(|e| Error::new(&format!("Failed to load profile '{}': {}", profile_id, e)))?;
465
466        // Convert atomic packs to policy context, loading real metadata from cache
467        let pack_contexts: Vec<PackContext> = packs
468            .iter()
469            .map(|pack_id| {
470                let pack_dir = self.registry.pack_dir(pack_id);
471                let metadata = load_pack_metadata(&pack_dir).unwrap_or_default();
472
473                let has_signature = metadata.signature.is_some();
474                PackContext::new(pack_id.to_string())
475                    .with_trust_tier(metadata.trust_tier)
476                    .with_signed_receipts(has_signature)
477                    .with_signature_verification(has_signature)
478                    .with_allowlisted(has_signature)
479                    .with_semver(true) // installed packs use semver versions
480            })
481            .collect();
482
483        // Enforce policies
484        let report = PolicyEnforcer::enforce(&profile.policy_overlays, &pack_contexts)
485            .map_err(|e| Error::new(&format!("Policy enforcement failed: {}", e)))?;
486
487        // Handle violations
488        if !report.passed {
489            // Check for error-level violations
490            // For now, all violations are treated as errors
491            let mut error_msg =
492                format!("Policy enforcement failed for profile '{}':\n", profile_id);
493            for violation in &report.violations {
494                error_msg.push_str(&format!("  - {}\n", violation.description));
495            }
496            bail!("{}", error_msg);
497        } else {
498            // Policy passed - log success
499            if report.violations.is_empty() {
500                tracing::info!(
501                    profile = %profile_id,
502                    packs = packs.len(),
503                    "All policies passed for profile '{}'",
504                    profile_id
505                );
506            } else {
507                tracing::debug!(
508                    profile = %profile_id,
509                    warnings = report.violations.len(),
510                    "Policy check passed with warnings"
511                );
512            }
513        }
514
515        Ok(profile_id)
516    }
517
518    /// Merge RDF ontologies from all packs.
519    ///
520    /// Loads ontology files from each pack and merges them into a single graph.
521    /// Foundation packs are loaded first to establish base ontology.
522    fn merge_ontologies(&self, packs: &[AtomicPackId]) -> Result<Graph> {
523        let merged = Graph::new()?;
524
525        // Load foundation ontology first (CISO requirement)
526        for foundation in foundation_packs() {
527            if packs.contains(&foundation) {
528                let ontology_path = self.registry.get_pack_ontology_path(&foundation)?;
529                if ontology_path.exists() {
530                    let content = std::fs::read_to_string(&ontology_path).map_err(|e| {
531                        Error::new(&format!(
532                            "Failed to read ontology for {}: {}",
533                            foundation, e
534                        ))
535                    })?;
536                    merged.insert_turtle(&content)?;
537                }
538            }
539        }
540
541        // Load pack ontologies
542        for pack in packs {
543            let ontology_path = self.registry.get_pack_ontology_path(pack)?;
544            if ontology_path.exists() {
545                let content = std::fs::read_to_string(&ontology_path).map_err(|e| {
546                    Error::new(&format!("Failed to read ontology for {}: {}", pack, e))
547                })?;
548                merged.insert_turtle(&content)?;
549            }
550        }
551
552        Ok(merged)
553    }
554
555    /// Build ownership map from all packs.
556    ///
557    /// Loads ownership declarations from each pack and builds a consolidated
558    /// ownership map for conflict detection.
559    fn build_ownership_map(&self, packs: &[AtomicPackId]) -> Result<OwnershipMap> {
560        let mut ownership_map = OwnershipMap::new();
561
562        for pack in packs {
563            let declarations = self.registry.get_ownership_declarations(pack)?;
564            for decl in declarations {
565                ownership_map.add(decl)?;
566            }
567        }
568
569        Ok(ownership_map)
570    }
571
572    /// Extract pack versions from lockfile.
573    ///
574    /// Returns a map of pack ID to version string.
575    fn extract_pack_versions(&self, lockfile: &PackLockfile) -> HashMap<String, String> {
576        lockfile
577            .packs
578            .iter()
579            .map(|(id, pack)| (id.clone(), pack.version.clone()))
580            .collect()
581    }
582
583    /// Parse a pack ID string to an AtomicPackId.
584    ///
585    /// Returns None if the string is not a valid atomic pack ID.
586    fn parse_atomic_pack_id(&self, pack_id: &str) -> Result<Option<AtomicPackId>> {
587        // Try to parse as atomic pack ID (e.g., "surface-mcp", "projection-rust")
588        Ok(pack_id.parse::<AtomicPackId>().ok())
589    }
590}
591
592/// Pack Registry
593///
594/// Provides access to pack metadata, ontologies, templates, and ownership
595/// declarations from the local cache.
596struct PackRegistry {
597    /// Cache directory where packs are stored
598    cache_dir: PathBuf,
599
600    /// In-memory bundle index
601    bundles: HashMap<String, Bundle>,
602}
603
604impl PackRegistry {
605    /// Create a new pack registry.
606    fn new(cache_dir: PathBuf) -> Result<Self> {
607        let mut registry = Self {
608            cache_dir,
609            bundles: HashMap::new(),
610        };
611
612        // Initialize common bundles
613        registry.initialize_bundles();
614
615        Ok(registry)
616    }
617
618    /// Initialize common bundle definitions.
619    fn initialize_bundles(&mut self) {
620        use crate::marketplace::bundle::Bundles;
621
622        // Register common bundles
623        self.bundles
624            .insert("mcp-rust".to_string(), Bundles::mcp_rust());
625        self.bundles
626            .insert("mcp-rust-stdio".to_string(), Bundles::mcp_rust_stdio());
627        self.bundles
628            .insert("mcp-rust-axum".to_string(), Bundles::mcp_rust_axum());
629        self.bundles
630            .insert("a2a-rust".to_string(), Bundles::a2a_rust());
631        self.bundles
632            .insert("openapi-rust".to_string(), Bundles::openapi_rust());
633        self.bundles.insert(
634            "graphql-typescript".to_string(),
635            Bundles::graphql_typescript(),
636        );
637    }
638
639    /// Get a bundle by ID.
640    fn get_bundle(&self, bundle_id: &str) -> Result<Option<&Bundle>> {
641        Ok(self.bundles.get(bundle_id))
642    }
643
644    /// Get the cache directory for a specific pack.
645    fn pack_dir(&self, pack: &AtomicPackId) -> PathBuf {
646        self.cache_dir.join(pack.to_string())
647    }
648
649    /// Get the path to a pack's ontology file.
650    fn get_pack_ontology_path(&self, pack: &AtomicPackId) -> Result<PathBuf> {
651        let pack_dir = self.cache_dir.join(pack.to_string());
652        Ok(pack_dir.join("ontology").join("pack.ttl"))
653    }
654
655    /// Get dependencies for a pack.
656    ///
657    /// Loads dependencies from the pack's `package.toml` file under a
658    /// `[dependencies]` section, or from a `dependencies.json` file.
659    /// Returns an empty vector if no dependency metadata exists.
660    fn get_pack_dependencies(&self, pack: &AtomicPackId) -> Result<Vec<AtomicPackId>> {
661        let pack_dir = self.pack_dir(pack);
662        let pack_id_str = pack.to_string();
663
664        // Try package.toml [dependencies] section first
665        let toml_path = pack_dir.join("package.toml");
666        if toml_path.exists() {
667            if let Ok(deps) = Self::load_deps_from_toml(&toml_path) {
668                if !deps.is_empty() {
669                    tracing::debug!(
670                        pack = %pack_id_str,
671                        deps = deps.len(),
672                        "Loaded {} dependencies from package.toml",
673                        deps.len()
674                    );
675                    return Ok(deps);
676                }
677            }
678        }
679
680        // Fallback to dependencies.json
681        let json_path = pack_dir.join("dependencies.json");
682        if json_path.exists() {
683            if let Ok(deps) = Self::load_deps_from_json(&json_path) {
684                if !deps.is_empty() {
685                    tracing::debug!(
686                        pack = %pack_id_str,
687                        deps = deps.len(),
688                        "Loaded {} dependencies from dependencies.json",
689                        deps.len()
690                    );
691                    return Ok(deps);
692                }
693            }
694        }
695
696        Ok(Vec::new())
697    }
698
699    /// Load dependency pack IDs from package.toml [dependencies] section.
700    fn load_deps_from_toml(toml_path: &Path) -> Result<Vec<AtomicPackId>> {
701        let content = std::fs::read_to_string(toml_path)
702            .map_err(|e| Error::new(&format!("Failed to read {}: {}", toml_path.display(), e)))?;
703        let value: toml::Value = toml::from_str(&content)
704            .map_err(|e| Error::new(&format!("Failed to parse {}: {}", toml_path.display(), e)))?;
705
706        let deps_array = value.get("dependencies").and_then(|v| v.as_array());
707
708        let mut result = Vec::new();
709        if let Some(array) = deps_array {
710            for item in array {
711                if let Some(dep_str) = item.as_str() {
712                    if let Some(pack_id) = dep_str.parse::<AtomicPackId>().ok() {
713                        result.push(pack_id);
714                    }
715                }
716            }
717        }
718
719        Ok(result)
720    }
721
722    /// Load dependency pack IDs from dependencies.json file.
723    fn load_deps_from_json(json_path: &Path) -> Result<Vec<AtomicPackId>> {
724        let content = std::fs::read_to_string(json_path)
725            .map_err(|e| Error::new(&format!("Failed to read {}: {}", json_path.display(), e)))?;
726        let deps: Vec<String> = serde_json::from_str(&content)
727            .map_err(|e| Error::new(&format!("Failed to parse {}: {}", json_path.display(), e)))?;
728
729        let mut result = Vec::new();
730        for dep_str in deps {
731            if let Some(pack_id) = dep_str.parse::<AtomicPackId>().ok() {
732                result.push(pack_id);
733            }
734        }
735
736        Ok(result)
737    }
738
739    /// Get ownership declarations for a pack.
740    ///
741    /// Loads ownership declarations from the pack's `ownership.json` file
742    /// or from the `[ownership.declarations]` section in `package.toml`.
743    /// Returns an empty vector if no ownership metadata exists.
744    fn get_ownership_declarations(&self, pack: &AtomicPackId) -> Result<Vec<OwnershipDeclaration>> {
745        let pack_dir = self.pack_dir(pack);
746        let pack_id_str = pack.to_string();
747
748        // Try ownership.json first (primary format)
749        let ownership_json_path = pack_dir.join("ownership.json");
750        if ownership_json_path.exists() {
751            let declarations = Self::load_ownership_json(&ownership_json_path)?;
752            if !declarations.is_empty() {
753                tracing::debug!(
754                    pack = %pack_id_str,
755                    declarations = declarations.len(),
756                    "Loaded {} ownership declarations from ownership.json",
757                    declarations.len()
758                );
759                return Ok(declarations);
760            }
761        }
762
763        // Fallback to package.toml [ownership.declarations] section
764        let package_toml_path = pack_dir.join("package.toml");
765        if package_toml_path.exists() {
766            let declarations = Self::load_ownership_from_toml(&package_toml_path, &pack_id_str)?;
767            if !declarations.is_empty() {
768                tracing::debug!(
769                    pack = %pack_id_str,
770                    declarations = declarations.len(),
771                    "Loaded {} ownership declarations from package.toml",
772                    declarations.len()
773                );
774                return Ok(declarations);
775            }
776        }
777
778        Ok(Vec::new())
779    }
780
781    /// Load ownership declarations from ownership.json file.
782    fn load_ownership_json(path: &Path) -> Result<Vec<OwnershipDeclaration>> {
783        let content = std::fs::read_to_string(path)
784            .map_err(|e| Error::new(&format!("Failed to read {}: {}", path.display(), e)))?;
785        let declarations: Vec<OwnershipDeclaration> = serde_json::from_str(&content)
786            .map_err(|e| Error::new(&format!("Failed to parse {}: {}", path.display(), e)))?;
787        Ok(declarations)
788    }
789
790    /// Load ownership declarations from package.toml [ownership.declarations] section.
791    fn load_ownership_from_toml(
792        path: &Path, pack_id_str: &str,
793    ) -> Result<Vec<OwnershipDeclaration>> {
794        let content = std::fs::read_to_string(path)
795            .map_err(|e| Error::new(&format!("Failed to read {}: {}", path.display(), e)))?;
796        let value: toml::Value = toml::from_str(&content)
797            .map_err(|e| Error::new(&format!("Failed to parse {}: {}", path.display(), e)))?;
798
799        let ownership_section = value.get("ownership").and_then(|v| v.as_table());
800        let declarations_array = ownership_section
801            .and_then(|t| t.get("declarations"))
802            .and_then(|v| v.as_array());
803
804        let mut result = Vec::new();
805        if let Some(array) = declarations_array {
806            for (idx, decl_value) in array.iter().enumerate() {
807                let table = decl_value.as_table().ok_or_else(|| {
808                    Error::new(&format!(
809                        "ownership.declarations[{}] is not a table in {}",
810                        idx,
811                        path.display()
812                    ))
813                })?;
814
815                let target = Self::parse_ownership_target(table, path, idx)?;
816                let class = Self::parse_ownership_class(table, path, idx)?;
817                let merge_strategy = Self::parse_merge_strategy(table);
818
819                result.push(OwnershipDeclaration {
820                    target,
821                    class,
822                    owner_pack: pack_id_str.to_string(),
823                    merge_strategy,
824                    metadata: None,
825                });
826            }
827        }
828
829        Ok(result)
830    }
831
832    /// Parse an ownership target from a TOML table.
833    fn parse_ownership_target(
834        table: &toml::Table, path: &Path, idx: usize,
835    ) -> Result<OwnershipTarget> {
836        let kind = table.get("kind").and_then(|v| v.as_str()).ok_or_else(|| {
837            Error::new(&format!(
838                "ownership.declarations[{}].kind is missing in {}",
839                idx,
840                path.display()
841            ))
842        })?;
843
844        let value = table.get("value").and_then(|v| v.as_str()).ok_or_else(|| {
845            Error::new(&format!(
846                "ownership.declarations[{}].value is missing in {}",
847                idx,
848                path.display()
849            ))
850        })?;
851
852        let target = match kind {
853            "file_path" => OwnershipTarget::FilePath(PathBuf::from(value)),
854            "rdf_namespace" => OwnershipTarget::RdfNamespace(value.to_string()),
855            "protocol_field" => OwnershipTarget::ProtocolField(value.to_string()),
856            "template_variable" => OwnershipTarget::TemplateVariable(value.to_string()),
857            "dependency_package" => OwnershipTarget::DependencyPackage(value.to_string()),
858            "feature_flag" => OwnershipTarget::FeatureFlag(value.to_string()),
859            other => {
860                bail!(
861                    "Unknown ownership target kind '{}' at index {} in {}",
862                    other,
863                    idx,
864                    path.display()
865                );
866            }
867        };
868
869        Ok(target)
870    }
871
872    /// Parse an ownership class from a TOML table.
873    fn parse_ownership_class(
874        table: &toml::Table, path: &Path, idx: usize,
875    ) -> Result<OwnershipClass> {
876        let class_str = table.get("class").and_then(|v| v.as_str()).ok_or_else(|| {
877            Error::new(&format!(
878                "ownership.declarations[{}].class is missing in {}",
879                idx,
880                path.display()
881            ))
882        })?;
883
884        match class_str {
885            "exclusive" => Ok(OwnershipClass::Exclusive),
886            "mergeable" => Ok(OwnershipClass::Mergeable),
887            "overlay" => Ok(OwnershipClass::Overlay),
888            "forbidden_overlap" => Ok(OwnershipClass::ForbiddenOverlap),
889            other => {
890                bail!(
891                    "Unknown ownership class '{}' at index {} in {}",
892                    other,
893                    idx,
894                    path.display()
895                );
896            }
897        }
898    }
899
900    /// Parse an optional merge strategy from a TOML table.
901    fn parse_merge_strategy(table: &toml::Table) -> Option<MergeStrategy> {
902        let strategy_str = table.get("merge_strategy").and_then(|v| v.as_str())?;
903        match strategy_str {
904            "concat" => Some(MergeStrategy::Concat),
905            "last_writer_wins" => Some(MergeStrategy::LastWriterWins),
906            "first_writer_wins" => Some(MergeStrategy::FirstWriterWins),
907            "recursive" => Some(MergeStrategy::Recursive),
908            "fail_on_conflict" => Some(MergeStrategy::FailOnConflict),
909            _ => None,
910        }
911    }
912
913    /// Get SPARQL queries for a pack.
914    ///
915    /// Scans the pack's queries directory for .rq files and returns a list of SparqlQuery objects.
916    /// This enables packs to contribute custom extraction logic to the μ₂ stage.
917    fn get_pack_queries(&self, pack: &AtomicPackId) -> Result<Vec<SparqlQuery>> {
918        let queries_dir = self.cache_dir.join(pack.to_string()).join("queries");
919
920        if !queries_dir.exists() {
921            // No queries directory is valid - return empty list
922            return Ok(Vec::new());
923        }
924
925        let mut queries = Vec::new();
926
927        let entries = std::fs::read_dir(&queries_dir).map_err(|e| {
928            crate::utils::error::Error::new(&format!(
929                "Failed to read queries directory {}: {}",
930                queries_dir.display(),
931                e
932            ))
933        })?;
934
935        for entry in entries {
936            let entry = entry.map_err(|e| {
937                crate::utils::error::Error::new(&format!("Failed to read directory entry: {}", e))
938            })?;
939            let path = entry.path();
940
941            // Only process .rq files
942            if path.extension().and_then(|s| s.to_str()) != Some("rq") {
943                continue;
944            }
945
946            let content = std::fs::read_to_string(&path).map_err(|e| {
947                crate::utils::error::Error::new(&format!(
948                    "Failed to read query file {}: {}",
949                    path.display(),
950                    e
951                ))
952            })?;
953
954            let stem = path
955                .file_stem()
956                .and_then(|s| s.to_str())
957                .unwrap_or("unknown")
958                .to_string();
959            let name = format!("{}::{}", pack, stem);
960
961            queries.push(SparqlQuery {
962                name,
963                sparql: content,
964            });
965        }
966
967        Ok(queries)
968    }
969
970    /// Get Tera templates for a pack.
971    ///
972    /// Scans the pack's templates directory for .tera files and returns a list of TemplateDef objects.
973    /// This enables packs to contribute code generation templates to the μ₃ stage.
974    fn get_pack_templates(&self, pack: &AtomicPackId) -> Result<Vec<TemplateDef>> {
975        let templates_dir = self.cache_dir.join(pack.to_string()).join("templates");
976
977        if !templates_dir.exists() {
978            // No templates directory is valid - return empty list
979            return Ok(Vec::new());
980        }
981
982        let mut templates = Vec::new();
983
984        let entries = std::fs::read_dir(&templates_dir).map_err(|e| {
985            crate::utils::error::Error::new(&format!(
986                "Failed to read templates directory {}: {}",
987                templates_dir.display(),
988                e
989            ))
990        })?;
991
992        for entry in entries {
993            let entry = entry.map_err(|e| {
994                crate::utils::error::Error::new(&format!("Failed to read directory entry: {}", e))
995            })?;
996            let path = entry.path();
997
998            // Only process .tera files
999            if path.extension().and_then(|s| s.to_str()) != Some("tera") {
1000                continue;
1001            }
1002
1003            let content = std::fs::read_to_string(&path).map_err(|e| {
1004                crate::utils::error::Error::new(&format!(
1005                    "Failed to read template file {}: {}",
1006                    path.display(),
1007                    e
1008                ))
1009            })?;
1010
1011            // Get relative path from templates_dir
1012            let relative_path = path.strip_prefix(&self.cache_dir).map_err(|e| {
1013                crate::utils::error::Error::new(&format!("Failed to create relative path: {}", e))
1014            })?;
1015
1016            templates.push(TemplateDef {
1017                path: relative_path.to_path_buf(),
1018                content,
1019            });
1020        }
1021
1022        Ok(templates)
1023    }
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028    use super::*;
1029    use tempfile::TempDir;
1030
1031    #[test]
1032    fn test_pack_resolver_new() {
1033        let temp_dir = TempDir::new().unwrap();
1034        let resolver = PackResolver::new(temp_dir.path());
1035        assert!(resolver.is_ok());
1036    }
1037
1038    #[test]
1039    fn test_bundle_expansion() {
1040        let temp_dir = TempDir::new().unwrap();
1041        let _resolver = PackResolver::new(temp_dir.path()).unwrap();
1042
1043        // Create a mock lockfile with mcp-rust bundle
1044        let _lockfile = PackLockfile::new("6.0.0");
1045    }
1046
1047    #[test]
1048    fn test_atomic_pack_parsing() {
1049        let temp_dir = TempDir::new().unwrap();
1050        let resolver = PackResolver::new(temp_dir.path()).unwrap();
1051
1052        // Valid atomic pack IDs
1053        assert!(resolver
1054            .parse_atomic_pack_id("surface-mcp")
1055            .unwrap()
1056            .is_some());
1057        assert!(resolver
1058            .parse_atomic_pack_id("projection-rust")
1059            .unwrap()
1060            .is_some());
1061        assert!(resolver
1062            .parse_atomic_pack_id("runtime-axum")
1063            .unwrap()
1064            .is_some());
1065
1066        // Bundle IDs should return None (they're expanded separately)
1067        assert!(resolver.parse_atomic_pack_id("mcp-rust").unwrap().is_none());
1068
1069        // Invalid pack ID
1070        assert!(resolver
1071            .parse_atomic_pack_id("invalid-pack")
1072            .unwrap()
1073            .is_none());
1074    }
1075
1076    #[test]
1077    fn test_foundation_packs() {
1078        let foundations = foundation_packs();
1079        assert!(!foundations.is_empty());
1080        assert!(foundations.iter().all(|p| p.class.is_foundation()));
1081    }
1082}