1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct SparqlQuery {
52 pub name: String,
54 pub sparql: String,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct TemplateDef {
61 pub path: PathBuf,
63 pub content: String,
65}
66
67#[derive(Clone)]
72pub struct ResolvedPacks {
73 pub atomic_packs: Vec<AtomicPackId>,
75
76 pub merged_ontology: Graph,
78
79 pub ownership_map: OwnershipMap,
81
82 pub bundle_expansions: Vec<BundleExpansion>,
84
85 pub pack_versions: HashMap<String, String>,
87
88 pub profile: String,
90
91 pub queries: Vec<SparqlQuery>,
93
94 pub templates: Vec<TemplateDef>,
96
97 pub pack_signatures: HashMap<String, String>,
99
100 pub pack_checksums: HashMap<String, String>,
102
103 pub pack_registry_types: HashMap<String, String>,
105
106 pub pack_origin_urls: HashMap<String, String>,
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct BundleExpansion {
113 pub bundle_id: String,
115
116 pub expanded_to: Vec<String>,
118}
119
120impl ResolvedPacks {
121 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 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 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
167pub struct PackResolver {
172 #[allow(dead_code)]
174 lockfile_path: PathBuf,
175
176 registry: Arc<PackRegistry>,
178}
179
180impl PackResolver {
181 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 pub fn resolve(&self) -> Result<ResolvedPacks> {
233 let lockfile = self.read_lockfile()?;
235
236 let (atomic_packs, bundle_expansions) = self.expand_bundles(&lockfile)?;
238
239 let resolved_packs = self.resolve_dependencies(&atomic_packs)?;
241
242 self.check_compatibility(&resolved_packs)?;
244
245 let profile = self.enforce_policies(&resolved_packs, &lockfile)?;
247
248 let merged_ontology = self.merge_ontologies(&resolved_packs)?;
250
251 let ownership_map = self.build_ownership_map(&resolved_packs)?;
253
254 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 let pack_versions = self.extract_pack_versions(&lockfile);
266
267 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 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 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 if let Some(bundle) = self.registry.get_bundle(pack_id)? {
338 let expanded = bundle.expand();
340
341 bundle_expansions.push(BundleExpansion {
343 bundle_id: pack_id.clone(),
344 expanded_to: expanded.iter().map(|p| p.to_string()).collect(),
345 });
346
347 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 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 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 resolved.insert(pack.clone());
381
382 let dependencies = self.registry.get_pack_dependencies(&pack)?;
384
385 for dep in dependencies {
387 if !resolved.contains(&dep) {
388 to_resolve.push(dep);
389 }
390 }
391 }
392
393 let mut sorted: Vec<_> = resolved.into_iter().collect();
395 sorted.sort_by_key(|p| p.to_string());
396
397 Ok(sorted)
398 }
399
400 fn check_compatibility(&self, packs: &[AtomicPackId]) -> Result<()> {
412 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 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 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 fn enforce_policies(&self, packs: &[AtomicPackId], lockfile: &PackLockfile) -> Result<String> {
456 let profile_id = lockfile.profile.clone().unwrap_or_else(|| {
458 "development".to_string()
460 });
461
462 let profile = get_profile(&profile_id)
464 .map_err(|e| Error::new(&format!("Failed to load profile '{}': {}", profile_id, e)))?;
465
466 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) })
481 .collect();
482
483 let report = PolicyEnforcer::enforce(&profile.policy_overlays, &pack_contexts)
485 .map_err(|e| Error::new(&format!("Policy enforcement failed: {}", e)))?;
486
487 if !report.passed {
489 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 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 fn merge_ontologies(&self, packs: &[AtomicPackId]) -> Result<Graph> {
523 let merged = Graph::new()?;
524
525 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 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 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 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 fn parse_atomic_pack_id(&self, pack_id: &str) -> Result<Option<AtomicPackId>> {
587 Ok(pack_id.parse::<AtomicPackId>().ok())
589 }
590}
591
592struct PackRegistry {
597 cache_dir: PathBuf,
599
600 bundles: HashMap<String, Bundle>,
602}
603
604impl PackRegistry {
605 fn new(cache_dir: PathBuf) -> Result<Self> {
607 let mut registry = Self {
608 cache_dir,
609 bundles: HashMap::new(),
610 };
611
612 registry.initialize_bundles();
614
615 Ok(registry)
616 }
617
618 fn initialize_bundles(&mut self) {
620 use crate::marketplace::bundle::Bundles;
621
622 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 fn get_bundle(&self, bundle_id: &str) -> Result<Option<&Bundle>> {
641 Ok(self.bundles.get(bundle_id))
642 }
643
644 fn pack_dir(&self, pack: &AtomicPackId) -> PathBuf {
646 self.cache_dir.join(pack.to_string())
647 }
648
649 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 assert!(resolver.parse_atomic_pack_id("mcp-rust").unwrap().is_none());
1068
1069 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}