1use crate::cli::resolve::{self, ResolveArgs};
2use crate::config::{
3 AssetConfig, ComponentConfig, ComponentOperationConfig, FlowConfig, PackConfig,
4};
5use crate::extensions::validate_components_extension;
6use crate::flow_resolve::load_flow_resolve_summary;
7use crate::runtime::{NetworkPolicy, RuntimeContext};
8use anyhow::{Context, Result, anyhow};
9use greentic_distributor_client::{DistClient, DistOptions};
10use greentic_flow::add_step::normalize::normalize_node_map;
11use greentic_flow::compile_ygtc_file;
12use greentic_flow::loader::load_ygtc_from_path;
13use greentic_pack::builder::SbomEntry;
14use greentic_pack::pack_lock::read_pack_lock;
15use greentic_types::component_source::ComponentSourceRef;
16use greentic_types::flow_resolve_summary::FlowResolveSummaryV1;
17use greentic_types::pack::extensions::component_manifests::{
18 ComponentManifestIndexEntryV1, ComponentManifestIndexV1, EXT_COMPONENT_MANIFEST_INDEX_V1,
19 ManifestEncoding,
20};
21use greentic_types::pack::extensions::component_sources::{
22 ArtifactLocationV1, ComponentSourceEntryV1, ComponentSourcesV1, EXT_COMPONENT_SOURCES_V1,
23 ResolvedComponentV1,
24};
25use greentic_types::{
26 BootstrapSpec, ComponentCapability, ComponentConfigurators, ComponentId, ComponentManifest,
27 ComponentOperation, ExtensionInline, ExtensionRef, Flow, FlowId, PackDependency, PackFlowEntry,
28 PackId, PackKind, PackManifest, PackSignatures, SecretRequirement, SecretScope, SemverReq,
29 encode_pack_manifest,
30};
31use semver::Version;
32use serde::Serialize;
33use serde_cbor;
34use serde_yaml_bw::Value as YamlValue;
35use sha2::{Digest, Sha256};
36use std::collections::{BTreeMap, BTreeSet};
37use std::fs;
38use std::io::Write;
39use std::path::{Path, PathBuf};
40use std::str::FromStr;
41use tracing::info;
42use walkdir::WalkDir;
43use zip::write::SimpleFileOptions;
44use zip::{CompressionMethod, ZipWriter};
45
46const SBOM_FORMAT: &str = "greentic-sbom-v1";
47
48#[derive(Serialize)]
49struct SbomDocument {
50 format: String,
51 files: Vec<SbomEntry>,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
55pub enum BundleMode {
56 Cache,
57 None,
58}
59
60#[derive(Clone)]
61pub struct BuildOptions {
62 pub pack_dir: PathBuf,
63 pub component_out: Option<PathBuf>,
64 pub manifest_out: PathBuf,
65 pub sbom_out: Option<PathBuf>,
66 pub gtpack_out: Option<PathBuf>,
67 pub lock_path: PathBuf,
68 pub bundle: BundleMode,
69 pub dry_run: bool,
70 pub secrets_req: Option<PathBuf>,
71 pub default_secret_scope: Option<String>,
72 pub allow_oci_tags: bool,
73 pub require_component_manifests: bool,
74 pub no_extra_dirs: bool,
75 pub runtime: RuntimeContext,
76 pub skip_update: bool,
77}
78
79impl BuildOptions {
80 pub fn from_args(args: crate::BuildArgs, runtime: &RuntimeContext) -> Result<Self> {
81 let pack_dir = args
82 .input
83 .canonicalize()
84 .with_context(|| format!("failed to canonicalize pack dir {}", args.input.display()))?;
85
86 let component_out = args
87 .component_out
88 .map(|p| if p.is_absolute() { p } else { pack_dir.join(p) });
89 let manifest_out = args
90 .manifest
91 .map(|p| if p.is_relative() { pack_dir.join(p) } else { p })
92 .unwrap_or_else(|| pack_dir.join("dist").join("manifest.cbor"));
93 let sbom_out = args
94 .sbom
95 .map(|p| if p.is_absolute() { p } else { pack_dir.join(p) });
96 let default_gtpack_name = pack_dir
97 .file_name()
98 .and_then(|name| name.to_str())
99 .unwrap_or("pack");
100 let default_gtpack_out = pack_dir
101 .join("dist")
102 .join(format!("{default_gtpack_name}.gtpack"));
103 let gtpack_out = Some(
104 args.gtpack_out
105 .map(|p| if p.is_absolute() { p } else { pack_dir.join(p) })
106 .unwrap_or(default_gtpack_out),
107 );
108 let lock_path = args
109 .lock
110 .map(|p| if p.is_absolute() { p } else { pack_dir.join(p) })
111 .unwrap_or_else(|| pack_dir.join("pack.lock.json"));
112
113 Ok(Self {
114 pack_dir,
115 component_out,
116 manifest_out,
117 sbom_out,
118 gtpack_out,
119 lock_path,
120 bundle: args.bundle,
121 dry_run: args.dry_run,
122 secrets_req: args.secrets_req,
123 default_secret_scope: args.default_secret_scope,
124 allow_oci_tags: args.allow_oci_tags,
125 require_component_manifests: args.require_component_manifests,
126 no_extra_dirs: args.no_extra_dirs,
127 runtime: runtime.clone(),
128 skip_update: args.no_update,
129 })
130 }
131}
132
133pub async fn run(opts: &BuildOptions) -> Result<()> {
134 info!(
135 pack_dir = %opts.pack_dir.display(),
136 manifest_out = %opts.manifest_out.display(),
137 gtpack_out = ?opts.gtpack_out,
138 dry_run = opts.dry_run,
139 "building greentic pack"
140 );
141
142 if !opts.skip_update {
143 crate::cli::update::update_pack(&opts.pack_dir, false)?;
145 }
146
147 resolve::handle(
150 ResolveArgs {
151 input: opts.pack_dir.clone(),
152 lock: Some(opts.lock_path.clone()),
153 },
154 &opts.runtime,
155 false,
156 )
157 .await?;
158
159 let config = crate::config::load_pack_config(&opts.pack_dir)?;
160 info!(
161 id = %config.pack_id,
162 version = %config.version,
163 kind = %config.kind,
164 components = config.components.len(),
165 flows = config.flows.len(),
166 dependencies = config.dependencies.len(),
167 "loaded pack.yaml"
168 );
169 validate_components_extension(&config.extensions, opts.allow_oci_tags)?;
170
171 let secret_requirements = aggregate_secret_requirements(
172 &config.components,
173 opts.secrets_req.as_deref(),
174 opts.default_secret_scope.as_deref(),
175 )?;
176
177 if !opts.lock_path.exists() {
178 anyhow::bail!(
179 "pack.lock.json is required (run `greentic-pack resolve`); missing: {}",
180 opts.lock_path.display()
181 );
182 }
183 let mut pack_lock = read_pack_lock(&opts.lock_path).with_context(|| {
184 format!(
185 "failed to read pack lock {} (try `greentic-pack resolve`)",
186 opts.lock_path.display()
187 )
188 })?;
189
190 let mut build = assemble_manifest(
191 &config,
192 &opts.pack_dir,
193 &secret_requirements,
194 !opts.no_extra_dirs,
195 )?;
196 build.lock_components =
197 collect_lock_component_artifacts(&mut pack_lock, &opts.runtime, opts.bundle, opts.dry_run)
198 .await?;
199
200 let materialized = materialize_flow_components(
201 &opts.pack_dir,
202 &build.manifest.flows,
203 &pack_lock,
204 &build.components,
205 &build.lock_components,
206 opts.require_component_manifests,
207 )?;
208 build.manifest.components.extend(materialized.components);
209 build.component_manifest_files = materialized.manifest_files;
210 build.manifest.components.sort_by(|a, b| a.id.cmp(&b.id));
211
212 let component_manifest_files =
213 collect_component_manifest_files(&build.components, &build.component_manifest_files);
214 build.manifest.extensions =
215 merge_component_manifest_extension(build.manifest.extensions, &component_manifest_files)?;
216 build.manifest.extensions = merge_component_sources_extension(
217 build.manifest.extensions,
218 &pack_lock,
219 opts.bundle,
220 materialized.manifest_paths.as_ref(),
221 )?;
222 if !opts.dry_run {
223 greentic_pack::pack_lock::write_pack_lock(&opts.lock_path, &pack_lock)?;
224 }
225
226 let manifest_bytes = encode_pack_manifest(&build.manifest)?;
227 info!(len = manifest_bytes.len(), "encoded manifest.cbor");
228
229 if opts.dry_run {
230 info!("dry-run complete; no files written");
231 return Ok(());
232 }
233
234 if let Some(component_out) = opts.component_out.as_ref() {
235 write_stub_wasm(component_out)?;
236 }
237
238 write_bytes(&opts.manifest_out, &manifest_bytes)?;
239
240 if let Some(sbom_out) = opts.sbom_out.as_ref() {
241 write_bytes(sbom_out, br#"{"files":[]} "#)?;
242 }
243
244 if let Some(gtpack_out) = opts.gtpack_out.as_ref() {
245 let mut build = build;
246 if !secret_requirements.is_empty() {
247 let logical = "secret-requirements.json".to_string();
248 let req_path =
249 write_secret_requirements_file(&opts.pack_dir, &secret_requirements, &logical)?;
250 build.assets.push(AssetFile {
251 logical_path: logical,
252 source: req_path,
253 });
254 }
255 package_gtpack(gtpack_out, &manifest_bytes, &build, opts.bundle)?;
256 info!(gtpack_out = %gtpack_out.display(), "gtpack archive ready");
257 eprintln!("wrote {}", gtpack_out.display());
258 }
259
260 Ok(())
261}
262
263struct BuildProducts {
264 manifest: PackManifest,
265 components: Vec<ComponentBinary>,
266 lock_components: Vec<LockComponentBinary>,
267 component_manifest_files: Vec<ComponentManifestFile>,
268 flow_files: Vec<FlowFile>,
269 assets: Vec<AssetFile>,
270 extra_files: Vec<ExtraFile>,
271}
272
273#[derive(Clone)]
274struct ComponentBinary {
275 id: String,
276 source: PathBuf,
277 manifest_bytes: Vec<u8>,
278 manifest_path: String,
279 manifest_hash_sha256: String,
280}
281
282#[derive(Clone)]
283struct LockComponentBinary {
284 logical_path: String,
285 source: PathBuf,
286}
287
288#[derive(Clone)]
289struct ComponentManifestFile {
290 component_id: String,
291 manifest_path: String,
292 manifest_bytes: Vec<u8>,
293 manifest_hash_sha256: String,
294}
295
296struct AssetFile {
297 logical_path: String,
298 source: PathBuf,
299}
300
301struct ExtraFile {
302 logical_path: String,
303 source: PathBuf,
304}
305
306#[derive(Clone)]
307struct FlowFile {
308 logical_path: String,
309 bytes: Vec<u8>,
310 media_type: &'static str,
311}
312
313fn assemble_manifest(
314 config: &PackConfig,
315 pack_root: &Path,
316 secret_requirements: &[SecretRequirement],
317 include_extra_dirs: bool,
318) -> Result<BuildProducts> {
319 let components = build_components(&config.components)?;
320 let (flows, flow_files) = build_flows(&config.flows, pack_root)?;
321 let dependencies = build_dependencies(&config.dependencies)?;
322 let assets = collect_assets(&config.assets, pack_root)?;
323 let extra_files = if include_extra_dirs {
324 collect_extra_dir_files(pack_root)?
325 } else {
326 Vec::new()
327 };
328 let component_manifests: Vec<_> = components.iter().map(|c| c.0.clone()).collect();
329 let bootstrap = build_bootstrap(config, &flows, &component_manifests)?;
330 let extensions = normalize_extensions(&config.extensions);
331
332 let manifest = PackManifest {
333 schema_version: "pack-v1".to_string(),
334 pack_id: PackId::new(config.pack_id.clone()).context("invalid pack_id")?,
335 version: Version::parse(&config.version)
336 .context("invalid pack version (expected semver)")?,
337 kind: map_kind(&config.kind)?,
338 publisher: config.publisher.clone(),
339 components: component_manifests,
340 flows,
341 dependencies,
342 capabilities: derive_pack_capabilities(&components),
343 secret_requirements: secret_requirements.to_vec(),
344 signatures: PackSignatures::default(),
345 bootstrap,
346 extensions,
347 };
348
349 Ok(BuildProducts {
350 manifest,
351 components: components.into_iter().map(|(_, bin)| bin).collect(),
352 lock_components: Vec::new(),
353 component_manifest_files: Vec::new(),
354 flow_files,
355 assets,
356 extra_files,
357 })
358}
359
360fn build_components(
361 configs: &[ComponentConfig],
362) -> Result<Vec<(ComponentManifest, ComponentBinary)>> {
363 let mut seen = BTreeSet::new();
364 let mut result = Vec::new();
365
366 for cfg in configs {
367 if !seen.insert(cfg.id.clone()) {
368 anyhow::bail!("duplicate component id {}", cfg.id);
369 }
370
371 info!(id = %cfg.id, wasm = %cfg.wasm.display(), "adding component");
372 let (manifest, binary) = resolve_component_artifacts(cfg)?;
373
374 result.push((manifest, binary));
375 }
376
377 Ok(result)
378}
379
380fn resolve_component_artifacts(
381 cfg: &ComponentConfig,
382) -> Result<(ComponentManifest, ComponentBinary)> {
383 let resolved_wasm = resolve_component_wasm_path(&cfg.wasm)?;
384
385 let mut manifest = if let Some(from_disk) = load_component_manifest_from_disk(&resolved_wasm)? {
386 if from_disk.id.to_string() != cfg.id {
387 anyhow::bail!(
388 "component manifest id {} does not match pack.yaml id {}",
389 from_disk.id,
390 cfg.id
391 );
392 }
393 if from_disk.version.to_string() != cfg.version {
394 anyhow::bail!(
395 "component manifest version {} does not match pack.yaml version {}",
396 from_disk.version,
397 cfg.version
398 );
399 }
400 from_disk
401 } else {
402 manifest_from_config(cfg)?
403 };
404
405 if manifest.operations.is_empty() && !cfg.operations.is_empty() {
407 manifest.operations = cfg
408 .operations
409 .iter()
410 .map(operation_from_config)
411 .collect::<Result<Vec<_>>>()?;
412 }
413
414 let manifest_bytes =
415 serde_cbor::to_vec(&manifest).context("encode component manifest to cbor")?;
416 let mut sha = Sha256::new();
417 sha.update(&manifest_bytes);
418 let manifest_hash_sha256 = format!("sha256:{:x}", sha.finalize());
419 let manifest_path = format!("components/{}.manifest.cbor", cfg.id);
420
421 let binary = ComponentBinary {
422 id: cfg.id.clone(),
423 source: resolved_wasm,
424 manifest_bytes,
425 manifest_path,
426 manifest_hash_sha256,
427 };
428
429 Ok((manifest, binary))
430}
431
432fn manifest_from_config(cfg: &ComponentConfig) -> Result<ComponentManifest> {
433 Ok(ComponentManifest {
434 id: ComponentId::new(cfg.id.clone())
435 .with_context(|| format!("invalid component id {}", cfg.id))?,
436 version: Version::parse(&cfg.version)
437 .context("invalid component version (expected semver)")?,
438 supports: cfg.supports.iter().map(|k| k.to_kind()).collect(),
439 world: cfg.world.clone(),
440 profiles: cfg.profiles.clone(),
441 capabilities: cfg.capabilities.clone(),
442 configurators: convert_configurators(cfg)?,
443 operations: cfg
444 .operations
445 .iter()
446 .map(operation_from_config)
447 .collect::<Result<Vec<_>>>()?,
448 config_schema: cfg.config_schema.clone(),
449 resources: cfg.resources.clone().unwrap_or_default(),
450 dev_flows: BTreeMap::new(),
451 })
452}
453
454fn resolve_component_wasm_path(path: &Path) -> Result<PathBuf> {
455 if path.is_file() {
456 return Ok(path.to_path_buf());
457 }
458 if !path.exists() {
459 anyhow::bail!("component path {} does not exist", path.display());
460 }
461 if !path.is_dir() {
462 anyhow::bail!(
463 "component path {} must be a file or directory",
464 path.display()
465 );
466 }
467
468 let mut component_candidates = Vec::new();
469 let mut wasm_candidates = Vec::new();
470 let mut stack = vec![path.to_path_buf()];
471 while let Some(current) = stack.pop() {
472 for entry in fs::read_dir(¤t)
473 .with_context(|| format!("failed to list components in {}", current.display()))?
474 {
475 let entry = entry?;
476 let entry_type = entry.file_type()?;
477 let entry_path = entry.path();
478 if entry_type.is_dir() {
479 stack.push(entry_path);
480 continue;
481 }
482 if entry_type.is_file() && entry_path.extension() == Some(std::ffi::OsStr::new("wasm"))
483 {
484 let file_name = entry_path
485 .file_name()
486 .and_then(|n| n.to_str())
487 .unwrap_or_default();
488 if file_name.ends_with(".component.wasm") {
489 component_candidates.push(entry_path);
490 } else {
491 wasm_candidates.push(entry_path);
492 }
493 }
494 }
495 }
496
497 let choose = |mut list: Vec<PathBuf>| -> Result<PathBuf> {
498 list.sort();
499 if list.len() == 1 {
500 Ok(list.remove(0))
501 } else {
502 let options = list
503 .iter()
504 .map(|p| p.strip_prefix(path).unwrap_or(p).display().to_string())
505 .collect::<Vec<_>>()
506 .join(", ");
507 anyhow::bail!(
508 "multiple wasm artifacts found under {}: {} (pick a single *.component.wasm or *.wasm)",
509 path.display(),
510 options
511 );
512 }
513 };
514
515 if !component_candidates.is_empty() {
516 return choose(component_candidates);
517 }
518 if !wasm_candidates.is_empty() {
519 return choose(wasm_candidates);
520 }
521
522 anyhow::bail!(
523 "no wasm artifact found under {}; expected *.component.wasm or *.wasm",
524 path.display()
525 );
526}
527
528fn load_component_manifest_from_disk(path: &Path) -> Result<Option<ComponentManifest>> {
529 let manifest_dir = if path.is_dir() {
530 path.to_path_buf()
531 } else {
532 path.parent()
533 .map(Path::to_path_buf)
534 .ok_or_else(|| anyhow!("component path {} has no parent directory", path.display()))?
535 };
536 let candidates = [
537 manifest_dir.join("component.manifest.cbor"),
538 manifest_dir.join("component.manifest.json"),
539 manifest_dir.join("component.json"),
540 ];
541 for manifest_path in candidates {
542 if !manifest_path.exists() {
543 continue;
544 }
545 let manifest = load_component_manifest_from_file(&manifest_path)?;
546 return Ok(Some(manifest));
547 }
548
549 Ok(None)
550}
551
552fn operation_from_config(cfg: &ComponentOperationConfig) -> Result<ComponentOperation> {
553 Ok(ComponentOperation {
554 name: cfg.name.clone(),
555 input_schema: cfg.input_schema.clone(),
556 output_schema: cfg.output_schema.clone(),
557 })
558}
559
560fn convert_configurators(cfg: &ComponentConfig) -> Result<Option<ComponentConfigurators>> {
561 let Some(configurators) = cfg.configurators.as_ref() else {
562 return Ok(None);
563 };
564
565 let basic = match &configurators.basic {
566 Some(id) => Some(FlowId::new(id).context("invalid configurator flow id")?),
567 None => None,
568 };
569 let full = match &configurators.full {
570 Some(id) => Some(FlowId::new(id).context("invalid configurator flow id")?),
571 None => None,
572 };
573
574 Ok(Some(ComponentConfigurators { basic, full }))
575}
576
577fn build_bootstrap(
578 config: &PackConfig,
579 flows: &[PackFlowEntry],
580 components: &[ComponentManifest],
581) -> Result<Option<BootstrapSpec>> {
582 let Some(raw) = config.bootstrap.as_ref() else {
583 return Ok(None);
584 };
585
586 let flow_ids: BTreeSet<_> = flows.iter().map(|flow| flow.id.to_string()).collect();
587 let component_ids: BTreeSet<_> = components.iter().map(|c| c.id.to_string()).collect();
588
589 let mut spec = BootstrapSpec::default();
590
591 if let Some(install_flow) = &raw.install_flow {
592 if !flow_ids.contains(install_flow) {
593 anyhow::bail!(
594 "bootstrap.install_flow references unknown flow {}",
595 install_flow
596 );
597 }
598 spec.install_flow = Some(install_flow.clone());
599 }
600
601 if let Some(upgrade_flow) = &raw.upgrade_flow {
602 if !flow_ids.contains(upgrade_flow) {
603 anyhow::bail!(
604 "bootstrap.upgrade_flow references unknown flow {}",
605 upgrade_flow
606 );
607 }
608 spec.upgrade_flow = Some(upgrade_flow.clone());
609 }
610
611 if let Some(component) = &raw.installer_component {
612 if !component_ids.contains(component) {
613 anyhow::bail!(
614 "bootstrap.installer_component references unknown component {}",
615 component
616 );
617 }
618 spec.installer_component = Some(component.clone());
619 }
620
621 if spec.install_flow.is_none()
622 && spec.upgrade_flow.is_none()
623 && spec.installer_component.is_none()
624 {
625 return Ok(None);
626 }
627
628 Ok(Some(spec))
629}
630
631fn build_flows(
632 configs: &[FlowConfig],
633 pack_root: &Path,
634) -> Result<(Vec<PackFlowEntry>, Vec<FlowFile>)> {
635 let mut seen = BTreeSet::new();
636 let mut entries = Vec::new();
637 let mut flow_files = Vec::new();
638
639 for cfg in configs {
640 info!(id = %cfg.id, path = %cfg.file.display(), "compiling flow");
641 let yaml_bytes = fs::read(&cfg.file)
642 .with_context(|| format!("failed to read flow {}", cfg.file.display()))?;
643 let mut flow: Flow = compile_ygtc_file(&cfg.file)
644 .with_context(|| format!("failed to compile {}", cfg.file.display()))?;
645 populate_component_exec_operations(&mut flow, &cfg.file).with_context(|| {
646 format!(
647 "failed to resolve component.exec operations in {}",
648 cfg.file.display()
649 )
650 })?;
651 normalize_legacy_component_exec_ids(&mut flow)?;
652 let summary = load_flow_resolve_summary(pack_root, cfg, &flow)?;
653 apply_summary_component_ids(&mut flow, &summary).with_context(|| {
654 format!("failed to resolve component ids in {}", cfg.file.display())
655 })?;
656
657 let flow_id = flow.id.to_string();
658 if !seen.insert(flow_id.clone()) {
659 anyhow::bail!("duplicate flow id {}", flow_id);
660 }
661
662 let entrypoints = if cfg.entrypoints.is_empty() {
663 flow.entrypoints.keys().cloned().collect()
664 } else {
665 cfg.entrypoints.clone()
666 };
667
668 let flow_entry = PackFlowEntry {
669 id: flow.id.clone(),
670 kind: flow.kind,
671 flow,
672 tags: cfg.tags.clone(),
673 entrypoints,
674 };
675
676 let flow_id = flow_entry.id.to_string();
677 flow_files.push(FlowFile {
678 logical_path: format!("flows/{flow_id}/flow.ygtc"),
679 bytes: yaml_bytes,
680 media_type: "application/yaml",
681 });
682 flow_files.push(FlowFile {
683 logical_path: format!("flows/{flow_id}/flow.json"),
684 bytes: serde_json::to_vec(&flow_entry.flow).context("encode flow json")?,
685 media_type: "application/json",
686 });
687 entries.push(flow_entry);
688 }
689
690 Ok((entries, flow_files))
691}
692
693fn apply_summary_component_ids(flow: &mut Flow, summary: &FlowResolveSummaryV1) -> Result<()> {
694 for (node_id, node) in flow.nodes.iter_mut() {
695 let resolved = summary.nodes.get(node_id.as_str()).ok_or_else(|| {
696 anyhow!(
697 "flow resolve summary missing node {} (expected component id for node)",
698 node_id
699 )
700 })?;
701 let summary_id = resolved.component_id.as_str();
702 if node.component.id.as_str().is_empty() || node.component.id.as_str() == "component.exec" {
703 node.component.id = resolved.component_id.clone();
704 continue;
705 }
706 if node.component.id.as_str() != summary_id {
707 anyhow::bail!(
708 "node {} component id {} does not match resolve summary {}",
709 node_id,
710 node.component.id.as_str(),
711 summary_id
712 );
713 }
714 }
715 Ok(())
716}
717
718fn populate_component_exec_operations(flow: &mut Flow, path: &Path) -> Result<()> {
719 let needs_op = flow.nodes.values().any(|node| {
720 node.component.id.as_str() == "component.exec" && node.component.operation.is_none()
721 });
722 if !needs_op {
723 return Ok(());
724 }
725
726 let flow_doc = load_ygtc_from_path(path)?;
727 let mut operations = BTreeMap::new();
728
729 for (node_id, node_doc) in flow_doc.nodes {
730 let value = serde_json::to_value(&node_doc)
731 .with_context(|| format!("failed to normalize component.exec node {}", node_id))?;
732 let normalized = normalize_node_map(value)?;
733 if !normalized.operation.trim().is_empty() {
734 operations.insert(node_id, normalized.operation);
735 }
736 }
737
738 for (node_id, node) in flow.nodes.iter_mut() {
739 if node.component.id.as_str() != "component.exec" || node.component.operation.is_some() {
740 continue;
741 }
742 if let Some(op) = operations.get(node_id.as_str()) {
743 node.component.operation = Some(op.clone());
744 }
745 }
746
747 Ok(())
748}
749
750fn normalize_legacy_component_exec_ids(flow: &mut Flow) -> Result<()> {
751 for (node_id, node) in flow.nodes.iter_mut() {
752 if node.component.id.as_str() != "component.exec" {
753 continue;
754 }
755 let Some(op) = node.component.operation.as_deref() else {
756 continue;
757 };
758 if !op.contains('.') && !op.contains(':') {
759 continue;
760 }
761 node.component.id = ComponentId::new(op).with_context(|| {
762 format!("invalid component id {} resolved for node {}", op, node_id)
763 })?;
764 node.component.operation = None;
765 }
766 Ok(())
767}
768
769fn build_dependencies(configs: &[crate::config::DependencyConfig]) -> Result<Vec<PackDependency>> {
770 let mut deps = Vec::new();
771 let mut seen = BTreeSet::new();
772 for cfg in configs {
773 if !seen.insert(cfg.alias.clone()) {
774 anyhow::bail!("duplicate dependency alias {}", cfg.alias);
775 }
776 deps.push(PackDependency {
777 alias: cfg.alias.clone(),
778 pack_id: PackId::new(cfg.pack_id.clone()).context("invalid dependency pack_id")?,
779 version_req: SemverReq::parse(&cfg.version_req)
780 .context("invalid dependency version requirement")?,
781 required_capabilities: cfg.required_capabilities.clone(),
782 });
783 }
784 Ok(deps)
785}
786
787fn collect_assets(configs: &[AssetConfig], pack_root: &Path) -> Result<Vec<AssetFile>> {
788 let mut assets = Vec::new();
789 for cfg in configs {
790 let logical = cfg
791 .path
792 .strip_prefix(pack_root)
793 .unwrap_or(&cfg.path)
794 .components()
795 .map(|c| c.as_os_str().to_string_lossy().into_owned())
796 .collect::<Vec<_>>()
797 .join("/");
798 if logical.is_empty() {
799 anyhow::bail!("invalid asset path {}", cfg.path.display());
800 }
801 assets.push(AssetFile {
802 logical_path: logical,
803 source: cfg.path.clone(),
804 });
805 }
806 Ok(assets)
807}
808
809fn collect_extra_dir_files(pack_root: &Path) -> Result<Vec<ExtraFile>> {
810 let excluded = [
811 "components",
812 "flows",
813 "assets",
814 "dist",
815 "target",
816 ".git",
817 ".github",
818 ".idea",
819 ".vscode",
820 "node_modules",
821 ];
822 let mut entries = Vec::new();
823 let mut seen = BTreeSet::new();
824 for entry in fs::read_dir(pack_root)
825 .with_context(|| format!("failed to list pack root {}", pack_root.display()))?
826 {
827 let entry = entry?;
828 let entry_type = entry.file_type()?;
829 if !entry_type.is_dir() {
830 continue;
831 }
832 let name = entry.file_name();
833 let name = name.to_string_lossy();
834 if name.starts_with('.') || excluded.contains(&name.as_ref()) {
835 continue;
836 }
837 let root = entry.path();
838 for sub in WalkDir::new(&root)
839 .into_iter()
840 .filter_entry(|walk| !walk.file_name().to_string_lossy().starts_with('.'))
841 .filter_map(Result::ok)
842 {
843 if !sub.file_type().is_file() {
844 continue;
845 }
846 let logical = sub
847 .path()
848 .strip_prefix(pack_root)
849 .unwrap_or(sub.path())
850 .components()
851 .map(|c| c.as_os_str().to_string_lossy().into_owned())
852 .collect::<Vec<_>>()
853 .join("/");
854 if logical.is_empty() || !seen.insert(logical.clone()) {
855 continue;
856 }
857 entries.push(ExtraFile {
858 logical_path: logical,
859 source: sub.path().to_path_buf(),
860 });
861 }
862 }
863 Ok(entries)
864}
865
866fn normalize_extensions(
867 extensions: &Option<BTreeMap<String, greentic_types::ExtensionRef>>,
868) -> Option<BTreeMap<String, greentic_types::ExtensionRef>> {
869 extensions.as_ref().filter(|map| !map.is_empty()).cloned()
870}
871
872fn merge_component_manifest_extension(
873 extensions: Option<BTreeMap<String, ExtensionRef>>,
874 manifest_files: &[ComponentManifestFile],
875) -> Result<Option<BTreeMap<String, ExtensionRef>>> {
876 if manifest_files.is_empty() {
877 return Ok(extensions);
878 }
879
880 let entries: Vec<_> = manifest_files
881 .iter()
882 .map(|entry| ComponentManifestIndexEntryV1 {
883 component_id: entry.component_id.clone(),
884 manifest_file: entry.manifest_path.clone(),
885 encoding: ManifestEncoding::Cbor,
886 content_hash: Some(entry.manifest_hash_sha256.clone()),
887 })
888 .collect();
889
890 let index = ComponentManifestIndexV1::new(entries);
891 let value = index
892 .to_extension_value()
893 .context("serialize component manifest index extension")?;
894
895 let ext = ExtensionRef {
896 kind: EXT_COMPONENT_MANIFEST_INDEX_V1.to_string(),
897 version: "v1".to_string(),
898 digest: None,
899 location: None,
900 inline: Some(ExtensionInline::Other(value)),
901 };
902
903 let mut map = extensions.unwrap_or_default();
904 map.insert(EXT_COMPONENT_MANIFEST_INDEX_V1.to_string(), ext);
905 if map.is_empty() {
906 Ok(None)
907 } else {
908 Ok(Some(map))
909 }
910}
911
912fn merge_component_sources_extension(
913 extensions: Option<BTreeMap<String, ExtensionRef>>,
914 lock: &greentic_pack::pack_lock::PackLockV1,
915 _bundle: BundleMode,
916 manifest_paths: Option<&std::collections::BTreeMap<String, String>>,
917) -> Result<Option<BTreeMap<String, ExtensionRef>>> {
918 let mut entries = Vec::new();
919 for comp in &lock.components {
920 if comp.r#ref.starts_with("file://") {
921 continue;
922 }
923 let source = match ComponentSourceRef::from_str(&comp.r#ref) {
924 Ok(parsed) => parsed,
925 Err(_) => {
926 eprintln!(
927 "warning: skipping pack.lock entry `{}` with unsupported ref {}",
928 comp.name, comp.r#ref
929 );
930 continue;
931 }
932 };
933 let manifest_path = manifest_paths.and_then(|paths| {
934 comp.component_id
935 .as_ref()
936 .map(|id| id.as_str())
937 .and_then(|key| paths.get(key))
938 .or_else(|| paths.get(&comp.name))
939 .cloned()
940 });
941 let artifact = if comp.bundled {
942 let wasm_path = comp.bundled_path.clone().ok_or_else(|| {
943 anyhow!(
944 "pack.lock entry {} marked bundled but missing bundled_path",
945 comp.name
946 )
947 })?;
948 ArtifactLocationV1::Inline {
949 wasm_path,
950 manifest_path,
951 }
952 } else {
953 ArtifactLocationV1::Remote
954 };
955 entries.push(ComponentSourceEntryV1 {
956 name: comp.name.clone(),
957 component_id: comp.component_id.clone(),
958 source,
959 resolved: ResolvedComponentV1 {
960 digest: comp.digest.clone(),
961 signature: None,
962 signed_by: None,
963 },
964 artifact,
965 licensing_hint: None,
966 metering_hint: None,
967 });
968 }
969
970 if entries.is_empty() {
971 return Ok(extensions);
972 }
973
974 let payload = ComponentSourcesV1::new(entries)
975 .to_extension_value()
976 .context("serialize component_sources extension")?;
977
978 let ext = ExtensionRef {
979 kind: EXT_COMPONENT_SOURCES_V1.to_string(),
980 version: "v1".to_string(),
981 digest: None,
982 location: None,
983 inline: Some(ExtensionInline::Other(payload)),
984 };
985
986 let mut map = extensions.unwrap_or_default();
987 map.insert(EXT_COMPONENT_SOURCES_V1.to_string(), ext);
988 if map.is_empty() {
989 Ok(None)
990 } else {
991 Ok(Some(map))
992 }
993}
994
995fn derive_pack_capabilities(
996 components: &[(ComponentManifest, ComponentBinary)],
997) -> Vec<ComponentCapability> {
998 let mut seen = BTreeSet::new();
999 let mut caps = Vec::new();
1000
1001 for (component, _) in components {
1002 let mut add = |name: &str| {
1003 if seen.insert(name.to_string()) {
1004 caps.push(ComponentCapability {
1005 name: name.to_string(),
1006 description: None,
1007 });
1008 }
1009 };
1010
1011 if component.capabilities.host.secrets.is_some() {
1012 add("host:secrets");
1013 }
1014 if let Some(state) = &component.capabilities.host.state {
1015 if state.read {
1016 add("host:state:read");
1017 }
1018 if state.write {
1019 add("host:state:write");
1020 }
1021 }
1022 if component.capabilities.host.messaging.is_some() {
1023 add("host:messaging");
1024 }
1025 if component.capabilities.host.events.is_some() {
1026 add("host:events");
1027 }
1028 if component.capabilities.host.http.is_some() {
1029 add("host:http");
1030 }
1031 if component.capabilities.host.telemetry.is_some() {
1032 add("host:telemetry");
1033 }
1034 if component.capabilities.host.iac.is_some() {
1035 add("host:iac");
1036 }
1037 if let Some(fs) = component.capabilities.wasi.filesystem.as_ref() {
1038 add(&format!(
1039 "wasi:fs:{}",
1040 format!("{:?}", fs.mode).to_lowercase()
1041 ));
1042 if !fs.mounts.is_empty() {
1043 add("wasi:fs:mounts");
1044 }
1045 }
1046 if component.capabilities.wasi.random {
1047 add("wasi:random");
1048 }
1049 if component.capabilities.wasi.clocks {
1050 add("wasi:clocks");
1051 }
1052 }
1053
1054 caps
1055}
1056
1057fn map_kind(raw: &str) -> Result<PackKind> {
1058 match raw.to_ascii_lowercase().as_str() {
1059 "application" => Ok(PackKind::Application),
1060 "provider" => Ok(PackKind::Provider),
1061 "infrastructure" => Ok(PackKind::Infrastructure),
1062 "library" => Ok(PackKind::Library),
1063 other => Err(anyhow!("unknown pack kind {}", other)),
1064 }
1065}
1066
1067fn package_gtpack(
1068 out_path: &Path,
1069 manifest_bytes: &[u8],
1070 build: &BuildProducts,
1071 bundle: BundleMode,
1072) -> Result<()> {
1073 if let Some(parent) = out_path.parent() {
1074 fs::create_dir_all(parent)
1075 .with_context(|| format!("failed to create {}", parent.display()))?;
1076 }
1077
1078 let file = fs::File::create(out_path)
1079 .with_context(|| format!("failed to create {}", out_path.display()))?;
1080 let mut writer = ZipWriter::new(file);
1081 let options = SimpleFileOptions::default()
1082 .compression_method(CompressionMethod::Stored)
1083 .unix_permissions(0o644);
1084
1085 let mut sbom_entries = Vec::new();
1086 let mut written_paths = BTreeSet::new();
1087 record_sbom_entry(
1088 &mut sbom_entries,
1089 "manifest.cbor",
1090 manifest_bytes,
1091 "application/cbor",
1092 );
1093 written_paths.insert("manifest.cbor".to_string());
1094 write_zip_entry(&mut writer, "manifest.cbor", manifest_bytes, options)?;
1095
1096 let mut flow_files = build.flow_files.clone();
1097 flow_files.sort_by(|a, b| a.logical_path.cmp(&b.logical_path));
1098 for flow_file in flow_files {
1099 if written_paths.insert(flow_file.logical_path.clone()) {
1100 record_sbom_entry(
1101 &mut sbom_entries,
1102 &flow_file.logical_path,
1103 &flow_file.bytes,
1104 flow_file.media_type,
1105 );
1106 write_zip_entry(
1107 &mut writer,
1108 &flow_file.logical_path,
1109 &flow_file.bytes,
1110 options,
1111 )?;
1112 }
1113 }
1114
1115 let mut component_wasm_paths = BTreeSet::new();
1116 if bundle != BundleMode::None {
1117 for comp in &build.components {
1118 component_wasm_paths.insert(format!("components/{}.wasm", comp.id));
1119 }
1120 }
1121
1122 let mut lock_components = build.lock_components.clone();
1123 lock_components.sort_by(|a, b| a.logical_path.cmp(&b.logical_path));
1124 for comp in lock_components {
1125 if component_wasm_paths.contains(&comp.logical_path) {
1126 continue;
1127 }
1128 if !written_paths.insert(comp.logical_path.clone()) {
1129 continue;
1130 }
1131 let bytes = fs::read(&comp.source).with_context(|| {
1132 format!("failed to read cached component {}", comp.source.display())
1133 })?;
1134 record_sbom_entry(
1135 &mut sbom_entries,
1136 &comp.logical_path,
1137 &bytes,
1138 "application/wasm",
1139 );
1140 write_zip_entry(&mut writer, &comp.logical_path, &bytes, options)?;
1141 }
1142
1143 let mut lock_manifests = build.component_manifest_files.clone();
1144 lock_manifests.sort_by(|a, b| a.manifest_path.cmp(&b.manifest_path));
1145 for manifest in lock_manifests {
1146 if written_paths.insert(manifest.manifest_path.clone()) {
1147 record_sbom_entry(
1148 &mut sbom_entries,
1149 &manifest.manifest_path,
1150 &manifest.manifest_bytes,
1151 "application/cbor",
1152 );
1153 write_zip_entry(
1154 &mut writer,
1155 &manifest.manifest_path,
1156 &manifest.manifest_bytes,
1157 options,
1158 )?;
1159 }
1160 }
1161
1162 if bundle != BundleMode::None {
1163 let mut components = build.components.clone();
1164 components.sort_by(|a, b| a.id.cmp(&b.id));
1165 for comp in components {
1166 let logical_wasm = format!("components/{}.wasm", comp.id);
1167 let wasm_bytes = fs::read(&comp.source)
1168 .with_context(|| format!("failed to read component {}", comp.source.display()))?;
1169 if written_paths.insert(logical_wasm.clone()) {
1170 record_sbom_entry(
1171 &mut sbom_entries,
1172 &logical_wasm,
1173 &wasm_bytes,
1174 "application/wasm",
1175 );
1176 write_zip_entry(&mut writer, &logical_wasm, &wasm_bytes, options)?;
1177 }
1178
1179 if written_paths.insert(comp.manifest_path.clone()) {
1180 record_sbom_entry(
1181 &mut sbom_entries,
1182 &comp.manifest_path,
1183 &comp.manifest_bytes,
1184 "application/cbor",
1185 );
1186 write_zip_entry(
1187 &mut writer,
1188 &comp.manifest_path,
1189 &comp.manifest_bytes,
1190 options,
1191 )?;
1192 }
1193 }
1194 }
1195
1196 let mut asset_entries: Vec<_> = build
1197 .assets
1198 .iter()
1199 .map(|a| (format!("assets/{}", &a.logical_path), a.source.clone()))
1200 .collect();
1201 asset_entries.sort_by(|a, b| a.0.cmp(&b.0));
1202 for (logical, source) in asset_entries {
1203 let bytes = fs::read(&source)
1204 .with_context(|| format!("failed to read asset {}", source.display()))?;
1205 if written_paths.insert(logical.clone()) {
1206 record_sbom_entry(
1207 &mut sbom_entries,
1208 &logical,
1209 &bytes,
1210 "application/octet-stream",
1211 );
1212 write_zip_entry(&mut writer, &logical, &bytes, options)?;
1213 }
1214 }
1215
1216 let mut extra_entries: Vec<_> = build
1217 .extra_files
1218 .iter()
1219 .map(|e| (e.logical_path.clone(), e.source.clone()))
1220 .collect();
1221 extra_entries.sort_by(|a, b| a.0.cmp(&b.0));
1222 for (logical, source) in extra_entries {
1223 if !written_paths.insert(logical.clone()) {
1224 continue;
1225 }
1226 let bytes = fs::read(&source)
1227 .with_context(|| format!("failed to read extra file {}", source.display()))?;
1228 record_sbom_entry(
1229 &mut sbom_entries,
1230 &logical,
1231 &bytes,
1232 "application/octet-stream",
1233 );
1234 write_zip_entry(&mut writer, &logical, &bytes, options)?;
1235 }
1236
1237 sbom_entries.sort_by(|a, b| a.path.cmp(&b.path));
1238 let sbom_doc = SbomDocument {
1239 format: SBOM_FORMAT.to_string(),
1240 files: sbom_entries,
1241 };
1242 let sbom_bytes = serde_cbor::to_vec(&sbom_doc).context("failed to encode sbom.cbor")?;
1243 write_zip_entry(&mut writer, "sbom.cbor", &sbom_bytes, options)?;
1244
1245 writer
1246 .finish()
1247 .context("failed to finalise gtpack archive")?;
1248 Ok(())
1249}
1250
1251async fn collect_lock_component_artifacts(
1252 lock: &mut greentic_pack::pack_lock::PackLockV1,
1253 runtime: &RuntimeContext,
1254 bundle: BundleMode,
1255 allow_missing: bool,
1256) -> Result<Vec<LockComponentBinary>> {
1257 let dist = DistClient::new(DistOptions {
1258 cache_dir: runtime.cache_dir(),
1259 allow_tags: true,
1260 offline: runtime.network_policy() == NetworkPolicy::Offline,
1261 allow_insecure_local_http: false,
1262 });
1263
1264 let mut artifacts = Vec::new();
1265 let mut seen_paths = BTreeSet::new();
1266 for comp in &mut lock.components {
1267 if comp.r#ref.starts_with("file://") {
1268 comp.bundled = false;
1269 comp.bundled_path = None;
1270 comp.wasm_sha256 = None;
1271 comp.resolved_digest = None;
1272 continue;
1273 }
1274 let parsed = ComponentSourceRef::from_str(&comp.r#ref).ok();
1275 let is_tag = parsed.as_ref().map(|r| r.is_tag()).unwrap_or(false);
1276 let should_bundle = is_tag || bundle == BundleMode::Cache;
1277 if !should_bundle {
1278 comp.bundled = false;
1279 comp.bundled_path = None;
1280 comp.wasm_sha256 = None;
1281 comp.resolved_digest = None;
1282 continue;
1283 }
1284
1285 let resolved = if is_tag {
1286 let item = if runtime.network_policy() == NetworkPolicy::Offline {
1287 dist.ensure_cached(&comp.digest).await.map_err(|err| {
1288 anyhow!(
1289 "tag ref {} must be bundled but cache is missing ({})",
1290 comp.r#ref,
1291 err
1292 )
1293 })?
1294 } else {
1295 dist.resolve_ref(&comp.r#ref)
1296 .await
1297 .map_err(|err| anyhow!("failed to resolve {}: {}", comp.r#ref, err))?
1298 };
1299 let cache_path = item.cache_path.clone().ok_or_else(|| {
1300 anyhow!("tag ref {} resolved but cache path is missing", comp.r#ref)
1301 })?;
1302 ResolvedLockItem { item, cache_path }
1303 } else {
1304 let mut resolved = dist
1305 .ensure_cached(&comp.digest)
1306 .await
1307 .ok()
1308 .and_then(|item| item.cache_path.clone().map(|path| (item, path)));
1309 if resolved.is_none()
1310 && runtime.network_policy() != NetworkPolicy::Offline
1311 && !allow_missing
1312 && comp.r#ref.starts_with("oci://")
1313 {
1314 let item = dist
1315 .resolve_ref(&comp.r#ref)
1316 .await
1317 .map_err(|err| anyhow!("failed to resolve {}: {}", comp.r#ref, err))?;
1318 if let Some(path) = item.cache_path.clone() {
1319 resolved = Some((item, path));
1320 }
1321 }
1322 let Some((item, path)) = resolved else {
1323 eprintln!(
1324 "warning: component {} is not cached; skipping embed",
1325 comp.name
1326 );
1327 comp.bundled = false;
1328 comp.bundled_path = None;
1329 comp.wasm_sha256 = None;
1330 comp.resolved_digest = None;
1331 continue;
1332 };
1333 ResolvedLockItem {
1334 item,
1335 cache_path: path,
1336 }
1337 };
1338
1339 let cache_path = resolved.cache_path;
1340 let bytes = fs::read(&cache_path)
1341 .with_context(|| format!("failed to read cached component {}", cache_path.display()))?;
1342 let wasm_sha256 = format!("{:x}", Sha256::digest(&bytes));
1343 let logical_path = if is_tag {
1344 format!("blobs/sha256/{}.wasm", wasm_sha256)
1345 } else {
1346 format!("components/{}.wasm", comp.name)
1347 };
1348
1349 comp.bundled = true;
1350 comp.bundled_path = Some(logical_path.clone());
1351 comp.wasm_sha256 = Some(wasm_sha256.clone());
1352 if is_tag {
1353 comp.digest = format!("sha256:{wasm_sha256}");
1354 comp.resolved_digest = Some(resolved.item.digest.clone());
1355 } else {
1356 comp.resolved_digest = None;
1357 }
1358
1359 if seen_paths.insert(logical_path.clone()) {
1360 artifacts.push(LockComponentBinary {
1361 logical_path: logical_path.clone(),
1362 source: cache_path.clone(),
1363 });
1364 }
1365 if let Some(component_id) = comp.component_id.as_ref()
1366 && comp.bundled
1367 {
1368 let alias_path = format!("components/{}.wasm", component_id.as_str());
1369 if alias_path != logical_path && seen_paths.insert(alias_path.clone()) {
1370 artifacts.push(LockComponentBinary {
1371 logical_path: alias_path,
1372 source: cache_path.clone(),
1373 });
1374 }
1375 }
1376 }
1377
1378 Ok(artifacts)
1379}
1380
1381struct ResolvedLockItem {
1382 item: greentic_distributor_client::ResolvedArtifact,
1383 cache_path: PathBuf,
1384}
1385
1386struct MaterializedComponents {
1387 components: Vec<ComponentManifest>,
1388 manifest_files: Vec<ComponentManifestFile>,
1389 manifest_paths: Option<BTreeMap<String, String>>,
1390}
1391
1392fn record_sbom_entry(entries: &mut Vec<SbomEntry>, path: &str, bytes: &[u8], media_type: &str) {
1393 entries.push(SbomEntry {
1394 path: path.to_string(),
1395 size: bytes.len() as u64,
1396 hash_blake3: blake3::hash(bytes).to_hex().to_string(),
1397 media_type: media_type.to_string(),
1398 });
1399}
1400
1401fn write_zip_entry(
1402 writer: &mut ZipWriter<std::fs::File>,
1403 logical_path: &str,
1404 bytes: &[u8],
1405 options: SimpleFileOptions,
1406) -> Result<()> {
1407 writer
1408 .start_file(logical_path, options)
1409 .with_context(|| format!("failed to start {}", logical_path))?;
1410 writer
1411 .write_all(bytes)
1412 .with_context(|| format!("failed to write {}", logical_path))?;
1413 Ok(())
1414}
1415
1416fn write_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
1417 if let Some(parent) = path.parent() {
1418 fs::create_dir_all(parent)
1419 .with_context(|| format!("failed to create directory {}", parent.display()))?;
1420 }
1421 fs::write(path, bytes).with_context(|| format!("failed to write {}", path.display()))?;
1422 Ok(())
1423}
1424
1425fn write_stub_wasm(path: &Path) -> Result<()> {
1426 const STUB: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
1427 write_bytes(path, STUB)
1428}
1429
1430fn collect_component_manifest_files(
1431 components: &[ComponentBinary],
1432 extra: &[ComponentManifestFile],
1433) -> Vec<ComponentManifestFile> {
1434 let mut files: Vec<ComponentManifestFile> = components
1435 .iter()
1436 .map(|binary| ComponentManifestFile {
1437 component_id: binary.id.clone(),
1438 manifest_path: binary.manifest_path.clone(),
1439 manifest_bytes: binary.manifest_bytes.clone(),
1440 manifest_hash_sha256: binary.manifest_hash_sha256.clone(),
1441 })
1442 .collect();
1443 files.extend(extra.iter().cloned());
1444 files.sort_by(|a, b| a.component_id.cmp(&b.component_id));
1445 files.dedup_by(|a, b| a.component_id == b.component_id);
1446 files
1447}
1448
1449fn materialize_flow_components(
1450 pack_dir: &Path,
1451 flows: &[PackFlowEntry],
1452 pack_lock: &greentic_pack::pack_lock::PackLockV1,
1453 components: &[ComponentBinary],
1454 lock_components: &[LockComponentBinary],
1455 require_component_manifests: bool,
1456) -> Result<MaterializedComponents> {
1457 let referenced = collect_flow_component_ids(flows);
1458 if referenced.is_empty() {
1459 return Ok(MaterializedComponents {
1460 components: Vec::new(),
1461 manifest_files: Vec::new(),
1462 manifest_paths: None,
1463 });
1464 }
1465
1466 let mut existing = BTreeSet::new();
1467 for component in components {
1468 existing.insert(component.id.clone());
1469 }
1470
1471 let mut lock_by_id = BTreeMap::new();
1472 let mut lock_by_name = BTreeMap::new();
1473 for entry in &pack_lock.components {
1474 if let Some(component_id) = entry.component_id.as_ref() {
1475 lock_by_id.insert(component_id.as_str().to_string(), entry);
1476 }
1477 lock_by_name.insert(entry.name.clone(), entry);
1478 }
1479
1480 let mut bundle_sources = BTreeMap::new();
1481 for entry in lock_components {
1482 bundle_sources.insert(entry.logical_path.clone(), entry.source.clone());
1483 }
1484
1485 let mut materialized_components = Vec::new();
1486 let mut manifest_files = Vec::new();
1487 let mut manifest_paths: BTreeMap<String, String> = BTreeMap::new();
1488
1489 for component_id in referenced {
1490 if existing.contains(&component_id) {
1491 continue;
1492 }
1493
1494 let lock_entry = lock_by_id
1495 .get(&component_id)
1496 .copied()
1497 .or_else(|| lock_by_name.get(&component_id).copied());
1498 let Some(lock_entry) = lock_entry else {
1499 handle_missing_component_manifest(&component_id, None, require_component_manifests)?;
1500 continue;
1501 };
1502 if !lock_entry.bundled {
1503 if require_component_manifests {
1504 anyhow::bail!(
1505 "component {} is not bundled; cannot materialize manifest without local artifacts",
1506 lock_entry.name
1507 );
1508 }
1509 eprintln!(
1510 "warning: component {} is not bundled; pack will emit PACK_COMPONENT_NOT_EXPLICIT",
1511 lock_entry.name
1512 );
1513 continue;
1514 }
1515
1516 let bundled_source = lock_entry
1517 .bundled_path
1518 .as_deref()
1519 .and_then(|path| bundle_sources.get(path));
1520 let manifest = load_component_manifest_for_lock(pack_dir, lock_entry, bundled_source)?;
1521
1522 let Some(manifest) = manifest else {
1523 handle_missing_component_manifest(
1524 &component_id,
1525 Some(&lock_entry.name),
1526 require_component_manifests,
1527 )?;
1528 continue;
1529 };
1530
1531 if let Some(lock_id) = lock_entry.component_id.as_ref()
1532 && manifest.id.as_str() != lock_id.as_str()
1533 {
1534 anyhow::bail!(
1535 "component manifest id {} does not match pack.lock component_id {}",
1536 manifest.id.as_str(),
1537 lock_id.as_str()
1538 );
1539 }
1540
1541 let manifest_file = component_manifest_file_from_manifest(&manifest)?;
1542 manifest_paths.insert(
1543 manifest.id.as_str().to_string(),
1544 manifest_file.manifest_path.clone(),
1545 );
1546 manifest_paths.insert(lock_entry.name.clone(), manifest_file.manifest_path.clone());
1547
1548 materialized_components.push(manifest);
1549 manifest_files.push(manifest_file);
1550 }
1551
1552 let manifest_paths = if manifest_paths.is_empty() {
1553 None
1554 } else {
1555 Some(manifest_paths)
1556 };
1557
1558 Ok(MaterializedComponents {
1559 components: materialized_components,
1560 manifest_files,
1561 manifest_paths,
1562 })
1563}
1564
1565fn collect_flow_component_ids(flows: &[PackFlowEntry]) -> BTreeSet<String> {
1566 let mut ids = BTreeSet::new();
1567 for flow in flows {
1568 for node in flow.flow.nodes.values() {
1569 if node.component.pack_alias.is_some() {
1570 continue;
1571 }
1572 let id = node.component.id.as_str();
1573 if !id.is_empty() {
1574 ids.insert(id.to_string());
1575 }
1576 }
1577 }
1578 ids
1579}
1580
1581fn load_component_manifest_for_lock(
1582 pack_dir: &Path,
1583 lock_entry: &greentic_pack::pack_lock::LockedComponent,
1584 bundled_source: Option<&PathBuf>,
1585) -> Result<Option<ComponentManifest>> {
1586 let mut search_paths = Vec::new();
1587 if let Some(component_id) = lock_entry.component_id.as_ref() {
1588 let id = component_id.as_str();
1589 search_paths.extend(component_manifest_search_paths(pack_dir, id));
1590 }
1591 search_paths.extend(component_manifest_search_paths(pack_dir, &lock_entry.name));
1592 if let Some(source) = bundled_source
1593 && let Some(parent) = source.parent()
1594 {
1595 search_paths.push(parent.join("component.manifest.cbor"));
1596 search_paths.push(parent.join("component.manifest.json"));
1597 }
1598
1599 for path in search_paths {
1600 if path.exists() {
1601 return Ok(Some(load_component_manifest_from_file(&path)?));
1602 }
1603 }
1604
1605 Ok(None)
1606}
1607
1608fn component_manifest_search_paths(pack_dir: &Path, name: &str) -> Vec<PathBuf> {
1609 vec![
1610 pack_dir
1611 .join("components")
1612 .join(format!("{name}.manifest.cbor")),
1613 pack_dir
1614 .join("components")
1615 .join(format!("{name}.manifest.json")),
1616 pack_dir
1617 .join("components")
1618 .join(name)
1619 .join("component.manifest.cbor"),
1620 pack_dir
1621 .join("components")
1622 .join(name)
1623 .join("component.manifest.json"),
1624 ]
1625}
1626
1627fn load_component_manifest_from_file(path: &Path) -> Result<ComponentManifest> {
1628 let bytes = fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
1629 if path
1630 .extension()
1631 .and_then(|ext| ext.to_str())
1632 .is_some_and(|ext| ext.eq_ignore_ascii_case("cbor"))
1633 {
1634 let manifest = serde_cbor::from_slice(&bytes)
1635 .with_context(|| format!("{} is not valid CBOR", path.display()))?;
1636 return Ok(manifest);
1637 }
1638
1639 let manifest = serde_json::from_slice(&bytes)
1640 .with_context(|| format!("{} is not valid JSON", path.display()))?;
1641 Ok(manifest)
1642}
1643
1644fn component_manifest_file_from_manifest(
1645 manifest: &ComponentManifest,
1646) -> Result<ComponentManifestFile> {
1647 let manifest_bytes =
1648 serde_cbor::to_vec(manifest).context("encode component manifest to cbor")?;
1649 let mut sha = Sha256::new();
1650 sha.update(&manifest_bytes);
1651 let manifest_hash_sha256 = format!("sha256:{:x}", sha.finalize());
1652 let manifest_path = format!("components/{}.manifest.cbor", manifest.id.as_str());
1653
1654 Ok(ComponentManifestFile {
1655 component_id: manifest.id.as_str().to_string(),
1656 manifest_path,
1657 manifest_bytes,
1658 manifest_hash_sha256,
1659 })
1660}
1661
1662fn handle_missing_component_manifest(
1663 component_id: &str,
1664 component_name: Option<&str>,
1665 require_component_manifests: bool,
1666) -> Result<()> {
1667 let label = component_name.unwrap_or(component_id);
1668 if require_component_manifests {
1669 anyhow::bail!(
1670 "component manifest metadata missing for {} (supply component.manifest.json or use --require-component-manifests=false)",
1671 label
1672 );
1673 }
1674 eprintln!(
1675 "warning: component manifest metadata missing for {}; pack will emit PACK_COMPONENT_NOT_EXPLICIT",
1676 label
1677 );
1678 Ok(())
1679}
1680
1681fn aggregate_secret_requirements(
1682 components: &[ComponentConfig],
1683 override_path: Option<&Path>,
1684 default_scope: Option<&str>,
1685) -> Result<Vec<SecretRequirement>> {
1686 let default_scope = default_scope.map(parse_default_scope).transpose()?;
1687 let mut merged: BTreeMap<(String, String, String), SecretRequirement> = BTreeMap::new();
1688
1689 let mut process_req = |req: &SecretRequirement, source: &str| -> Result<()> {
1690 let mut req = req.clone();
1691 if req.scope.is_none() {
1692 if let Some(scope) = default_scope.clone() {
1693 req.scope = Some(scope);
1694 tracing::warn!(
1695 key = %secret_key_string(&req),
1696 source,
1697 "secret requirement missing scope; applying default scope"
1698 );
1699 } else {
1700 anyhow::bail!(
1701 "secret requirement {} from {} is missing scope (provide --default-secret-scope or fix the component manifest)",
1702 secret_key_string(&req),
1703 source
1704 );
1705 }
1706 }
1707 let scope = req.scope.as_ref().expect("scope present");
1708 let fmt = fmt_key(&req);
1709 let key_tuple = (req.key.clone().into(), scope_key(scope), fmt.clone());
1710 if let Some(existing) = merged.get_mut(&key_tuple) {
1711 merge_requirement(existing, &req);
1712 } else {
1713 merged.insert(key_tuple, req);
1714 }
1715 Ok(())
1716 };
1717
1718 for component in components {
1719 if let Some(secret_caps) = component.capabilities.host.secrets.as_ref() {
1720 for req in &secret_caps.required {
1721 process_req(req, &component.id)?;
1722 }
1723 }
1724 }
1725
1726 if let Some(path) = override_path {
1727 let contents = fs::read_to_string(path)
1728 .with_context(|| format!("failed to read secrets override {}", path.display()))?;
1729 let value: serde_json::Value = if path
1730 .extension()
1731 .and_then(|ext| ext.to_str())
1732 .map(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
1733 .unwrap_or(false)
1734 {
1735 let yaml: YamlValue = serde_yaml_bw::from_str(&contents)
1736 .with_context(|| format!("{} is not valid YAML", path.display()))?;
1737 serde_json::to_value(yaml).context("failed to normalise YAML secrets override")?
1738 } else {
1739 serde_json::from_str(&contents)
1740 .with_context(|| format!("{} is not valid JSON", path.display()))?
1741 };
1742
1743 let overrides: Vec<SecretRequirement> =
1744 serde_json::from_value(value).with_context(|| {
1745 format!(
1746 "{} must be an array of secret requirements (migration bridge)",
1747 path.display()
1748 )
1749 })?;
1750 for req in &overrides {
1751 process_req(req, &format!("override:{}", path.display()))?;
1752 }
1753 }
1754
1755 let mut out: Vec<SecretRequirement> = merged.into_values().collect();
1756 out.sort_by(|a, b| {
1757 let a_scope = a.scope.as_ref().map(scope_key).unwrap_or_default();
1758 let b_scope = b.scope.as_ref().map(scope_key).unwrap_or_default();
1759 (a_scope, secret_key_string(a), fmt_key(a)).cmp(&(
1760 b_scope,
1761 secret_key_string(b),
1762 fmt_key(b),
1763 ))
1764 });
1765 Ok(out)
1766}
1767
1768fn fmt_key(req: &SecretRequirement) -> String {
1769 req.format
1770 .as_ref()
1771 .map(|f| format!("{:?}", f))
1772 .unwrap_or_else(|| "unspecified".to_string())
1773}
1774
1775fn scope_key(scope: &SecretScope) -> String {
1776 format!(
1777 "{}/{}/{}",
1778 &scope.env,
1779 &scope.tenant,
1780 scope
1781 .team
1782 .as_deref()
1783 .map(|t| t.to_string())
1784 .unwrap_or_else(|| "_".to_string())
1785 )
1786}
1787
1788fn secret_key_string(req: &SecretRequirement) -> String {
1789 let key: String = req.key.clone().into();
1790 key
1791}
1792
1793fn merge_requirement(base: &mut SecretRequirement, incoming: &SecretRequirement) {
1794 if base.description.is_none() {
1795 base.description = incoming.description.clone();
1796 }
1797 if let Some(schema) = &incoming.schema {
1798 if base.schema.is_none() {
1799 base.schema = Some(schema.clone());
1800 } else if base.schema.as_ref() != Some(schema) {
1801 tracing::warn!(
1802 key = %secret_key_string(base),
1803 "conflicting secret schema encountered; keeping first"
1804 );
1805 }
1806 }
1807
1808 if !incoming.examples.is_empty() {
1809 for example in &incoming.examples {
1810 if !base.examples.contains(example) {
1811 base.examples.push(example.clone());
1812 }
1813 }
1814 }
1815
1816 base.required = base.required || incoming.required;
1817}
1818
1819fn parse_default_scope(raw: &str) -> Result<SecretScope> {
1820 let parts: Vec<_> = raw.split('/').collect();
1821 if parts.len() < 2 || parts.len() > 3 {
1822 anyhow::bail!(
1823 "default secret scope must be ENV/TENANT or ENV/TENANT/TEAM (got {})",
1824 raw
1825 );
1826 }
1827 Ok(SecretScope {
1828 env: parts[0].to_string(),
1829 tenant: parts[1].to_string(),
1830 team: parts.get(2).map(|s| s.to_string()),
1831 })
1832}
1833
1834fn write_secret_requirements_file(
1835 pack_root: &Path,
1836 requirements: &[SecretRequirement],
1837 logical_name: &str,
1838) -> Result<PathBuf> {
1839 let path = pack_root.join(".packc").join(logical_name);
1840 if let Some(parent) = path.parent() {
1841 fs::create_dir_all(parent)
1842 .with_context(|| format!("failed to create {}", parent.display()))?;
1843 }
1844 let data = serde_json::to_vec_pretty(&requirements)
1845 .context("failed to serialise secret requirements")?;
1846 fs::write(&path, data).with_context(|| format!("failed to write {}", path.display()))?;
1847 Ok(path)
1848}
1849
1850#[cfg(test)]
1851mod tests {
1852 use super::*;
1853 use crate::config::BootstrapConfig;
1854 use greentic_pack::pack_lock::{LockedComponent, PackLockV1};
1855 use greentic_types::flow::FlowKind;
1856 use serde_json::json;
1857 use sha2::{Digest, Sha256};
1858 use std::collections::BTreeSet;
1859 use std::fs::File;
1860 use std::io::Read;
1861 use std::{fs, path::PathBuf};
1862 use tempfile::tempdir;
1863 use zip::ZipArchive;
1864
1865 #[test]
1866 fn map_kind_accepts_known_values() {
1867 assert!(matches!(
1868 map_kind("application").unwrap(),
1869 PackKind::Application
1870 ));
1871 assert!(matches!(map_kind("provider").unwrap(), PackKind::Provider));
1872 assert!(matches!(
1873 map_kind("infrastructure").unwrap(),
1874 PackKind::Infrastructure
1875 ));
1876 assert!(matches!(map_kind("library").unwrap(), PackKind::Library));
1877 assert!(map_kind("unknown").is_err());
1878 }
1879
1880 #[test]
1881 fn collect_assets_preserves_relative_paths() {
1882 let root = PathBuf::from("/packs/demo");
1883 let assets = vec![AssetConfig {
1884 path: root.join("assets").join("foo.txt"),
1885 }];
1886 let collected = collect_assets(&assets, &root).expect("collect assets");
1887 assert_eq!(collected[0].logical_path, "assets/foo.txt");
1888 }
1889
1890 #[test]
1891 fn collect_extra_dir_files_skips_hidden_and_known_dirs() {
1892 let temp = tempdir().expect("temp dir");
1893 let root = temp.path();
1894 fs::create_dir_all(root.join("schemas")).expect("schemas dir");
1895 fs::create_dir_all(root.join("schemas").join(".nested")).expect("nested hidden dir");
1896 fs::create_dir_all(root.join(".hidden")).expect("hidden dir");
1897 fs::create_dir_all(root.join("assets")).expect("assets dir");
1898 fs::write(root.join("schemas").join("config.schema.json"), b"{}").expect("schema file");
1899 fs::write(
1900 root.join("schemas").join(".nested").join("skip.json"),
1901 b"{}",
1902 )
1903 .expect("nested hidden file");
1904 fs::write(root.join(".hidden").join("secret.txt"), b"nope").expect("hidden file");
1905 fs::write(root.join("assets").join("asset.txt"), b"nope").expect("asset file");
1906
1907 let collected = collect_extra_dir_files(root).expect("collect extra dirs");
1908 let paths: BTreeSet<_> = collected.iter().map(|e| e.logical_path.as_str()).collect();
1909 assert!(paths.contains("schemas/config.schema.json"));
1910 assert!(!paths.contains("schemas/.nested/skip.json"));
1911 assert!(!paths.contains(".hidden/secret.txt"));
1912 assert!(!paths.iter().any(|path| path.starts_with("assets/")));
1913 }
1914
1915 #[test]
1916 fn build_bootstrap_requires_known_references() {
1917 let config = pack_config_with_bootstrap(BootstrapConfig {
1918 install_flow: Some("flow.a".to_string()),
1919 upgrade_flow: None,
1920 installer_component: Some("component.a".to_string()),
1921 });
1922 let flows = vec![flow_entry("flow.a")];
1923 let components = vec![minimal_component_manifest("component.a")];
1924
1925 let bootstrap = build_bootstrap(&config, &flows, &components)
1926 .expect("bootstrap populated")
1927 .expect("bootstrap present");
1928
1929 assert_eq!(bootstrap.install_flow.as_deref(), Some("flow.a"));
1930 assert_eq!(bootstrap.upgrade_flow, None);
1931 assert_eq!(
1932 bootstrap.installer_component.as_deref(),
1933 Some("component.a")
1934 );
1935 }
1936
1937 #[test]
1938 fn build_bootstrap_rejects_unknown_flow() {
1939 let config = pack_config_with_bootstrap(BootstrapConfig {
1940 install_flow: Some("missing".to_string()),
1941 upgrade_flow: None,
1942 installer_component: Some("component.a".to_string()),
1943 });
1944 let flows = vec![flow_entry("flow.a")];
1945 let components = vec![minimal_component_manifest("component.a")];
1946
1947 let err = build_bootstrap(&config, &flows, &components).unwrap_err();
1948 assert!(
1949 err.to_string()
1950 .contains("bootstrap.install_flow references unknown flow"),
1951 "unexpected error: {err}"
1952 );
1953 }
1954
1955 #[test]
1956 fn component_manifest_without_dev_flows_defaults_to_empty() {
1957 let manifest: ComponentManifest = serde_json::from_value(json!({
1958 "id": "component.dev",
1959 "version": "1.0.0",
1960 "supports": ["messaging"],
1961 "world": "greentic:demo@1.0.0",
1962 "profiles": { "default": "default", "supported": ["default"] },
1963 "capabilities": { "wasi": {}, "host": {} },
1964 "operations": [],
1965 "resources": {}
1966 }))
1967 .expect("manifest without dev_flows");
1968
1969 assert!(manifest.dev_flows.is_empty());
1970
1971 let pack_manifest = pack_manifest_with_component(manifest.clone());
1972 let encoded = encode_pack_manifest(&pack_manifest).expect("encode manifest");
1973 let decoded: PackManifest =
1974 greentic_types::decode_pack_manifest(&encoded).expect("decode manifest");
1975 let stored = decoded
1976 .components
1977 .iter()
1978 .find(|item| item.id == manifest.id)
1979 .expect("component present");
1980 assert!(stored.dev_flows.is_empty());
1981 }
1982
1983 #[test]
1984 fn dev_flows_round_trip_in_manifest_and_gtpack() {
1985 let component = manifest_with_dev_flow();
1986 let pack_manifest = pack_manifest_with_component(component.clone());
1987 let manifest_bytes = encode_pack_manifest(&pack_manifest).expect("encode manifest");
1988
1989 let decoded: PackManifest =
1990 greentic_types::decode_pack_manifest(&manifest_bytes).expect("decode manifest");
1991 let decoded_component = decoded
1992 .components
1993 .iter()
1994 .find(|item| item.id == component.id)
1995 .expect("component present");
1996 assert_eq!(decoded_component.dev_flows, component.dev_flows);
1997
1998 let temp = tempdir().expect("temp dir");
1999 let wasm_path = temp.path().join("component.wasm");
2000 write_stub_wasm(&wasm_path).expect("write stub wasm");
2001
2002 let build = BuildProducts {
2003 manifest: pack_manifest,
2004 components: vec![ComponentBinary {
2005 id: component.id.to_string(),
2006 source: wasm_path,
2007 manifest_bytes: serde_cbor::to_vec(&component).expect("component cbor"),
2008 manifest_path: format!("components/{}.manifest.cbor", component.id),
2009 manifest_hash_sha256: {
2010 let mut sha = Sha256::new();
2011 sha.update(serde_cbor::to_vec(&component).expect("component cbor"));
2012 format!("sha256:{:x}", sha.finalize())
2013 },
2014 }],
2015 lock_components: Vec::new(),
2016 component_manifest_files: Vec::new(),
2017 flow_files: Vec::new(),
2018 assets: Vec::new(),
2019 extra_files: Vec::new(),
2020 };
2021
2022 let out = temp.path().join("demo.gtpack");
2023 package_gtpack(&out, &manifest_bytes, &build, BundleMode::Cache).expect("package gtpack");
2024
2025 let mut archive = ZipArchive::new(fs::File::open(&out).expect("open gtpack"))
2026 .expect("read gtpack archive");
2027 let mut manifest_entry = archive.by_name("manifest.cbor").expect("manifest.cbor");
2028 let mut stored = Vec::new();
2029 manifest_entry
2030 .read_to_end(&mut stored)
2031 .expect("read manifest");
2032 let decoded: PackManifest =
2033 greentic_types::decode_pack_manifest(&stored).expect("decode packaged manifest");
2034
2035 let stored_component = decoded
2036 .components
2037 .iter()
2038 .find(|item| item.id == component.id)
2039 .expect("component preserved");
2040 assert_eq!(stored_component.dev_flows, component.dev_flows);
2041 }
2042
2043 #[test]
2044 fn component_sources_extension_respects_bundle() {
2045 let lock_tag = PackLockV1::new(vec![LockedComponent {
2046 name: "demo.tagged".into(),
2047 r#ref: "oci://ghcr.io/demo/component:1.0.0".into(),
2048 digest: "sha256:deadbeef".into(),
2049 component_id: None,
2050 bundled: true,
2051 bundled_path: Some("blobs/sha256/deadbeef.wasm".into()),
2052 wasm_sha256: Some("deadbeef".repeat(8)),
2053 resolved_digest: Some("sha256:deadbeef".into()),
2054 }]);
2055
2056 let ext_none = merge_component_sources_extension(None, &lock_tag, BundleMode::None, None)
2057 .expect("ext");
2058 let value = match ext_none
2059 .unwrap()
2060 .get(EXT_COMPONENT_SOURCES_V1)
2061 .and_then(|e| e.inline.as_ref())
2062 {
2063 Some(ExtensionInline::Other(v)) => v.clone(),
2064 _ => panic!("missing inline"),
2065 };
2066 let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2067 assert!(matches!(
2068 decoded.components[0].artifact,
2069 ArtifactLocationV1::Inline { .. }
2070 ));
2071
2072 let lock_digest = PackLockV1::new(vec![LockedComponent {
2073 name: "demo.component".into(),
2074 r#ref: "oci://ghcr.io/demo/component@sha256:deadbeef".into(),
2075 digest: "sha256:deadbeef".into(),
2076 component_id: None,
2077 bundled: false,
2078 bundled_path: None,
2079 wasm_sha256: None,
2080 resolved_digest: None,
2081 }]);
2082
2083 let ext_none =
2084 merge_component_sources_extension(None, &lock_digest, BundleMode::None, None)
2085 .expect("ext");
2086 let value = match ext_none
2087 .unwrap()
2088 .get(EXT_COMPONENT_SOURCES_V1)
2089 .and_then(|e| e.inline.as_ref())
2090 {
2091 Some(ExtensionInline::Other(v)) => v.clone(),
2092 _ => panic!("missing inline"),
2093 };
2094 let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2095 assert!(matches!(
2096 decoded.components[0].artifact,
2097 ArtifactLocationV1::Remote
2098 ));
2099
2100 let lock_digest_bundled = PackLockV1::new(vec![LockedComponent {
2101 name: "demo.component".into(),
2102 r#ref: "oci://ghcr.io/demo/component@sha256:deadbeef".into(),
2103 digest: "sha256:deadbeef".into(),
2104 component_id: None,
2105 bundled: true,
2106 bundled_path: Some("components/demo.component.wasm".into()),
2107 wasm_sha256: Some("deadbeef".repeat(8)),
2108 resolved_digest: None,
2109 }]);
2110
2111 let ext_cache =
2112 merge_component_sources_extension(None, &lock_digest_bundled, BundleMode::Cache, None)
2113 .expect("ext");
2114 let value = match ext_cache
2115 .unwrap()
2116 .get(EXT_COMPONENT_SOURCES_V1)
2117 .and_then(|e| e.inline.as_ref())
2118 {
2119 Some(ExtensionInline::Other(v)) => v.clone(),
2120 _ => panic!("missing inline"),
2121 };
2122 let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2123 assert!(matches!(
2124 decoded.components[0].artifact,
2125 ArtifactLocationV1::Inline { .. }
2126 ));
2127 }
2128
2129 #[test]
2130 fn component_sources_extension_skips_file_refs() {
2131 let lock = PackLockV1::new(vec![LockedComponent {
2132 name: "local.component".into(),
2133 r#ref: "file:///tmp/component.wasm".into(),
2134 digest: "sha256:deadbeef".into(),
2135 component_id: None,
2136 bundled: false,
2137 bundled_path: None,
2138 wasm_sha256: None,
2139 resolved_digest: None,
2140 }]);
2141
2142 let ext_none =
2143 merge_component_sources_extension(None, &lock, BundleMode::Cache, None).expect("ext");
2144 assert!(ext_none.is_none(), "file refs should be omitted");
2145
2146 let lock = PackLockV1::new(vec![
2147 LockedComponent {
2148 name: "local.component".into(),
2149 r#ref: "file:///tmp/component.wasm".into(),
2150 digest: "sha256:deadbeef".into(),
2151 component_id: None,
2152 bundled: false,
2153 bundled_path: None,
2154 wasm_sha256: None,
2155 resolved_digest: None,
2156 },
2157 LockedComponent {
2158 name: "remote.component".into(),
2159 r#ref: "oci://ghcr.io/demo/component:2.0.0".into(),
2160 digest: "sha256:cafebabe".into(),
2161 component_id: None,
2162 bundled: false,
2163 bundled_path: None,
2164 wasm_sha256: None,
2165 resolved_digest: None,
2166 },
2167 ]);
2168
2169 let ext_some =
2170 merge_component_sources_extension(None, &lock, BundleMode::None, None).expect("ext");
2171 let value = match ext_some
2172 .unwrap()
2173 .get(EXT_COMPONENT_SOURCES_V1)
2174 .and_then(|e| e.inline.as_ref())
2175 {
2176 Some(ExtensionInline::Other(v)) => v.clone(),
2177 _ => panic!("missing inline"),
2178 };
2179 let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2180 assert_eq!(decoded.components.len(), 1);
2181 assert!(matches!(
2182 decoded.components[0].source,
2183 ComponentSourceRef::Oci(_)
2184 ));
2185 }
2186
2187 #[test]
2188 fn build_embeds_lock_components_from_cache() {
2189 let rt = tokio::runtime::Runtime::new().expect("runtime");
2190 rt.block_on(async {
2191 let temp = tempdir().expect("temp dir");
2192 let pack_dir = temp.path().join("pack");
2193 fs::create_dir_all(pack_dir.join("flows")).expect("flows dir");
2194 fs::create_dir_all(pack_dir.join("components")).expect("components dir");
2195
2196 let wasm_path = pack_dir.join("components/dummy.wasm");
2197 fs::write(&wasm_path, [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])
2198 .expect("write wasm");
2199
2200 let flow_path = pack_dir.join("flows/main.ygtc");
2201 fs::write(
2202 &flow_path,
2203 r#"id: main
2204type: messaging
2205start: call
2206nodes:
2207 call:
2208 handle_message:
2209 text: "hi"
2210 routing: out
2211"#,
2212 )
2213 .expect("write flow");
2214
2215 let cache_dir = temp.path().join("cache");
2216 let cached_bytes = b"cached-component";
2217 let digest = format!("sha256:{:x}", Sha256::digest(cached_bytes));
2218 let cache_path = cache_dir
2219 .join(digest.trim_start_matches("sha256:"))
2220 .join("component.wasm");
2221 fs::create_dir_all(cache_path.parent().expect("cache parent")).expect("cache dir");
2222 fs::write(&cache_path, cached_bytes).expect("write cached");
2223
2224 let summary = serde_json::json!({
2225 "schema_version": 1,
2226 "flow": "main.ygtc",
2227 "nodes": {
2228 "call": {
2229 "component_id": "dummy.component",
2230 "source": {
2231 "kind": "oci",
2232 "ref": format!("oci://ghcr.io/demo/component@{digest}")
2233 },
2234 "digest": digest
2235 }
2236 }
2237 });
2238 fs::write(
2239 flow_path.with_extension("ygtc.resolve.summary.json"),
2240 serde_json::to_vec_pretty(&summary).expect("summary json"),
2241 )
2242 .expect("write summary");
2243
2244 let pack_yaml = r#"pack_id: demo.lock-bundle
2245version: 0.1.0
2246kind: application
2247publisher: Test
2248components:
2249 - id: dummy.component
2250 version: "0.1.0"
2251 world: "greentic:component/component@0.5.0"
2252 supports: ["messaging"]
2253 profiles:
2254 default: "stateless"
2255 supported: ["stateless"]
2256 capabilities:
2257 wasi: {}
2258 host: {}
2259 operations:
2260 - name: "handle_message"
2261 input_schema: {}
2262 output_schema: {}
2263 wasm: "components/dummy.wasm"
2264flows:
2265 - id: main
2266 file: flows/main.ygtc
2267 tags: [default]
2268 entrypoints: [main]
2269"#;
2270 fs::write(pack_dir.join("pack.yaml"), pack_yaml).expect("pack.yaml");
2271
2272 let runtime = crate::runtime::resolve_runtime(
2273 Some(pack_dir.as_path()),
2274 Some(cache_dir.as_path()),
2275 true,
2276 None,
2277 )
2278 .expect("runtime");
2279
2280 let opts = BuildOptions {
2281 pack_dir: pack_dir.clone(),
2282 component_out: None,
2283 manifest_out: pack_dir.join("dist/manifest.cbor"),
2284 sbom_out: None,
2285 gtpack_out: Some(pack_dir.join("dist/pack.gtpack")),
2286 lock_path: pack_dir.join("pack.lock.json"),
2287 bundle: BundleMode::Cache,
2288 dry_run: false,
2289 secrets_req: None,
2290 default_secret_scope: None,
2291 allow_oci_tags: false,
2292 require_component_manifests: false,
2293 no_extra_dirs: false,
2294 runtime,
2295 skip_update: false,
2296 };
2297
2298 run(&opts).await.expect("build");
2299
2300 let gtpack_path = opts.gtpack_out.expect("gtpack path");
2301 let mut archive = ZipArchive::new(File::open(>pack_path).expect("open gtpack"))
2302 .expect("read gtpack");
2303 assert!(
2304 archive.by_name("components/main___call.wasm").is_ok(),
2305 "missing lock component artifact in gtpack"
2306 );
2307 });
2308 }
2309
2310 #[test]
2311 #[ignore = "requires network access to fetch OCI component"]
2312 fn build_fetches_and_embeds_lock_components_online() {
2313 if std::env::var("GREENTIC_PACK_ONLINE").is_err() {
2314 return;
2315 }
2316 let rt = tokio::runtime::Runtime::new().expect("runtime");
2317 rt.block_on(async {
2318 let temp = tempdir().expect("temp dir");
2319 let pack_dir = temp.path().join("pack");
2320 fs::create_dir_all(pack_dir.join("flows")).expect("flows dir");
2321 fs::create_dir_all(pack_dir.join("components")).expect("components dir");
2322
2323 let wasm_path = pack_dir.join("components/dummy.wasm");
2324 fs::write(&wasm_path, [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])
2325 .expect("write wasm");
2326
2327 let flow_path = pack_dir.join("flows/main.ygtc");
2328 fs::write(
2329 &flow_path,
2330 r#"id: main
2331type: messaging
2332start: call
2333nodes:
2334 call:
2335 handle_message:
2336 text: "hi"
2337 routing: out
2338"#,
2339 )
2340 .expect("write flow");
2341
2342 let digest =
2343 "sha256:0904bee6ecd737506265e3f38f3e4fe6b185c20fd1b0e7c06ce03cdeedc00340";
2344 let summary = serde_json::json!({
2345 "schema_version": 1,
2346 "flow": "main.ygtc",
2347 "nodes": {
2348 "call": {
2349 "component_id": "dummy.component",
2350 "source": {
2351 "kind": "oci",
2352 "ref": format!("oci://ghcr.io/greentic-ai/components/templates@{digest}")
2353 },
2354 "digest": digest
2355 }
2356 }
2357 });
2358 fs::write(
2359 flow_path.with_extension("ygtc.resolve.summary.json"),
2360 serde_json::to_vec_pretty(&summary).expect("summary json"),
2361 )
2362 .expect("write summary");
2363
2364 let pack_yaml = r#"pack_id: demo.lock-online
2365version: 0.1.0
2366kind: application
2367publisher: Test
2368components:
2369 - id: dummy.component
2370 version: "0.1.0"
2371 world: "greentic:component/component@0.5.0"
2372 supports: ["messaging"]
2373 profiles:
2374 default: "stateless"
2375 supported: ["stateless"]
2376 capabilities:
2377 wasi: {}
2378 host: {}
2379 operations:
2380 - name: "handle_message"
2381 input_schema: {}
2382 output_schema: {}
2383 wasm: "components/dummy.wasm"
2384flows:
2385 - id: main
2386 file: flows/main.ygtc
2387 tags: [default]
2388 entrypoints: [main]
2389"#;
2390 fs::write(pack_dir.join("pack.yaml"), pack_yaml).expect("pack.yaml");
2391
2392 let cache_dir = temp.path().join("cache");
2393 let runtime = crate::runtime::resolve_runtime(
2394 Some(pack_dir.as_path()),
2395 Some(cache_dir.as_path()),
2396 false,
2397 None,
2398 )
2399 .expect("runtime");
2400
2401 let opts = BuildOptions {
2402 pack_dir: pack_dir.clone(),
2403 component_out: None,
2404 manifest_out: pack_dir.join("dist/manifest.cbor"),
2405 sbom_out: None,
2406 gtpack_out: Some(pack_dir.join("dist/pack.gtpack")),
2407 lock_path: pack_dir.join("pack.lock.json"),
2408 bundle: BundleMode::Cache,
2409 dry_run: false,
2410 secrets_req: None,
2411 default_secret_scope: None,
2412 allow_oci_tags: false,
2413 require_component_manifests: false,
2414 no_extra_dirs: false,
2415 runtime,
2416 skip_update: false,
2417 };
2418
2419 run(&opts).await.expect("build");
2420
2421 let gtpack_path = opts.gtpack_out.expect("gtpack path");
2422 let mut archive =
2423 ZipArchive::new(File::open(>pack_path).expect("open gtpack"))
2424 .expect("read gtpack");
2425 assert!(
2426 archive.by_name("components/main___call.wasm").is_ok(),
2427 "missing lock component artifact in gtpack"
2428 );
2429 });
2430 }
2431
2432 #[test]
2433 fn aggregate_secret_requirements_dedupes_and_sorts() {
2434 let component: ComponentConfig = serde_json::from_value(json!({
2435 "id": "component.a",
2436 "version": "1.0.0",
2437 "world": "greentic:demo@1.0.0",
2438 "supports": [],
2439 "profiles": { "default": "default", "supported": ["default"] },
2440 "capabilities": {
2441 "wasi": {},
2442 "host": {
2443 "secrets": {
2444 "required": [
2445 {
2446 "key": "db/password",
2447 "required": true,
2448 "scope": { "env": "dev", "tenant": "t1" },
2449 "format": "text",
2450 "description": "primary"
2451 }
2452 ]
2453 }
2454 }
2455 },
2456 "wasm": "component.wasm",
2457 "operations": [],
2458 "resources": {}
2459 }))
2460 .expect("component config");
2461
2462 let dupe: ComponentConfig = serde_json::from_value(json!({
2463 "id": "component.b",
2464 "version": "1.0.0",
2465 "world": "greentic:demo@1.0.0",
2466 "supports": [],
2467 "profiles": { "default": "default", "supported": ["default"] },
2468 "capabilities": {
2469 "wasi": {},
2470 "host": {
2471 "secrets": {
2472 "required": [
2473 {
2474 "key": "db/password",
2475 "required": true,
2476 "scope": { "env": "dev", "tenant": "t1" },
2477 "format": "text",
2478 "description": "secondary",
2479 "examples": ["example"]
2480 }
2481 ]
2482 }
2483 }
2484 },
2485 "wasm": "component.wasm",
2486 "operations": [],
2487 "resources": {}
2488 }))
2489 .expect("component config");
2490
2491 let reqs = aggregate_secret_requirements(&[component, dupe], None, None)
2492 .expect("aggregate secrets");
2493 assert_eq!(reqs.len(), 1);
2494 let req = &reqs[0];
2495 assert_eq!(req.description.as_deref(), Some("primary"));
2496 assert!(req.examples.contains(&"example".to_string()));
2497 }
2498
2499 fn pack_config_with_bootstrap(bootstrap: BootstrapConfig) -> PackConfig {
2500 PackConfig {
2501 pack_id: "demo.pack".to_string(),
2502 version: "1.0.0".to_string(),
2503 kind: "application".to_string(),
2504 publisher: "demo".to_string(),
2505 bootstrap: Some(bootstrap),
2506 components: Vec::new(),
2507 dependencies: Vec::new(),
2508 flows: Vec::new(),
2509 assets: Vec::new(),
2510 extensions: None,
2511 }
2512 }
2513
2514 fn flow_entry(id: &str) -> PackFlowEntry {
2515 let flow: Flow = serde_json::from_value(json!({
2516 "schema_version": "flow/v1",
2517 "id": id,
2518 "kind": "messaging"
2519 }))
2520 .expect("flow json");
2521
2522 PackFlowEntry {
2523 id: FlowId::new(id).expect("flow id"),
2524 kind: FlowKind::Messaging,
2525 flow,
2526 tags: Vec::new(),
2527 entrypoints: Vec::new(),
2528 }
2529 }
2530
2531 fn minimal_component_manifest(id: &str) -> ComponentManifest {
2532 serde_json::from_value(json!({
2533 "id": id,
2534 "version": "1.0.0",
2535 "supports": [],
2536 "world": "greentic:demo@1.0.0",
2537 "profiles": { "default": "default", "supported": ["default"] },
2538 "capabilities": { "wasi": {}, "host": {} },
2539 "operations": [],
2540 "resources": {}
2541 }))
2542 .expect("component manifest")
2543 }
2544
2545 fn manifest_with_dev_flow() -> ComponentManifest {
2546 serde_json::from_str(include_str!(
2547 "../tests/fixtures/component_manifest_with_dev_flows.json"
2548 ))
2549 .expect("fixture manifest")
2550 }
2551
2552 fn pack_manifest_with_component(component: ComponentManifest) -> PackManifest {
2553 let flow = serde_json::from_value(json!({
2554 "schema_version": "flow/v1",
2555 "id": "flow.dev",
2556 "kind": "messaging"
2557 }))
2558 .expect("flow json");
2559
2560 PackManifest {
2561 schema_version: "pack-v1".to_string(),
2562 pack_id: PackId::new("demo.pack").expect("pack id"),
2563 version: Version::parse("1.0.0").expect("version"),
2564 kind: PackKind::Application,
2565 publisher: "demo".to_string(),
2566 components: vec![component],
2567 flows: vec![PackFlowEntry {
2568 id: FlowId::new("flow.dev").expect("flow id"),
2569 kind: FlowKind::Messaging,
2570 flow,
2571 tags: Vec::new(),
2572 entrypoints: Vec::new(),
2573 }],
2574 dependencies: Vec::new(),
2575 capabilities: Vec::new(),
2576 secret_requirements: Vec::new(),
2577 signatures: PackSignatures::default(),
2578 bootstrap: None,
2579 extensions: None,
2580 }
2581 }
2582}