Skip to main content

packc/
build.rs

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        // Keep pack.yaml in sync before building.
144        crate::cli::update::update_pack(&opts.pack_dir, false)?;
145    }
146
147    // Resolve component references into pack.lock.json before building to ensure
148    // manifests/extensions can rely on the lockfile contents.
149    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    // Ensure operations are populated from pack.yaml when missing in the on-disk manifest.
406    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(&current)
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        let name = entry.file_name();
830        let name = name.to_string_lossy();
831        if entry_type.is_file() {
832            let logical = name.to_string();
833            if !logical.is_empty() && seen.insert(logical.clone()) {
834                entries.push(ExtraFile {
835                    logical_path: logical,
836                    source: entry.path(),
837                });
838            }
839            continue;
840        }
841        if !entry_type.is_dir() {
842            continue;
843        }
844        if name.starts_with('.') || excluded.contains(&name.as_ref()) {
845            continue;
846        }
847        let root = entry.path();
848        for sub in WalkDir::new(&root)
849            .into_iter()
850            .filter_entry(|walk| !walk.file_name().to_string_lossy().starts_with('.'))
851            .filter_map(Result::ok)
852        {
853            if !sub.file_type().is_file() {
854                continue;
855            }
856            let logical = sub
857                .path()
858                .strip_prefix(pack_root)
859                .unwrap_or(sub.path())
860                .components()
861                .map(|c| c.as_os_str().to_string_lossy().into_owned())
862                .collect::<Vec<_>>()
863                .join("/");
864            if logical.is_empty() || !seen.insert(logical.clone()) {
865                continue;
866            }
867            entries.push(ExtraFile {
868                logical_path: logical,
869                source: sub.path().to_path_buf(),
870            });
871        }
872    }
873    Ok(entries)
874}
875
876fn normalize_extensions(
877    extensions: &Option<BTreeMap<String, greentic_types::ExtensionRef>>,
878) -> Option<BTreeMap<String, greentic_types::ExtensionRef>> {
879    extensions.as_ref().filter(|map| !map.is_empty()).cloned()
880}
881
882fn merge_component_manifest_extension(
883    extensions: Option<BTreeMap<String, ExtensionRef>>,
884    manifest_files: &[ComponentManifestFile],
885) -> Result<Option<BTreeMap<String, ExtensionRef>>> {
886    if manifest_files.is_empty() {
887        return Ok(extensions);
888    }
889
890    let entries: Vec<_> = manifest_files
891        .iter()
892        .map(|entry| ComponentManifestIndexEntryV1 {
893            component_id: entry.component_id.clone(),
894            manifest_file: entry.manifest_path.clone(),
895            encoding: ManifestEncoding::Cbor,
896            content_hash: Some(entry.manifest_hash_sha256.clone()),
897        })
898        .collect();
899
900    let index = ComponentManifestIndexV1::new(entries);
901    let value = index
902        .to_extension_value()
903        .context("serialize component manifest index extension")?;
904
905    let ext = ExtensionRef {
906        kind: EXT_COMPONENT_MANIFEST_INDEX_V1.to_string(),
907        version: "v1".to_string(),
908        digest: None,
909        location: None,
910        inline: Some(ExtensionInline::Other(value)),
911    };
912
913    let mut map = extensions.unwrap_or_default();
914    map.insert(EXT_COMPONENT_MANIFEST_INDEX_V1.to_string(), ext);
915    if map.is_empty() {
916        Ok(None)
917    } else {
918        Ok(Some(map))
919    }
920}
921
922fn merge_component_sources_extension(
923    extensions: Option<BTreeMap<String, ExtensionRef>>,
924    lock: &greentic_pack::pack_lock::PackLockV1,
925    _bundle: BundleMode,
926    manifest_paths: Option<&std::collections::BTreeMap<String, String>>,
927) -> Result<Option<BTreeMap<String, ExtensionRef>>> {
928    let mut entries = Vec::new();
929    for comp in &lock.components {
930        if comp.r#ref.starts_with("file://") {
931            continue;
932        }
933        let source = match ComponentSourceRef::from_str(&comp.r#ref) {
934            Ok(parsed) => parsed,
935            Err(_) => {
936                eprintln!(
937                    "warning: skipping pack.lock entry `{}` with unsupported ref {}",
938                    comp.name, comp.r#ref
939                );
940                continue;
941            }
942        };
943        let manifest_path = manifest_paths.and_then(|paths| {
944            comp.component_id
945                .as_ref()
946                .map(|id| id.as_str())
947                .and_then(|key| paths.get(key))
948                .or_else(|| paths.get(&comp.name))
949                .cloned()
950        });
951        let artifact = if comp.bundled {
952            let wasm_path = comp.bundled_path.clone().ok_or_else(|| {
953                anyhow!(
954                    "pack.lock entry {} marked bundled but missing bundled_path",
955                    comp.name
956                )
957            })?;
958            ArtifactLocationV1::Inline {
959                wasm_path,
960                manifest_path,
961            }
962        } else {
963            ArtifactLocationV1::Remote
964        };
965        entries.push(ComponentSourceEntryV1 {
966            name: comp.name.clone(),
967            component_id: comp.component_id.clone(),
968            source,
969            resolved: ResolvedComponentV1 {
970                digest: comp.digest.clone(),
971                signature: None,
972                signed_by: None,
973            },
974            artifact,
975            licensing_hint: None,
976            metering_hint: None,
977        });
978    }
979
980    if entries.is_empty() {
981        return Ok(extensions);
982    }
983
984    let payload = ComponentSourcesV1::new(entries)
985        .to_extension_value()
986        .context("serialize component_sources extension")?;
987
988    let ext = ExtensionRef {
989        kind: EXT_COMPONENT_SOURCES_V1.to_string(),
990        version: "v1".to_string(),
991        digest: None,
992        location: None,
993        inline: Some(ExtensionInline::Other(payload)),
994    };
995
996    let mut map = extensions.unwrap_or_default();
997    map.insert(EXT_COMPONENT_SOURCES_V1.to_string(), ext);
998    if map.is_empty() {
999        Ok(None)
1000    } else {
1001        Ok(Some(map))
1002    }
1003}
1004
1005fn derive_pack_capabilities(
1006    components: &[(ComponentManifest, ComponentBinary)],
1007) -> Vec<ComponentCapability> {
1008    let mut seen = BTreeSet::new();
1009    let mut caps = Vec::new();
1010
1011    for (component, _) in components {
1012        let mut add = |name: &str| {
1013            if seen.insert(name.to_string()) {
1014                caps.push(ComponentCapability {
1015                    name: name.to_string(),
1016                    description: None,
1017                });
1018            }
1019        };
1020
1021        if component.capabilities.host.secrets.is_some() {
1022            add("host:secrets");
1023        }
1024        if let Some(state) = &component.capabilities.host.state {
1025            if state.read {
1026                add("host:state:read");
1027            }
1028            if state.write {
1029                add("host:state:write");
1030            }
1031        }
1032        if component.capabilities.host.messaging.is_some() {
1033            add("host:messaging");
1034        }
1035        if component.capabilities.host.events.is_some() {
1036            add("host:events");
1037        }
1038        if component.capabilities.host.http.is_some() {
1039            add("host:http");
1040        }
1041        if component.capabilities.host.telemetry.is_some() {
1042            add("host:telemetry");
1043        }
1044        if component.capabilities.host.iac.is_some() {
1045            add("host:iac");
1046        }
1047        if let Some(fs) = component.capabilities.wasi.filesystem.as_ref() {
1048            add(&format!(
1049                "wasi:fs:{}",
1050                format!("{:?}", fs.mode).to_lowercase()
1051            ));
1052            if !fs.mounts.is_empty() {
1053                add("wasi:fs:mounts");
1054            }
1055        }
1056        if component.capabilities.wasi.random {
1057            add("wasi:random");
1058        }
1059        if component.capabilities.wasi.clocks {
1060            add("wasi:clocks");
1061        }
1062    }
1063
1064    caps
1065}
1066
1067fn map_kind(raw: &str) -> Result<PackKind> {
1068    match raw.to_ascii_lowercase().as_str() {
1069        "application" => Ok(PackKind::Application),
1070        "provider" => Ok(PackKind::Provider),
1071        "infrastructure" => Ok(PackKind::Infrastructure),
1072        "library" => Ok(PackKind::Library),
1073        other => Err(anyhow!("unknown pack kind {}", other)),
1074    }
1075}
1076
1077fn package_gtpack(
1078    out_path: &Path,
1079    manifest_bytes: &[u8],
1080    build: &BuildProducts,
1081    bundle: BundleMode,
1082) -> Result<()> {
1083    if let Some(parent) = out_path.parent() {
1084        fs::create_dir_all(parent)
1085            .with_context(|| format!("failed to create {}", parent.display()))?;
1086    }
1087
1088    let file = fs::File::create(out_path)
1089        .with_context(|| format!("failed to create {}", out_path.display()))?;
1090    let mut writer = ZipWriter::new(file);
1091    let options = SimpleFileOptions::default()
1092        .compression_method(CompressionMethod::Stored)
1093        .unix_permissions(0o644);
1094
1095    let mut sbom_entries = Vec::new();
1096    let mut written_paths = BTreeSet::new();
1097    record_sbom_entry(
1098        &mut sbom_entries,
1099        "manifest.cbor",
1100        manifest_bytes,
1101        "application/cbor",
1102    );
1103    written_paths.insert("manifest.cbor".to_string());
1104    write_zip_entry(&mut writer, "manifest.cbor", manifest_bytes, options)?;
1105
1106    let mut flow_files = build.flow_files.clone();
1107    flow_files.sort_by(|a, b| a.logical_path.cmp(&b.logical_path));
1108    for flow_file in flow_files {
1109        if written_paths.insert(flow_file.logical_path.clone()) {
1110            record_sbom_entry(
1111                &mut sbom_entries,
1112                &flow_file.logical_path,
1113                &flow_file.bytes,
1114                flow_file.media_type,
1115            );
1116            write_zip_entry(
1117                &mut writer,
1118                &flow_file.logical_path,
1119                &flow_file.bytes,
1120                options,
1121            )?;
1122        }
1123    }
1124
1125    let mut component_wasm_paths = BTreeSet::new();
1126    if bundle != BundleMode::None {
1127        for comp in &build.components {
1128            component_wasm_paths.insert(format!("components/{}.wasm", comp.id));
1129        }
1130    }
1131
1132    let mut lock_components = build.lock_components.clone();
1133    lock_components.sort_by(|a, b| a.logical_path.cmp(&b.logical_path));
1134    for comp in lock_components {
1135        if component_wasm_paths.contains(&comp.logical_path) {
1136            continue;
1137        }
1138        if !written_paths.insert(comp.logical_path.clone()) {
1139            continue;
1140        }
1141        let bytes = fs::read(&comp.source).with_context(|| {
1142            format!("failed to read cached component {}", comp.source.display())
1143        })?;
1144        record_sbom_entry(
1145            &mut sbom_entries,
1146            &comp.logical_path,
1147            &bytes,
1148            "application/wasm",
1149        );
1150        write_zip_entry(&mut writer, &comp.logical_path, &bytes, options)?;
1151    }
1152
1153    let mut lock_manifests = build.component_manifest_files.clone();
1154    lock_manifests.sort_by(|a, b| a.manifest_path.cmp(&b.manifest_path));
1155    for manifest in lock_manifests {
1156        if written_paths.insert(manifest.manifest_path.clone()) {
1157            record_sbom_entry(
1158                &mut sbom_entries,
1159                &manifest.manifest_path,
1160                &manifest.manifest_bytes,
1161                "application/cbor",
1162            );
1163            write_zip_entry(
1164                &mut writer,
1165                &manifest.manifest_path,
1166                &manifest.manifest_bytes,
1167                options,
1168            )?;
1169        }
1170    }
1171
1172    if bundle != BundleMode::None {
1173        let mut components = build.components.clone();
1174        components.sort_by(|a, b| a.id.cmp(&b.id));
1175        for comp in components {
1176            let logical_wasm = format!("components/{}.wasm", comp.id);
1177            let wasm_bytes = fs::read(&comp.source)
1178                .with_context(|| format!("failed to read component {}", comp.source.display()))?;
1179            if written_paths.insert(logical_wasm.clone()) {
1180                record_sbom_entry(
1181                    &mut sbom_entries,
1182                    &logical_wasm,
1183                    &wasm_bytes,
1184                    "application/wasm",
1185                );
1186                write_zip_entry(&mut writer, &logical_wasm, &wasm_bytes, options)?;
1187            }
1188
1189            if written_paths.insert(comp.manifest_path.clone()) {
1190                record_sbom_entry(
1191                    &mut sbom_entries,
1192                    &comp.manifest_path,
1193                    &comp.manifest_bytes,
1194                    "application/cbor",
1195                );
1196                write_zip_entry(
1197                    &mut writer,
1198                    &comp.manifest_path,
1199                    &comp.manifest_bytes,
1200                    options,
1201                )?;
1202            }
1203        }
1204    }
1205
1206    let mut asset_entries: Vec<_> = build
1207        .assets
1208        .iter()
1209        .map(|a| (format!("assets/{}", &a.logical_path), a.source.clone()))
1210        .collect();
1211    asset_entries.sort_by(|a, b| a.0.cmp(&b.0));
1212    for (logical, source) in asset_entries {
1213        let bytes = fs::read(&source)
1214            .with_context(|| format!("failed to read asset {}", source.display()))?;
1215        if written_paths.insert(logical.clone()) {
1216            record_sbom_entry(
1217                &mut sbom_entries,
1218                &logical,
1219                &bytes,
1220                "application/octet-stream",
1221            );
1222            write_zip_entry(&mut writer, &logical, &bytes, options)?;
1223        }
1224    }
1225
1226    let mut extra_entries: Vec<_> = build
1227        .extra_files
1228        .iter()
1229        .map(|e| (e.logical_path.clone(), e.source.clone()))
1230        .collect();
1231    extra_entries.sort_by(|a, b| a.0.cmp(&b.0));
1232    for (logical, source) in extra_entries {
1233        if !written_paths.insert(logical.clone()) {
1234            continue;
1235        }
1236        let bytes = fs::read(&source)
1237            .with_context(|| format!("failed to read extra file {}", source.display()))?;
1238        record_sbom_entry(
1239            &mut sbom_entries,
1240            &logical,
1241            &bytes,
1242            "application/octet-stream",
1243        );
1244        write_zip_entry(&mut writer, &logical, &bytes, options)?;
1245    }
1246
1247    sbom_entries.sort_by(|a, b| a.path.cmp(&b.path));
1248    let sbom_doc = SbomDocument {
1249        format: SBOM_FORMAT.to_string(),
1250        files: sbom_entries,
1251    };
1252    let sbom_bytes = serde_cbor::to_vec(&sbom_doc).context("failed to encode sbom.cbor")?;
1253    write_zip_entry(&mut writer, "sbom.cbor", &sbom_bytes, options)?;
1254
1255    writer
1256        .finish()
1257        .context("failed to finalise gtpack archive")?;
1258    Ok(())
1259}
1260
1261async fn collect_lock_component_artifacts(
1262    lock: &mut greentic_pack::pack_lock::PackLockV1,
1263    runtime: &RuntimeContext,
1264    bundle: BundleMode,
1265    allow_missing: bool,
1266) -> Result<Vec<LockComponentBinary>> {
1267    let dist = DistClient::new(DistOptions {
1268        cache_dir: runtime.cache_dir(),
1269        allow_tags: true,
1270        offline: runtime.network_policy() == NetworkPolicy::Offline,
1271        allow_insecure_local_http: false,
1272    });
1273
1274    let mut artifacts = Vec::new();
1275    let mut seen_paths = BTreeSet::new();
1276    for comp in &mut lock.components {
1277        if comp.r#ref.starts_with("file://") {
1278            comp.bundled = false;
1279            comp.bundled_path = None;
1280            comp.wasm_sha256 = None;
1281            comp.resolved_digest = None;
1282            continue;
1283        }
1284        let parsed = ComponentSourceRef::from_str(&comp.r#ref).ok();
1285        let is_tag = parsed.as_ref().map(|r| r.is_tag()).unwrap_or(false);
1286        let should_bundle = is_tag || bundle == BundleMode::Cache;
1287        if !should_bundle {
1288            comp.bundled = false;
1289            comp.bundled_path = None;
1290            comp.wasm_sha256 = None;
1291            comp.resolved_digest = None;
1292            continue;
1293        }
1294
1295        let resolved = if is_tag {
1296            let item = if runtime.network_policy() == NetworkPolicy::Offline {
1297                dist.ensure_cached(&comp.digest).await.map_err(|err| {
1298                    anyhow!(
1299                        "tag ref {} must be bundled but cache is missing ({})",
1300                        comp.r#ref,
1301                        err
1302                    )
1303                })?
1304            } else {
1305                dist.resolve_ref(&comp.r#ref)
1306                    .await
1307                    .map_err(|err| anyhow!("failed to resolve {}: {}", comp.r#ref, err))?
1308            };
1309            let cache_path = item.cache_path.clone().ok_or_else(|| {
1310                anyhow!("tag ref {} resolved but cache path is missing", comp.r#ref)
1311            })?;
1312            ResolvedLockItem { item, cache_path }
1313        } else {
1314            let mut resolved = dist
1315                .ensure_cached(&comp.digest)
1316                .await
1317                .ok()
1318                .and_then(|item| item.cache_path.clone().map(|path| (item, path)));
1319            if resolved.is_none()
1320                && runtime.network_policy() != NetworkPolicy::Offline
1321                && !allow_missing
1322                && comp.r#ref.starts_with("oci://")
1323            {
1324                let item = dist
1325                    .resolve_ref(&comp.r#ref)
1326                    .await
1327                    .map_err(|err| anyhow!("failed to resolve {}: {}", comp.r#ref, err))?;
1328                if let Some(path) = item.cache_path.clone() {
1329                    resolved = Some((item, path));
1330                }
1331            }
1332            let Some((item, path)) = resolved else {
1333                eprintln!(
1334                    "warning: component {} is not cached; skipping embed",
1335                    comp.name
1336                );
1337                comp.bundled = false;
1338                comp.bundled_path = None;
1339                comp.wasm_sha256 = None;
1340                comp.resolved_digest = None;
1341                continue;
1342            };
1343            ResolvedLockItem {
1344                item,
1345                cache_path: path,
1346            }
1347        };
1348
1349        let cache_path = resolved.cache_path;
1350        let bytes = fs::read(&cache_path)
1351            .with_context(|| format!("failed to read cached component {}", cache_path.display()))?;
1352        let wasm_sha256 = format!("{:x}", Sha256::digest(&bytes));
1353        let logical_path = if is_tag {
1354            format!("blobs/sha256/{}.wasm", wasm_sha256)
1355        } else {
1356            format!("components/{}.wasm", comp.name)
1357        };
1358
1359        comp.bundled = true;
1360        comp.bundled_path = Some(logical_path.clone());
1361        comp.wasm_sha256 = Some(wasm_sha256.clone());
1362        if is_tag {
1363            comp.digest = format!("sha256:{wasm_sha256}");
1364            comp.resolved_digest = Some(resolved.item.digest.clone());
1365        } else {
1366            comp.resolved_digest = None;
1367        }
1368
1369        if seen_paths.insert(logical_path.clone()) {
1370            artifacts.push(LockComponentBinary {
1371                logical_path: logical_path.clone(),
1372                source: cache_path.clone(),
1373            });
1374        }
1375        if let Some(component_id) = comp.component_id.as_ref()
1376            && comp.bundled
1377        {
1378            let alias_path = format!("components/{}.wasm", component_id.as_str());
1379            if alias_path != logical_path && seen_paths.insert(alias_path.clone()) {
1380                artifacts.push(LockComponentBinary {
1381                    logical_path: alias_path,
1382                    source: cache_path.clone(),
1383                });
1384            }
1385        }
1386    }
1387
1388    Ok(artifacts)
1389}
1390
1391struct ResolvedLockItem {
1392    item: greentic_distributor_client::ResolvedArtifact,
1393    cache_path: PathBuf,
1394}
1395
1396struct MaterializedComponents {
1397    components: Vec<ComponentManifest>,
1398    manifest_files: Vec<ComponentManifestFile>,
1399    manifest_paths: Option<BTreeMap<String, String>>,
1400}
1401
1402fn record_sbom_entry(entries: &mut Vec<SbomEntry>, path: &str, bytes: &[u8], media_type: &str) {
1403    entries.push(SbomEntry {
1404        path: path.to_string(),
1405        size: bytes.len() as u64,
1406        hash_blake3: blake3::hash(bytes).to_hex().to_string(),
1407        media_type: media_type.to_string(),
1408    });
1409}
1410
1411fn write_zip_entry(
1412    writer: &mut ZipWriter<std::fs::File>,
1413    logical_path: &str,
1414    bytes: &[u8],
1415    options: SimpleFileOptions,
1416) -> Result<()> {
1417    writer
1418        .start_file(logical_path, options)
1419        .with_context(|| format!("failed to start {}", logical_path))?;
1420    writer
1421        .write_all(bytes)
1422        .with_context(|| format!("failed to write {}", logical_path))?;
1423    Ok(())
1424}
1425
1426fn write_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
1427    if let Some(parent) = path.parent() {
1428        fs::create_dir_all(parent)
1429            .with_context(|| format!("failed to create directory {}", parent.display()))?;
1430    }
1431    fs::write(path, bytes).with_context(|| format!("failed to write {}", path.display()))?;
1432    Ok(())
1433}
1434
1435fn write_stub_wasm(path: &Path) -> Result<()> {
1436    const STUB: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
1437    write_bytes(path, STUB)
1438}
1439
1440fn collect_component_manifest_files(
1441    components: &[ComponentBinary],
1442    extra: &[ComponentManifestFile],
1443) -> Vec<ComponentManifestFile> {
1444    let mut files: Vec<ComponentManifestFile> = components
1445        .iter()
1446        .map(|binary| ComponentManifestFile {
1447            component_id: binary.id.clone(),
1448            manifest_path: binary.manifest_path.clone(),
1449            manifest_bytes: binary.manifest_bytes.clone(),
1450            manifest_hash_sha256: binary.manifest_hash_sha256.clone(),
1451        })
1452        .collect();
1453    files.extend(extra.iter().cloned());
1454    files.sort_by(|a, b| a.component_id.cmp(&b.component_id));
1455    files.dedup_by(|a, b| a.component_id == b.component_id);
1456    files
1457}
1458
1459fn materialize_flow_components(
1460    pack_dir: &Path,
1461    flows: &[PackFlowEntry],
1462    pack_lock: &greentic_pack::pack_lock::PackLockV1,
1463    components: &[ComponentBinary],
1464    lock_components: &[LockComponentBinary],
1465    require_component_manifests: bool,
1466) -> Result<MaterializedComponents> {
1467    let referenced = collect_flow_component_ids(flows);
1468    if referenced.is_empty() {
1469        return Ok(MaterializedComponents {
1470            components: Vec::new(),
1471            manifest_files: Vec::new(),
1472            manifest_paths: None,
1473        });
1474    }
1475
1476    let mut existing = BTreeSet::new();
1477    for component in components {
1478        existing.insert(component.id.clone());
1479    }
1480
1481    let mut lock_by_id = BTreeMap::new();
1482    let mut lock_by_name = BTreeMap::new();
1483    for entry in &pack_lock.components {
1484        if let Some(component_id) = entry.component_id.as_ref() {
1485            lock_by_id.insert(component_id.as_str().to_string(), entry);
1486        }
1487        lock_by_name.insert(entry.name.clone(), entry);
1488    }
1489
1490    let mut bundle_sources = BTreeMap::new();
1491    for entry in lock_components {
1492        bundle_sources.insert(entry.logical_path.clone(), entry.source.clone());
1493    }
1494
1495    let mut materialized_components = Vec::new();
1496    let mut manifest_files = Vec::new();
1497    let mut manifest_paths: BTreeMap<String, String> = BTreeMap::new();
1498
1499    for component_id in referenced {
1500        if existing.contains(&component_id) {
1501            continue;
1502        }
1503
1504        let lock_entry = lock_by_id
1505            .get(&component_id)
1506            .copied()
1507            .or_else(|| lock_by_name.get(&component_id).copied());
1508        let Some(lock_entry) = lock_entry else {
1509            handle_missing_component_manifest(&component_id, None, require_component_manifests)?;
1510            continue;
1511        };
1512        if !lock_entry.bundled {
1513            if require_component_manifests {
1514                anyhow::bail!(
1515                    "component {} is not bundled; cannot materialize manifest without local artifacts",
1516                    lock_entry.name
1517                );
1518            }
1519            eprintln!(
1520                "warning: component {} is not bundled; pack will emit PACK_COMPONENT_NOT_EXPLICIT",
1521                lock_entry.name
1522            );
1523            continue;
1524        }
1525
1526        let bundled_source = lock_entry
1527            .bundled_path
1528            .as_deref()
1529            .and_then(|path| bundle_sources.get(path));
1530        let manifest = load_component_manifest_for_lock(pack_dir, lock_entry, bundled_source)?;
1531
1532        let Some(manifest) = manifest else {
1533            handle_missing_component_manifest(
1534                &component_id,
1535                Some(&lock_entry.name),
1536                require_component_manifests,
1537            )?;
1538            continue;
1539        };
1540
1541        if let Some(lock_id) = lock_entry.component_id.as_ref()
1542            && manifest.id.as_str() != lock_id.as_str()
1543        {
1544            anyhow::bail!(
1545                "component manifest id {} does not match pack.lock component_id {}",
1546                manifest.id.as_str(),
1547                lock_id.as_str()
1548            );
1549        }
1550
1551        let manifest_file = component_manifest_file_from_manifest(&manifest)?;
1552        manifest_paths.insert(
1553            manifest.id.as_str().to_string(),
1554            manifest_file.manifest_path.clone(),
1555        );
1556        manifest_paths.insert(lock_entry.name.clone(), manifest_file.manifest_path.clone());
1557
1558        materialized_components.push(manifest);
1559        manifest_files.push(manifest_file);
1560    }
1561
1562    let manifest_paths = if manifest_paths.is_empty() {
1563        None
1564    } else {
1565        Some(manifest_paths)
1566    };
1567
1568    Ok(MaterializedComponents {
1569        components: materialized_components,
1570        manifest_files,
1571        manifest_paths,
1572    })
1573}
1574
1575fn collect_flow_component_ids(flows: &[PackFlowEntry]) -> BTreeSet<String> {
1576    let mut ids = BTreeSet::new();
1577    for flow in flows {
1578        for node in flow.flow.nodes.values() {
1579            if node.component.pack_alias.is_some() {
1580                continue;
1581            }
1582            let id = node.component.id.as_str();
1583            if !id.is_empty() {
1584                ids.insert(id.to_string());
1585            }
1586        }
1587    }
1588    ids
1589}
1590
1591fn load_component_manifest_for_lock(
1592    pack_dir: &Path,
1593    lock_entry: &greentic_pack::pack_lock::LockedComponent,
1594    bundled_source: Option<&PathBuf>,
1595) -> Result<Option<ComponentManifest>> {
1596    let mut search_paths = Vec::new();
1597    if let Some(component_id) = lock_entry.component_id.as_ref() {
1598        let id = component_id.as_str();
1599        search_paths.extend(component_manifest_search_paths(pack_dir, id));
1600    }
1601    search_paths.extend(component_manifest_search_paths(pack_dir, &lock_entry.name));
1602    if let Some(source) = bundled_source
1603        && let Some(parent) = source.parent()
1604    {
1605        search_paths.push(parent.join("component.manifest.cbor"));
1606        search_paths.push(parent.join("component.manifest.json"));
1607    }
1608
1609    for path in search_paths {
1610        if path.exists() {
1611            return Ok(Some(load_component_manifest_from_file(&path)?));
1612        }
1613    }
1614
1615    Ok(None)
1616}
1617
1618fn component_manifest_search_paths(pack_dir: &Path, name: &str) -> Vec<PathBuf> {
1619    vec![
1620        pack_dir
1621            .join("components")
1622            .join(format!("{name}.manifest.cbor")),
1623        pack_dir
1624            .join("components")
1625            .join(format!("{name}.manifest.json")),
1626        pack_dir
1627            .join("components")
1628            .join(name)
1629            .join("component.manifest.cbor"),
1630        pack_dir
1631            .join("components")
1632            .join(name)
1633            .join("component.manifest.json"),
1634    ]
1635}
1636
1637fn load_component_manifest_from_file(path: &Path) -> Result<ComponentManifest> {
1638    let bytes = fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
1639    if path
1640        .extension()
1641        .and_then(|ext| ext.to_str())
1642        .is_some_and(|ext| ext.eq_ignore_ascii_case("cbor"))
1643    {
1644        let manifest = serde_cbor::from_slice(&bytes)
1645            .with_context(|| format!("{} is not valid CBOR", path.display()))?;
1646        return Ok(manifest);
1647    }
1648
1649    let manifest = serde_json::from_slice(&bytes)
1650        .with_context(|| format!("{} is not valid JSON", path.display()))?;
1651    Ok(manifest)
1652}
1653
1654fn component_manifest_file_from_manifest(
1655    manifest: &ComponentManifest,
1656) -> Result<ComponentManifestFile> {
1657    let manifest_bytes =
1658        serde_cbor::to_vec(manifest).context("encode component manifest to cbor")?;
1659    let mut sha = Sha256::new();
1660    sha.update(&manifest_bytes);
1661    let manifest_hash_sha256 = format!("sha256:{:x}", sha.finalize());
1662    let manifest_path = format!("components/{}.manifest.cbor", manifest.id.as_str());
1663
1664    Ok(ComponentManifestFile {
1665        component_id: manifest.id.as_str().to_string(),
1666        manifest_path,
1667        manifest_bytes,
1668        manifest_hash_sha256,
1669    })
1670}
1671
1672fn handle_missing_component_manifest(
1673    component_id: &str,
1674    component_name: Option<&str>,
1675    require_component_manifests: bool,
1676) -> Result<()> {
1677    let label = component_name.unwrap_or(component_id);
1678    if require_component_manifests {
1679        anyhow::bail!(
1680            "component manifest metadata missing for {} (supply component.manifest.json or use --require-component-manifests=false)",
1681            label
1682        );
1683    }
1684    eprintln!(
1685        "warning: component manifest metadata missing for {}; pack will emit PACK_COMPONENT_NOT_EXPLICIT",
1686        label
1687    );
1688    Ok(())
1689}
1690
1691fn aggregate_secret_requirements(
1692    components: &[ComponentConfig],
1693    override_path: Option<&Path>,
1694    default_scope: Option<&str>,
1695) -> Result<Vec<SecretRequirement>> {
1696    let default_scope = default_scope.map(parse_default_scope).transpose()?;
1697    let mut merged: BTreeMap<(String, String, String), SecretRequirement> = BTreeMap::new();
1698
1699    let mut process_req = |req: &SecretRequirement, source: &str| -> Result<()> {
1700        let mut req = req.clone();
1701        if req.scope.is_none() {
1702            if let Some(scope) = default_scope.clone() {
1703                req.scope = Some(scope);
1704                tracing::warn!(
1705                    key = %secret_key_string(&req),
1706                    source,
1707                    "secret requirement missing scope; applying default scope"
1708                );
1709            } else {
1710                anyhow::bail!(
1711                    "secret requirement {} from {} is missing scope (provide --default-secret-scope or fix the component manifest)",
1712                    secret_key_string(&req),
1713                    source
1714                );
1715            }
1716        }
1717        let scope = req.scope.as_ref().expect("scope present");
1718        let fmt = fmt_key(&req);
1719        let key_tuple = (req.key.clone().into(), scope_key(scope), fmt.clone());
1720        if let Some(existing) = merged.get_mut(&key_tuple) {
1721            merge_requirement(existing, &req);
1722        } else {
1723            merged.insert(key_tuple, req);
1724        }
1725        Ok(())
1726    };
1727
1728    for component in components {
1729        if let Some(secret_caps) = component.capabilities.host.secrets.as_ref() {
1730            for req in &secret_caps.required {
1731                process_req(req, &component.id)?;
1732            }
1733        }
1734    }
1735
1736    if let Some(path) = override_path {
1737        let contents = fs::read_to_string(path)
1738            .with_context(|| format!("failed to read secrets override {}", path.display()))?;
1739        let value: serde_json::Value = if path
1740            .extension()
1741            .and_then(|ext| ext.to_str())
1742            .map(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
1743            .unwrap_or(false)
1744        {
1745            let yaml: YamlValue = serde_yaml_bw::from_str(&contents)
1746                .with_context(|| format!("{} is not valid YAML", path.display()))?;
1747            serde_json::to_value(yaml).context("failed to normalise YAML secrets override")?
1748        } else {
1749            serde_json::from_str(&contents)
1750                .with_context(|| format!("{} is not valid JSON", path.display()))?
1751        };
1752
1753        let overrides: Vec<SecretRequirement> =
1754            serde_json::from_value(value).with_context(|| {
1755                format!(
1756                    "{} must be an array of secret requirements (migration bridge)",
1757                    path.display()
1758                )
1759            })?;
1760        for req in &overrides {
1761            process_req(req, &format!("override:{}", path.display()))?;
1762        }
1763    }
1764
1765    let mut out: Vec<SecretRequirement> = merged.into_values().collect();
1766    out.sort_by(|a, b| {
1767        let a_scope = a.scope.as_ref().map(scope_key).unwrap_or_default();
1768        let b_scope = b.scope.as_ref().map(scope_key).unwrap_or_default();
1769        (a_scope, secret_key_string(a), fmt_key(a)).cmp(&(
1770            b_scope,
1771            secret_key_string(b),
1772            fmt_key(b),
1773        ))
1774    });
1775    Ok(out)
1776}
1777
1778fn fmt_key(req: &SecretRequirement) -> String {
1779    req.format
1780        .as_ref()
1781        .map(|f| format!("{:?}", f))
1782        .unwrap_or_else(|| "unspecified".to_string())
1783}
1784
1785fn scope_key(scope: &SecretScope) -> String {
1786    format!(
1787        "{}/{}/{}",
1788        &scope.env,
1789        &scope.tenant,
1790        scope
1791            .team
1792            .as_deref()
1793            .map(|t| t.to_string())
1794            .unwrap_or_else(|| "_".to_string())
1795    )
1796}
1797
1798fn secret_key_string(req: &SecretRequirement) -> String {
1799    let key: String = req.key.clone().into();
1800    key
1801}
1802
1803fn merge_requirement(base: &mut SecretRequirement, incoming: &SecretRequirement) {
1804    if base.description.is_none() {
1805        base.description = incoming.description.clone();
1806    }
1807    if let Some(schema) = &incoming.schema {
1808        if base.schema.is_none() {
1809            base.schema = Some(schema.clone());
1810        } else if base.schema.as_ref() != Some(schema) {
1811            tracing::warn!(
1812                key = %secret_key_string(base),
1813                "conflicting secret schema encountered; keeping first"
1814            );
1815        }
1816    }
1817
1818    if !incoming.examples.is_empty() {
1819        for example in &incoming.examples {
1820            if !base.examples.contains(example) {
1821                base.examples.push(example.clone());
1822            }
1823        }
1824    }
1825
1826    base.required = base.required || incoming.required;
1827}
1828
1829fn parse_default_scope(raw: &str) -> Result<SecretScope> {
1830    let parts: Vec<_> = raw.split('/').collect();
1831    if parts.len() < 2 || parts.len() > 3 {
1832        anyhow::bail!(
1833            "default secret scope must be ENV/TENANT or ENV/TENANT/TEAM (got {})",
1834            raw
1835        );
1836    }
1837    Ok(SecretScope {
1838        env: parts[0].to_string(),
1839        tenant: parts[1].to_string(),
1840        team: parts.get(2).map(|s| s.to_string()),
1841    })
1842}
1843
1844fn write_secret_requirements_file(
1845    pack_root: &Path,
1846    requirements: &[SecretRequirement],
1847    logical_name: &str,
1848) -> Result<PathBuf> {
1849    let path = pack_root.join(".packc").join(logical_name);
1850    if let Some(parent) = path.parent() {
1851        fs::create_dir_all(parent)
1852            .with_context(|| format!("failed to create {}", parent.display()))?;
1853    }
1854    let data = serde_json::to_vec_pretty(&requirements)
1855        .context("failed to serialise secret requirements")?;
1856    fs::write(&path, data).with_context(|| format!("failed to write {}", path.display()))?;
1857    Ok(path)
1858}
1859
1860#[cfg(test)]
1861mod tests {
1862    use super::*;
1863    use crate::config::BootstrapConfig;
1864    use greentic_pack::pack_lock::{LockedComponent, PackLockV1};
1865    use greentic_types::flow::FlowKind;
1866    use serde_json::json;
1867    use sha2::{Digest, Sha256};
1868    use std::collections::BTreeSet;
1869    use std::fs::File;
1870    use std::io::Read;
1871    use std::{fs, path::PathBuf};
1872    use tempfile::tempdir;
1873    use zip::ZipArchive;
1874
1875    #[test]
1876    fn map_kind_accepts_known_values() {
1877        assert!(matches!(
1878            map_kind("application").unwrap(),
1879            PackKind::Application
1880        ));
1881        assert!(matches!(map_kind("provider").unwrap(), PackKind::Provider));
1882        assert!(matches!(
1883            map_kind("infrastructure").unwrap(),
1884            PackKind::Infrastructure
1885        ));
1886        assert!(matches!(map_kind("library").unwrap(), PackKind::Library));
1887        assert!(map_kind("unknown").is_err());
1888    }
1889
1890    #[test]
1891    fn collect_assets_preserves_relative_paths() {
1892        let root = PathBuf::from("/packs/demo");
1893        let assets = vec![AssetConfig {
1894            path: root.join("assets").join("foo.txt"),
1895        }];
1896        let collected = collect_assets(&assets, &root).expect("collect assets");
1897        assert_eq!(collected[0].logical_path, "assets/foo.txt");
1898    }
1899
1900    #[test]
1901    fn collect_extra_dir_files_skips_hidden_and_known_dirs() {
1902        let temp = tempdir().expect("temp dir");
1903        let root = temp.path();
1904        fs::create_dir_all(root.join("schemas")).expect("schemas dir");
1905        fs::create_dir_all(root.join("schemas").join(".nested")).expect("nested hidden dir");
1906        fs::create_dir_all(root.join(".hidden")).expect("hidden dir");
1907        fs::create_dir_all(root.join("assets")).expect("assets dir");
1908        fs::write(root.join("README.txt"), b"root").expect("root file");
1909        fs::write(root.join("schemas").join("config.schema.json"), b"{}").expect("schema file");
1910        fs::write(
1911            root.join("schemas").join(".nested").join("skip.json"),
1912            b"{}",
1913        )
1914        .expect("nested hidden file");
1915        fs::write(root.join(".hidden").join("secret.txt"), b"nope").expect("hidden file");
1916        fs::write(root.join("assets").join("asset.txt"), b"nope").expect("asset file");
1917
1918        let collected = collect_extra_dir_files(root).expect("collect extra dirs");
1919        let paths: BTreeSet<_> = collected.iter().map(|e| e.logical_path.as_str()).collect();
1920        assert!(paths.contains("README.txt"));
1921        assert!(paths.contains("schemas/config.schema.json"));
1922        assert!(!paths.contains("schemas/.nested/skip.json"));
1923        assert!(!paths.contains(".hidden/secret.txt"));
1924        assert!(!paths.iter().any(|path| path.starts_with("assets/")));
1925    }
1926
1927    #[test]
1928    fn build_bootstrap_requires_known_references() {
1929        let config = pack_config_with_bootstrap(BootstrapConfig {
1930            install_flow: Some("flow.a".to_string()),
1931            upgrade_flow: None,
1932            installer_component: Some("component.a".to_string()),
1933        });
1934        let flows = vec![flow_entry("flow.a")];
1935        let components = vec![minimal_component_manifest("component.a")];
1936
1937        let bootstrap = build_bootstrap(&config, &flows, &components)
1938            .expect("bootstrap populated")
1939            .expect("bootstrap present");
1940
1941        assert_eq!(bootstrap.install_flow.as_deref(), Some("flow.a"));
1942        assert_eq!(bootstrap.upgrade_flow, None);
1943        assert_eq!(
1944            bootstrap.installer_component.as_deref(),
1945            Some("component.a")
1946        );
1947    }
1948
1949    #[test]
1950    fn build_bootstrap_rejects_unknown_flow() {
1951        let config = pack_config_with_bootstrap(BootstrapConfig {
1952            install_flow: Some("missing".to_string()),
1953            upgrade_flow: None,
1954            installer_component: Some("component.a".to_string()),
1955        });
1956        let flows = vec![flow_entry("flow.a")];
1957        let components = vec![minimal_component_manifest("component.a")];
1958
1959        let err = build_bootstrap(&config, &flows, &components).unwrap_err();
1960        assert!(
1961            err.to_string()
1962                .contains("bootstrap.install_flow references unknown flow"),
1963            "unexpected error: {err}"
1964        );
1965    }
1966
1967    #[test]
1968    fn component_manifest_without_dev_flows_defaults_to_empty() {
1969        let manifest: ComponentManifest = serde_json::from_value(json!({
1970            "id": "component.dev",
1971            "version": "1.0.0",
1972            "supports": ["messaging"],
1973            "world": "greentic:demo@1.0.0",
1974            "profiles": { "default": "default", "supported": ["default"] },
1975            "capabilities": { "wasi": {}, "host": {} },
1976            "operations": [],
1977            "resources": {}
1978        }))
1979        .expect("manifest without dev_flows");
1980
1981        assert!(manifest.dev_flows.is_empty());
1982
1983        let pack_manifest = pack_manifest_with_component(manifest.clone());
1984        let encoded = encode_pack_manifest(&pack_manifest).expect("encode manifest");
1985        let decoded: PackManifest =
1986            greentic_types::decode_pack_manifest(&encoded).expect("decode manifest");
1987        let stored = decoded
1988            .components
1989            .iter()
1990            .find(|item| item.id == manifest.id)
1991            .expect("component present");
1992        assert!(stored.dev_flows.is_empty());
1993    }
1994
1995    #[test]
1996    fn dev_flows_round_trip_in_manifest_and_gtpack() {
1997        let component = manifest_with_dev_flow();
1998        let pack_manifest = pack_manifest_with_component(component.clone());
1999        let manifest_bytes = encode_pack_manifest(&pack_manifest).expect("encode manifest");
2000
2001        let decoded: PackManifest =
2002            greentic_types::decode_pack_manifest(&manifest_bytes).expect("decode manifest");
2003        let decoded_component = decoded
2004            .components
2005            .iter()
2006            .find(|item| item.id == component.id)
2007            .expect("component present");
2008        assert_eq!(decoded_component.dev_flows, component.dev_flows);
2009
2010        let temp = tempdir().expect("temp dir");
2011        let wasm_path = temp.path().join("component.wasm");
2012        write_stub_wasm(&wasm_path).expect("write stub wasm");
2013
2014        let build = BuildProducts {
2015            manifest: pack_manifest,
2016            components: vec![ComponentBinary {
2017                id: component.id.to_string(),
2018                source: wasm_path,
2019                manifest_bytes: serde_cbor::to_vec(&component).expect("component cbor"),
2020                manifest_path: format!("components/{}.manifest.cbor", component.id),
2021                manifest_hash_sha256: {
2022                    let mut sha = Sha256::new();
2023                    sha.update(serde_cbor::to_vec(&component).expect("component cbor"));
2024                    format!("sha256:{:x}", sha.finalize())
2025                },
2026            }],
2027            lock_components: Vec::new(),
2028            component_manifest_files: Vec::new(),
2029            flow_files: Vec::new(),
2030            assets: Vec::new(),
2031            extra_files: Vec::new(),
2032        };
2033
2034        let out = temp.path().join("demo.gtpack");
2035        package_gtpack(&out, &manifest_bytes, &build, BundleMode::Cache).expect("package gtpack");
2036
2037        let mut archive = ZipArchive::new(fs::File::open(&out).expect("open gtpack"))
2038            .expect("read gtpack archive");
2039        let mut manifest_entry = archive.by_name("manifest.cbor").expect("manifest.cbor");
2040        let mut stored = Vec::new();
2041        manifest_entry
2042            .read_to_end(&mut stored)
2043            .expect("read manifest");
2044        let decoded: PackManifest =
2045            greentic_types::decode_pack_manifest(&stored).expect("decode packaged manifest");
2046
2047        let stored_component = decoded
2048            .components
2049            .iter()
2050            .find(|item| item.id == component.id)
2051            .expect("component preserved");
2052        assert_eq!(stored_component.dev_flows, component.dev_flows);
2053    }
2054
2055    #[test]
2056    fn component_sources_extension_respects_bundle() {
2057        let lock_tag = PackLockV1::new(vec![LockedComponent {
2058            name: "demo.tagged".into(),
2059            r#ref: "oci://ghcr.io/demo/component:1.0.0".into(),
2060            digest: "sha256:deadbeef".into(),
2061            component_id: None,
2062            bundled: true,
2063            bundled_path: Some("blobs/sha256/deadbeef.wasm".into()),
2064            wasm_sha256: Some("deadbeef".repeat(8)),
2065            resolved_digest: Some("sha256:deadbeef".into()),
2066        }]);
2067
2068        let ext_none = merge_component_sources_extension(None, &lock_tag, BundleMode::None, None)
2069            .expect("ext");
2070        let value = match ext_none
2071            .unwrap()
2072            .get(EXT_COMPONENT_SOURCES_V1)
2073            .and_then(|e| e.inline.as_ref())
2074        {
2075            Some(ExtensionInline::Other(v)) => v.clone(),
2076            _ => panic!("missing inline"),
2077        };
2078        let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2079        assert!(matches!(
2080            decoded.components[0].artifact,
2081            ArtifactLocationV1::Inline { .. }
2082        ));
2083
2084        let lock_digest = PackLockV1::new(vec![LockedComponent {
2085            name: "demo.component".into(),
2086            r#ref: "oci://ghcr.io/demo/component@sha256:deadbeef".into(),
2087            digest: "sha256:deadbeef".into(),
2088            component_id: None,
2089            bundled: false,
2090            bundled_path: None,
2091            wasm_sha256: None,
2092            resolved_digest: None,
2093        }]);
2094
2095        let ext_none =
2096            merge_component_sources_extension(None, &lock_digest, BundleMode::None, None)
2097                .expect("ext");
2098        let value = match ext_none
2099            .unwrap()
2100            .get(EXT_COMPONENT_SOURCES_V1)
2101            .and_then(|e| e.inline.as_ref())
2102        {
2103            Some(ExtensionInline::Other(v)) => v.clone(),
2104            _ => panic!("missing inline"),
2105        };
2106        let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2107        assert!(matches!(
2108            decoded.components[0].artifact,
2109            ArtifactLocationV1::Remote
2110        ));
2111
2112        let lock_digest_bundled = PackLockV1::new(vec![LockedComponent {
2113            name: "demo.component".into(),
2114            r#ref: "oci://ghcr.io/demo/component@sha256:deadbeef".into(),
2115            digest: "sha256:deadbeef".into(),
2116            component_id: None,
2117            bundled: true,
2118            bundled_path: Some("components/demo.component.wasm".into()),
2119            wasm_sha256: Some("deadbeef".repeat(8)),
2120            resolved_digest: None,
2121        }]);
2122
2123        let ext_cache =
2124            merge_component_sources_extension(None, &lock_digest_bundled, BundleMode::Cache, None)
2125                .expect("ext");
2126        let value = match ext_cache
2127            .unwrap()
2128            .get(EXT_COMPONENT_SOURCES_V1)
2129            .and_then(|e| e.inline.as_ref())
2130        {
2131            Some(ExtensionInline::Other(v)) => v.clone(),
2132            _ => panic!("missing inline"),
2133        };
2134        let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2135        assert!(matches!(
2136            decoded.components[0].artifact,
2137            ArtifactLocationV1::Inline { .. }
2138        ));
2139    }
2140
2141    #[test]
2142    fn component_sources_extension_skips_file_refs() {
2143        let lock = PackLockV1::new(vec![LockedComponent {
2144            name: "local.component".into(),
2145            r#ref: "file:///tmp/component.wasm".into(),
2146            digest: "sha256:deadbeef".into(),
2147            component_id: None,
2148            bundled: false,
2149            bundled_path: None,
2150            wasm_sha256: None,
2151            resolved_digest: None,
2152        }]);
2153
2154        let ext_none =
2155            merge_component_sources_extension(None, &lock, BundleMode::Cache, None).expect("ext");
2156        assert!(ext_none.is_none(), "file refs should be omitted");
2157
2158        let lock = PackLockV1::new(vec![
2159            LockedComponent {
2160                name: "local.component".into(),
2161                r#ref: "file:///tmp/component.wasm".into(),
2162                digest: "sha256:deadbeef".into(),
2163                component_id: None,
2164                bundled: false,
2165                bundled_path: None,
2166                wasm_sha256: None,
2167                resolved_digest: None,
2168            },
2169            LockedComponent {
2170                name: "remote.component".into(),
2171                r#ref: "oci://ghcr.io/demo/component:2.0.0".into(),
2172                digest: "sha256:cafebabe".into(),
2173                component_id: None,
2174                bundled: false,
2175                bundled_path: None,
2176                wasm_sha256: None,
2177                resolved_digest: None,
2178            },
2179        ]);
2180
2181        let ext_some =
2182            merge_component_sources_extension(None, &lock, BundleMode::None, None).expect("ext");
2183        let value = match ext_some
2184            .unwrap()
2185            .get(EXT_COMPONENT_SOURCES_V1)
2186            .and_then(|e| e.inline.as_ref())
2187        {
2188            Some(ExtensionInline::Other(v)) => v.clone(),
2189            _ => panic!("missing inline"),
2190        };
2191        let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2192        assert_eq!(decoded.components.len(), 1);
2193        assert!(matches!(
2194            decoded.components[0].source,
2195            ComponentSourceRef::Oci(_)
2196        ));
2197    }
2198
2199    #[test]
2200    fn build_embeds_lock_components_from_cache() {
2201        let rt = tokio::runtime::Runtime::new().expect("runtime");
2202        rt.block_on(async {
2203            let temp = tempdir().expect("temp dir");
2204            let pack_dir = temp.path().join("pack");
2205            fs::create_dir_all(pack_dir.join("flows")).expect("flows dir");
2206            fs::create_dir_all(pack_dir.join("components")).expect("components dir");
2207
2208            let wasm_path = pack_dir.join("components/dummy.wasm");
2209            fs::write(&wasm_path, [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])
2210                .expect("write wasm");
2211
2212            let flow_path = pack_dir.join("flows/main.ygtc");
2213            fs::write(
2214                &flow_path,
2215                r#"id: main
2216type: messaging
2217start: call
2218nodes:
2219  call:
2220    handle_message:
2221      text: "hi"
2222    routing: out
2223"#,
2224            )
2225            .expect("write flow");
2226
2227            let cache_dir = temp.path().join("cache");
2228            let cached_bytes = b"cached-component";
2229            let digest = format!("sha256:{:x}", Sha256::digest(cached_bytes));
2230            let cache_path = cache_dir
2231                .join(digest.trim_start_matches("sha256:"))
2232                .join("component.wasm");
2233            fs::create_dir_all(cache_path.parent().expect("cache parent")).expect("cache dir");
2234            fs::write(&cache_path, cached_bytes).expect("write cached");
2235
2236            let summary = serde_json::json!({
2237                "schema_version": 1,
2238                "flow": "main.ygtc",
2239                "nodes": {
2240                    "call": {
2241                        "component_id": "dummy.component",
2242                        "source": {
2243                            "kind": "oci",
2244                            "ref": format!("oci://ghcr.io/demo/component@{digest}")
2245                        },
2246                        "digest": digest
2247                    }
2248                }
2249            });
2250            fs::write(
2251                flow_path.with_extension("ygtc.resolve.summary.json"),
2252                serde_json::to_vec_pretty(&summary).expect("summary json"),
2253            )
2254            .expect("write summary");
2255
2256            let pack_yaml = r#"pack_id: demo.lock-bundle
2257version: 0.1.0
2258kind: application
2259publisher: Test
2260components:
2261  - id: dummy.component
2262    version: "0.1.0"
2263    world: "greentic:component/component@0.5.0"
2264    supports: ["messaging"]
2265    profiles:
2266      default: "stateless"
2267      supported: ["stateless"]
2268    capabilities:
2269      wasi: {}
2270      host: {}
2271    operations:
2272      - name: "handle_message"
2273        input_schema: {}
2274        output_schema: {}
2275    wasm: "components/dummy.wasm"
2276flows:
2277  - id: main
2278    file: flows/main.ygtc
2279    tags: [default]
2280    entrypoints: [main]
2281"#;
2282            fs::write(pack_dir.join("pack.yaml"), pack_yaml).expect("pack.yaml");
2283
2284            let runtime = crate::runtime::resolve_runtime(
2285                Some(pack_dir.as_path()),
2286                Some(cache_dir.as_path()),
2287                true,
2288                None,
2289            )
2290            .expect("runtime");
2291
2292            let opts = BuildOptions {
2293                pack_dir: pack_dir.clone(),
2294                component_out: None,
2295                manifest_out: pack_dir.join("dist/manifest.cbor"),
2296                sbom_out: None,
2297                gtpack_out: Some(pack_dir.join("dist/pack.gtpack")),
2298                lock_path: pack_dir.join("pack.lock.json"),
2299                bundle: BundleMode::Cache,
2300                dry_run: false,
2301                secrets_req: None,
2302                default_secret_scope: None,
2303                allow_oci_tags: false,
2304                require_component_manifests: false,
2305                no_extra_dirs: false,
2306                runtime,
2307                skip_update: false,
2308            };
2309
2310            run(&opts).await.expect("build");
2311
2312            let gtpack_path = opts.gtpack_out.expect("gtpack path");
2313            let mut archive = ZipArchive::new(File::open(&gtpack_path).expect("open gtpack"))
2314                .expect("read gtpack");
2315            assert!(
2316                archive.by_name("components/main___call.wasm").is_ok(),
2317                "missing lock component artifact in gtpack"
2318            );
2319        });
2320    }
2321
2322    #[test]
2323    #[ignore = "requires network access to fetch OCI component"]
2324    fn build_fetches_and_embeds_lock_components_online() {
2325        if std::env::var("GREENTIC_PACK_ONLINE").is_err() {
2326            return;
2327        }
2328        let rt = tokio::runtime::Runtime::new().expect("runtime");
2329        rt.block_on(async {
2330            let temp = tempdir().expect("temp dir");
2331            let pack_dir = temp.path().join("pack");
2332            fs::create_dir_all(pack_dir.join("flows")).expect("flows dir");
2333            fs::create_dir_all(pack_dir.join("components")).expect("components dir");
2334
2335            let wasm_path = pack_dir.join("components/dummy.wasm");
2336            fs::write(&wasm_path, [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])
2337                .expect("write wasm");
2338
2339            let flow_path = pack_dir.join("flows/main.ygtc");
2340            fs::write(
2341                &flow_path,
2342                r#"id: main
2343type: messaging
2344start: call
2345nodes:
2346  call:
2347    handle_message:
2348      text: "hi"
2349    routing: out
2350"#,
2351            )
2352            .expect("write flow");
2353
2354            let digest =
2355                "sha256:0904bee6ecd737506265e3f38f3e4fe6b185c20fd1b0e7c06ce03cdeedc00340";
2356            let summary = serde_json::json!({
2357                "schema_version": 1,
2358                "flow": "main.ygtc",
2359                "nodes": {
2360                    "call": {
2361                        "component_id": "dummy.component",
2362                        "source": {
2363                            "kind": "oci",
2364                            "ref": format!("oci://ghcr.io/greentic-ai/components/templates@{digest}")
2365                        },
2366                        "digest": digest
2367                    }
2368                }
2369            });
2370            fs::write(
2371                flow_path.with_extension("ygtc.resolve.summary.json"),
2372                serde_json::to_vec_pretty(&summary).expect("summary json"),
2373            )
2374            .expect("write summary");
2375
2376            let pack_yaml = r#"pack_id: demo.lock-online
2377version: 0.1.0
2378kind: application
2379publisher: Test
2380components:
2381  - id: dummy.component
2382    version: "0.1.0"
2383    world: "greentic:component/component@0.5.0"
2384    supports: ["messaging"]
2385    profiles:
2386      default: "stateless"
2387      supported: ["stateless"]
2388    capabilities:
2389      wasi: {}
2390      host: {}
2391    operations:
2392      - name: "handle_message"
2393        input_schema: {}
2394        output_schema: {}
2395    wasm: "components/dummy.wasm"
2396flows:
2397  - id: main
2398    file: flows/main.ygtc
2399    tags: [default]
2400    entrypoints: [main]
2401"#;
2402            fs::write(pack_dir.join("pack.yaml"), pack_yaml).expect("pack.yaml");
2403
2404            let cache_dir = temp.path().join("cache");
2405            let runtime = crate::runtime::resolve_runtime(
2406                Some(pack_dir.as_path()),
2407                Some(cache_dir.as_path()),
2408                false,
2409                None,
2410            )
2411            .expect("runtime");
2412
2413            let opts = BuildOptions {
2414                pack_dir: pack_dir.clone(),
2415                component_out: None,
2416                manifest_out: pack_dir.join("dist/manifest.cbor"),
2417                sbom_out: None,
2418                gtpack_out: Some(pack_dir.join("dist/pack.gtpack")),
2419                lock_path: pack_dir.join("pack.lock.json"),
2420                bundle: BundleMode::Cache,
2421                dry_run: false,
2422                secrets_req: None,
2423                default_secret_scope: None,
2424                allow_oci_tags: false,
2425                require_component_manifests: false,
2426                no_extra_dirs: false,
2427                runtime,
2428                skip_update: false,
2429            };
2430
2431            run(&opts).await.expect("build");
2432
2433            let gtpack_path = opts.gtpack_out.expect("gtpack path");
2434            let mut archive =
2435                ZipArchive::new(File::open(&gtpack_path).expect("open gtpack"))
2436                    .expect("read gtpack");
2437            assert!(
2438                archive.by_name("components/main___call.wasm").is_ok(),
2439                "missing lock component artifact in gtpack"
2440            );
2441        });
2442    }
2443
2444    #[test]
2445    fn aggregate_secret_requirements_dedupes_and_sorts() {
2446        let component: ComponentConfig = serde_json::from_value(json!({
2447            "id": "component.a",
2448            "version": "1.0.0",
2449            "world": "greentic:demo@1.0.0",
2450            "supports": [],
2451            "profiles": { "default": "default", "supported": ["default"] },
2452            "capabilities": {
2453                "wasi": {},
2454                "host": {
2455                    "secrets": {
2456                        "required": [
2457                    {
2458                        "key": "db/password",
2459                        "required": true,
2460                        "scope": { "env": "dev", "tenant": "t1" },
2461                        "format": "text",
2462                        "description": "primary"
2463                    }
2464                ]
2465            }
2466        }
2467            },
2468            "wasm": "component.wasm",
2469            "operations": [],
2470            "resources": {}
2471        }))
2472        .expect("component config");
2473
2474        let dupe: ComponentConfig = serde_json::from_value(json!({
2475            "id": "component.b",
2476            "version": "1.0.0",
2477            "world": "greentic:demo@1.0.0",
2478            "supports": [],
2479            "profiles": { "default": "default", "supported": ["default"] },
2480            "capabilities": {
2481                "wasi": {},
2482                "host": {
2483                    "secrets": {
2484                        "required": [
2485                            {
2486                        "key": "db/password",
2487                        "required": true,
2488                        "scope": { "env": "dev", "tenant": "t1" },
2489                        "format": "text",
2490                        "description": "secondary",
2491                        "examples": ["example"]
2492                    }
2493                ]
2494            }
2495                }
2496            },
2497            "wasm": "component.wasm",
2498            "operations": [],
2499            "resources": {}
2500        }))
2501        .expect("component config");
2502
2503        let reqs = aggregate_secret_requirements(&[component, dupe], None, None)
2504            .expect("aggregate secrets");
2505        assert_eq!(reqs.len(), 1);
2506        let req = &reqs[0];
2507        assert_eq!(req.description.as_deref(), Some("primary"));
2508        assert!(req.examples.contains(&"example".to_string()));
2509    }
2510
2511    fn pack_config_with_bootstrap(bootstrap: BootstrapConfig) -> PackConfig {
2512        PackConfig {
2513            pack_id: "demo.pack".to_string(),
2514            version: "1.0.0".to_string(),
2515            kind: "application".to_string(),
2516            publisher: "demo".to_string(),
2517            bootstrap: Some(bootstrap),
2518            components: Vec::new(),
2519            dependencies: Vec::new(),
2520            flows: Vec::new(),
2521            assets: Vec::new(),
2522            extensions: None,
2523        }
2524    }
2525
2526    fn flow_entry(id: &str) -> PackFlowEntry {
2527        let flow: Flow = serde_json::from_value(json!({
2528            "schema_version": "flow/v1",
2529            "id": id,
2530            "kind": "messaging"
2531        }))
2532        .expect("flow json");
2533
2534        PackFlowEntry {
2535            id: FlowId::new(id).expect("flow id"),
2536            kind: FlowKind::Messaging,
2537            flow,
2538            tags: Vec::new(),
2539            entrypoints: Vec::new(),
2540        }
2541    }
2542
2543    fn minimal_component_manifest(id: &str) -> ComponentManifest {
2544        serde_json::from_value(json!({
2545            "id": id,
2546            "version": "1.0.0",
2547            "supports": [],
2548            "world": "greentic:demo@1.0.0",
2549            "profiles": { "default": "default", "supported": ["default"] },
2550            "capabilities": { "wasi": {}, "host": {} },
2551            "operations": [],
2552            "resources": {}
2553        }))
2554        .expect("component manifest")
2555    }
2556
2557    fn manifest_with_dev_flow() -> ComponentManifest {
2558        serde_json::from_str(include_str!(
2559            "../tests/fixtures/component_manifest_with_dev_flows.json"
2560        ))
2561        .expect("fixture manifest")
2562    }
2563
2564    fn pack_manifest_with_component(component: ComponentManifest) -> PackManifest {
2565        let flow = serde_json::from_value(json!({
2566            "schema_version": "flow/v1",
2567            "id": "flow.dev",
2568            "kind": "messaging"
2569        }))
2570        .expect("flow json");
2571
2572        PackManifest {
2573            schema_version: "pack-v1".to_string(),
2574            pack_id: PackId::new("demo.pack").expect("pack id"),
2575            version: Version::parse("1.0.0").expect("version"),
2576            kind: PackKind::Application,
2577            publisher: "demo".to_string(),
2578            components: vec![component],
2579            flows: vec![PackFlowEntry {
2580                id: FlowId::new("flow.dev").expect("flow id"),
2581                kind: FlowKind::Messaging,
2582                flow,
2583                tags: Vec::new(),
2584                entrypoints: Vec::new(),
2585            }],
2586            dependencies: Vec::new(),
2587            capabilities: Vec::new(),
2588            secret_requirements: Vec::new(),
2589            signatures: PackSignatures::default(),
2590            bootstrap: None,
2591            extensions: None,
2592        }
2593    }
2594}