greentic-runner-host 0.4.73

Host runtime shim for Greentic runner: config, pack loading, activity handling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
use std::path::{Path, PathBuf};
use std::str::FromStr;

use anyhow::{Context, Result, anyhow};
use greentic_flow::flow_bundle::load_and_validate_bundle_with_flow;
use greentic_runner_host::config::{
    FlowRetryConfig, HostConfig, OperatorPolicy, RateLimits, SecretsPolicy, StateStorePolicy,
    WebhookPolicy,
};
use greentic_runner_host::pack::{ComponentResolution, PackRuntime};
use greentic_runner_host::runner::engine::{FlowContext, FlowEngine, FlowStatus};
use greentic_runner_host::runner::flow_adapter::{FlowIR, NodeIR, RouteIR};
use greentic_runner_host::trace::TraceConfig;
use greentic_runner_host::validate::ValidationConfig;
use greentic_types::{
    ComponentCapabilities, ComponentManifest, ComponentProfiles, ExtensionInline, ExtensionRef,
    Flow, FlowComponentRef, FlowId, FlowKind, FlowMetadata, InputMapping, Node, NodeId,
    OutputMapping, PackFlowEntry, PackKind, PackManifest, ResourceHints, Routing, TelemetryHints,
    encode_pack_manifest,
};
use once_cell::sync::Lazy;
use semver::Version;
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashMap};
use std::fs::File;
use std::io::{Read, Write};
use std::sync::Arc;
use tempfile::TempDir;
use zip::ZipArchive;
use zip::write::FileOptions;

fn workspace_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(|p| p.parent())
        .map(PathBuf::from)
        .expect("workspace root")
}

fn build_components() -> Result<Vec<(String, PathBuf)>> {
    let workspace = workspace_root().join("tests/fixtures/runner-components");
    let mut results = Vec::new();
    let crates = vec![
        ("qa.process", "qa_process"),
        ("templating.handlebars", "templating_handlebars"),
        ("state.store", "state_store_component"),
    ];
    let offline = std::env::var("CARGO_NET_OFFLINE").ok();
    for (name, krate) in &crates {
        let manifest = workspace.join(krate).join("Cargo.toml");
        let mut cmd = std::process::Command::new("cargo");
        if let Some(val) = &offline {
            cmd.env("CARGO_NET_OFFLINE", val);
        }
        let mut args: Vec<String> = vec![
            "build".into(),
            "--manifest-path".into(),
            manifest.to_str().unwrap().into(),
            "--target".into(),
            "wasm32-wasip2".into(),
            "--release".into(),
        ];
        if matches!(offline.as_deref(), Some("true")) {
            args.insert(1, "--offline".into());
        }

        let status = cmd
            .current_dir(&workspace)
            .args(args)
            .status()
            .with_context(|| format!("failed to build {krate} component"))?;
        if !status.success() {
            anyhow::bail!("component build failed for {krate}");
        }
        let artifact = workspace.join(format!("target/wasm32-wasip2/release/{}.wasm", krate));
        results.push((name.to_string(), artifact));
    }
    Ok(results)
}

fn demo_flow_ir() -> FlowIR {
    let mut nodes = indexmap::IndexMap::new();
    nodes.insert(
        "qa".into(),
        NodeIR {
            component: "component.exec".into(),
            payload_expr: serde_json::json!({
                "component": "qa.process",
                "operation": "process",
                "input": { "text": "hello" }
            }),
            routes: vec![RouteIR {
                to: Some("emit".into()),
                out: false,
            }],
        },
    );
    nodes.insert(
        "emit".into(),
        NodeIR {
            component: "emit.response".into(),
            payload_expr: serde_json::json!({
                "text": "Echo: {{node.qa.text}}"
            }),
            routes: vec![RouteIR {
                to: None,
                out: true,
            }],
        },
    );
    FlowIR {
        id: "demo.flow".into(),
        flow_type: "messaging".into(),
        start: Some("qa".into()),
        parameters: serde_json::Value::Object(Default::default()),
        nodes,
    }
}

const RUNTIME_FLOW_EXTENSION_ID: &str = "greentic.pack.runtime_flow";

fn host_config(bindings_path: &Path) -> HostConfig {
    HostConfig {
        tenant: "demo".into(),
        bindings_path: bindings_path.to_path_buf(),
        flow_type_bindings: HashMap::new(),
        rate_limits: RateLimits::default(),
        retry: FlowRetryConfig::default(),
        http_enabled: false,
        secrets_policy: SecretsPolicy::allow_all(),
        state_store_policy: StateStorePolicy::default(),
        webhook_policy: WebhookPolicy::default(),
        timers: Vec::new(),
        oauth: None,
        mocks: None,
        pack_bindings: Vec::new(),
        env_passthrough: Vec::new(),
        trace: TraceConfig::from_env(),
        validation: ValidationConfig::from_env(),
        operator_policy: OperatorPolicy::allow_all(),
    }
}

fn legacy_component_exec_flow(flow_id: &str, message: &str) -> Result<Flow> {
    let node_id = NodeId::from_str("exec")?;
    let mut nodes = HashMap::new();
    nodes.insert(
        node_id.clone(),
        Node {
            id: node_id.clone(),
            component: FlowComponentRef {
                id: "component.exec".parse()?,
                pack_alias: None,
                operation: None,
            },
            input: InputMapping {
                mapping: serde_json::json!({
                    "component": "qa.process",
                    "operation": "process",
                    "input": { "message": message }
                }),
            },
            output: OutputMapping {
                mapping: Value::Null,
            },
            routing: Routing::End,
            telemetry: TelemetryHints::default(),
        },
    );
    Ok(Flow {
        schema_version: "1.0".into(),
        id: FlowId::from_str(flow_id)?,
        kind: FlowKind::Messaging,
        entrypoints: BTreeMap::from([("default".to_string(), Value::String(node_id.to_string()))]),
        nodes: nodes.into_iter().collect(),
        metadata: Default::default(),
    })
}

fn component_artifact_path(temp_dir: &Path) -> Result<PathBuf> {
    let local =
        workspace_root().join("tests/fixtures/packs/runner-components/components/qa_process.wasm");
    if local.exists() {
        return Ok(local);
    }
    let archive_path =
        workspace_root().join("tests/fixtures/packs/runner-components/runner-components.gtpack");
    let mut archive = ZipArchive::new(File::open(&archive_path).context("open fixture gtpack")?)?;
    let mut wasm = archive
        .by_name("components/qa.process@0.1.0/component.wasm")
        .context("qa.process component missing from fixture pack")?;
    let out = temp_dir.join("qa_process.wasm");
    let mut buf = Vec::new();
    wasm.read_to_end(&mut buf)?;
    std::fs::write(&out, &buf)?;
    Ok(out)
}

fn build_pack(flow_yaml: &str, pack_path: &Path) -> Result<()> {
    let component_path = component_artifact_path(
        pack_path
            .parent()
            .expect("pack path should have parent for temp dir"),
    )?;
    let (_bundle, flow) = load_and_validate_bundle_with_flow(flow_yaml, None)?;
    let manifest = PackManifest {
        schema_version: "1.0".into(),
        pack_id: "component.exec.test".parse()?,
        name: None,
        version: Version::parse("0.0.0")?,
        kind: PackKind::Application,
        publisher: "test".into(),
        components: vec![ComponentManifest {
            id: "qa.process".parse()?,
            version: Version::parse("0.1.0")?,
            supports: vec![FlowKind::Messaging],
            world: "greentic:component@0.4.0".into(),
            profiles: ComponentProfiles::default(),
            capabilities: ComponentCapabilities::default(),
            configurators: None,
            operations: Vec::new(),
            config_schema: None,
            resources: ResourceHints::default(),
            dev_flows: BTreeMap::new(),
        }],
        flows: vec![PackFlowEntry {
            id: flow.id.clone(),
            kind: flow.kind,
            flow: flow.clone(),
            tags: Vec::new(),
            entrypoints: vec!["default".into()],
        }],
        dependencies: Vec::new(),
        capabilities: Vec::new(),
        signatures: Default::default(),
        secret_requirements: Vec::new(),
        bootstrap: None,
        extensions: None,
    };

    let mut zip = zip::ZipWriter::new(File::create(pack_path).context("create pack archive")?);
    let options: FileOptions<'_, ()> =
        FileOptions::default().compression_method(zip::CompressionMethod::Stored);
    let manifest_bytes = encode_pack_manifest(&manifest)?;
    zip.start_file("manifest.cbor", options)?;
    zip.write_all(&manifest_bytes)?;

    zip.start_file("components/qa.process.wasm", options)?;
    let mut comp_file = File::open(&component_path)?;
    std::io::copy(&mut comp_file, &mut zip)?;
    zip.finish().context("finalise pack archive")?;
    Ok(())
}

fn build_component_exec_flow_with_input(flow_id: &str, input: Value) -> Result<Flow> {
    let node_id = NodeId::from_str("run").context("build node id")?;
    let mut nodes = HashMap::new();
    nodes.insert(
        node_id.clone(),
        Node {
            id: node_id.clone(),
            component: FlowComponentRef {
                id: "qa.process".parse()?,
                pack_alias: None,
                operation: Some("process".into()),
            },
            input: InputMapping { mapping: input },
            output: OutputMapping {
                mapping: Value::Null,
            },
            routing: Routing::End,
            telemetry: TelemetryHints::default(),
        },
    );
    Ok(Flow {
        schema_version: "1.0".into(),
        id: FlowId::from_str(flow_id)?,
        kind: FlowKind::Messaging,
        entrypoints: BTreeMap::from([("default".into(), Value::String(node_id.to_string()))]),
        nodes: nodes.into_iter().collect(),
        metadata: FlowMetadata::default(),
    })
}

fn build_pack_with_flow_id(pack_id: &str, flow: Flow, pack_path: &Path) -> Result<()> {
    let component_path = component_artifact_path(
        pack_path
            .parent()
            .expect("pack path should have parent for temp dir"),
    )?;
    let manifest = PackManifest {
        schema_version: "1.0".into(),
        pack_id: pack_id.parse()?,
        name: None,
        version: Version::parse("0.0.0")?,
        kind: PackKind::Application,
        publisher: "test".into(),
        components: vec![ComponentManifest {
            id: "qa.process".parse()?,
            version: Version::parse("0.1.0")?,
            supports: vec![FlowKind::Messaging],
            world: "greentic:component@0.4.0".into(),
            profiles: ComponentProfiles::default(),
            capabilities: ComponentCapabilities::default(),
            configurators: None,
            operations: Vec::new(),
            config_schema: None,
            resources: ResourceHints::default(),
            dev_flows: BTreeMap::new(),
        }],
        flows: vec![PackFlowEntry {
            id: flow.id.clone(),
            kind: flow.kind,
            flow,
            tags: Vec::new(),
            entrypoints: vec!["default".into()],
        }],
        dependencies: Vec::new(),
        capabilities: Vec::new(),
        signatures: Default::default(),
        secret_requirements: Vec::new(),
        bootstrap: None,
        extensions: None,
    };

    let mut zip = zip::ZipWriter::new(File::create(pack_path).context("create pack archive")?);
    let options: FileOptions<'_, ()> =
        FileOptions::default().compression_method(zip::CompressionMethod::Stored);
    let manifest_bytes = encode_pack_manifest(&manifest)?;
    zip.start_file("manifest.cbor", options)?;
    zip.write_all(&manifest_bytes)?;

    zip.start_file("components/qa.process.wasm", options)?;
    let mut comp_file = File::open(&component_path)?;
    std::io::copy(&mut comp_file, &mut zip)?;
    zip.finish().context("finalise pack archive")?;
    Ok(())
}

fn build_pack_with_runtime_extension(
    manifest_flows: Vec<Flow>,
    runtime_extension: Value,
    pack_path: &Path,
) -> Result<()> {
    let component_path = component_artifact_path(
        pack_path
            .parent()
            .expect("pack path should have parent for temp dir"),
    )?;

    let flow_entries = manifest_flows
        .iter()
        .map(|flow| PackFlowEntry {
            id: flow.id.clone(),
            kind: flow.kind,
            flow: flow.clone(),
            tags: Vec::new(),
            entrypoints: vec!["default".into()],
        })
        .collect::<Vec<_>>();

    let mut extensions = BTreeMap::new();
    extensions.insert(
        RUNTIME_FLOW_EXTENSION_ID.to_string(),
        ExtensionRef {
            kind: RUNTIME_FLOW_EXTENSION_ID.to_string(),
            version: "2.0.0".into(),
            digest: None,
            location: None,
            inline: Some(ExtensionInline::Other(runtime_extension)),
        },
    );

    let manifest = PackManifest {
        schema_version: "1.0".into(),
        pack_id: "component.exec.runtime".parse()?,
        name: None,
        version: Version::parse("0.0.0")?,
        kind: PackKind::Application,
        publisher: "test".into(),
        components: vec![ComponentManifest {
            id: "qa.process".parse()?,
            version: Version::parse("0.1.0")?,
            supports: vec![FlowKind::Messaging],
            world: "greentic:component@0.4.0".into(),
            profiles: ComponentProfiles::default(),
            capabilities: ComponentCapabilities::default(),
            configurators: None,
            operations: Vec::new(),
            config_schema: None,
            resources: ResourceHints::default(),
            dev_flows: BTreeMap::new(),
        }],
        flows: flow_entries,
        dependencies: Vec::new(),
        capabilities: Vec::new(),
        signatures: Default::default(),
        secret_requirements: Vec::new(),
        bootstrap: None,
        extensions: Some(extensions),
    };

    let mut zip = zip::ZipWriter::new(File::create(pack_path).context("create pack archive")?);
    let options: FileOptions<'_, ()> =
        FileOptions::default().compression_method(zip::CompressionMethod::Stored);
    let manifest_bytes = encode_pack_manifest(&manifest)?;
    zip.start_file("manifest.cbor", options)?;
    zip.write_all(&manifest_bytes)?;

    zip.start_file("components/qa.process.wasm", options)?;
    let mut comp_file = File::open(&component_path)?;
    std::io::copy(&mut comp_file, &mut zip)?;
    zip.finish().context("finalise pack archive")?;
    Ok(())
}

static RUNTIME: Lazy<&'static tokio::runtime::Runtime> = Lazy::new(|| {
    Box::leak(Box::new(
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("test runtime"),
    ))
});

#[test]
fn component_exec_invokes_pack_component() -> Result<()> {
    let temp = TempDir::new()?;
    let bindings_path = temp.path().join("bindings.yaml");
    std::fs::write(&bindings_path, b"tenant: demo")?;

    let components = build_components()?;
    let flow = demo_flow_ir();
    let mut flows = HashMap::new();
    flows.insert(flow.id.clone(), flow);

    let config = Arc::new(host_config(&bindings_path));
    let runtime = Arc::new(
        PackRuntime::for_component_test(
            components,
            flows.clone(),
            "test-pack",
            Arc::clone(&config),
        )
        .context("pack init")?,
    );
    // Ensure the runtime constructed successfully with components and flows in place.
    let _ = (runtime, config, flows);
    Ok(())
}

#[test]
fn exec_node_uses_inner_component_artifact() -> Result<()> {
    // Regression: component.exec is a meta-component and must call the referenced pack artifact.
    let rt = *RUNTIME;
    let temp = TempDir::new()?;
    let pack_path = temp.path().join("component-exec.gtpack");
    let bindings_path = temp.path().join("bindings.yaml");
    std::fs::write(&bindings_path, b"tenant: demo")?;

    // Build a pack whose flow uses component.exec to call qa.process.
    let flow_yaml = r#"
id: exec.flow
type: messaging
start: exec
nodes:
  exec:
    component.exec:
      component: qa.process
      operation: process
      input:
        payload:
          text: "hello"
        metadata:
          __return_envelope: true
    routing:
      - out: true
"#;
    build_pack(flow_yaml, &pack_path)?;

    let config = Arc::new(host_config(&bindings_path));
    let pack = Arc::new(rt.block_on(PackRuntime::load(
        &pack_path,
        Arc::clone(&config),
        None,
        None,
        None,
        None,
        Arc::new(greentic_runner_host::wasi::RunnerWasiPolicy::new()),
        greentic_runner_host::secrets::default_manager()?,
        None,
        false,
        ComponentResolution::default(),
    ))?);
    let engine = rt.block_on(FlowEngine::new(
        vec![Arc::clone(&pack)],
        Arc::clone(&config),
    ))?;

    let retry_config = config.retry.clone().into();
    let tenant = config.tenant.clone();
    let flow_id = "exec.flow".to_string();
    let ctx = FlowContext {
        tenant: tenant.as_str(),
        pack_id: pack.metadata().pack_id.as_str(),
        flow_id: flow_id.as_str(),
        node_id: None,
        tool: None,
        action: None,
        session_id: None,
        provider_id: None,
        retry_config,
        attempt: 1,
        observer: None,
        mocks: None,
    };

    let execution = rt
        .block_on(engine.execute(ctx, Value::Null))
        .context("component.exec flow run")?;
    match execution.status {
        FlowStatus::Completed => {}
        FlowStatus::Waiting(wait) => {
            anyhow::bail!("flow paused unexpectedly: {:?}", wait.reason);
        }
    }

    let payload = envelope_payload(&execution.output)?;
    assert_eq!(payload, json!({ "text": "hello" }));
    Ok(())
}

#[test]
fn component_exec_always_serializes_invocation_envelope() -> Result<()> {
    let rt = *RUNTIME;
    let config_temp = TempDir::new()?;
    let bindings_path = config_temp.path().join("bindings.yaml");
    std::fs::write(
        &bindings_path,
        b"tenant: demo\n\
flow_type_bindings: {}\n\
rate_limits: {}\n\
retry: {}\n\
timers: []\n",
    )?;
    let config = Arc::new(host_config(&bindings_path));
    let retry_config = config.retry.clone().into();
    let pack_dir = TempDir::new()?;

    struct InvocationCase {
        suffix: &'static str,
        input: Value,
        expected_payload: Value,
        expected_metadata: Value,
    }

    let cases = vec![
        InvocationCase {
            suffix: "envelope",
            input: json!({
                "envelope": {
                    "ctx": {
                        "tenant": "spoof",
                        "env": "spoof-env",
                        "flow_id": "spoof.flow",
                        "node_id": "spoof.node",
                        "provider_id": "spoof.provider"
                    },
                    "flow_id": "spoof.flow",
                    "node_id": "spoof.node",
                    "op": "process",
                    "payload": { "message": "from envelope" },
                    "metadata": { "source": "envelope", "__return_envelope": true }
                }
            }),
            expected_payload: json!({ "message": "from envelope" }),
            expected_metadata: json!({ "source": "envelope", "__return_envelope": true }),
        },
        InvocationCase {
            suffix: "partial",
            input: json!({
                "op": "process",
                "payload": { "message": "partial" },
                "metadata": { "source": "partial", "__return_envelope": true }
            }),
            expected_payload: json!({ "message": "partial" }),
            expected_metadata: json!({ "source": "partial", "__return_envelope": true }),
        },
    ];

    for case in cases {
        let flow_id = format!("ctx.flow.{}", case.suffix);
        let flow = build_component_exec_flow_with_input(&flow_id, case.input.clone())?;
        let pack_path = pack_dir
            .path()
            .join(format!("component.exec.ctx.{}.gtpack", case.suffix));
        build_pack_with_flow_id(
            &format!("component.exec.ctx.{}", case.suffix),
            flow.clone(),
            &pack_path,
        )?;

        let pack = Arc::new(rt.block_on(PackRuntime::load(
            &pack_path,
            Arc::clone(&config),
            None,
            Some(&pack_path),
            None,
            None,
            Arc::new(greentic_runner_host::wasi::RunnerWasiPolicy::new()),
            greentic_runner_host::secrets::default_manager()?,
            None,
            false,
            ComponentResolution::default(),
        ))?);
        let engine = rt.block_on(FlowEngine::new(
            vec![Arc::clone(&pack)],
            Arc::clone(&config),
        ))?;

        let ctx = FlowContext {
            tenant: config.tenant.as_str(),
            pack_id: pack.metadata().pack_id.as_str(),
            flow_id: flow.id.as_str(),
            node_id: None,
            tool: None,
            action: None,
            session_id: None,
            provider_id: None,
            retry_config,
            attempt: 1,
            observer: None,
            mocks: None,
        };

        let execution = rt
            .block_on(engine.execute(ctx, Value::Null))
            .context("execute component.exec flow")?;
        match execution.status {
            FlowStatus::Completed => {}
            other => panic!("flow {} paused unexpectedly: {:?}", flow.id, other),
        }

        let envelope_value = execution.output;
        let envelope = envelope_value
            .as_object()
            .context("expected component output object")?;
        assert_eq!(
            envelope
                .get("flow_id")
                .and_then(Value::as_str)
                .context("envelope flow_id missing")?,
            flow.id.as_str()
        );
        assert_eq!(
            envelope
                .get("node_id")
                .and_then(Value::as_str)
                .context("envelope node_id missing")?,
            "run"
        );
        assert_eq!(
            envelope
                .get("op")
                .and_then(Value::as_str)
                .context("envelope op missing")?,
            "process"
        );

        let ctx_value = envelope
            .get("ctx")
            .and_then(Value::as_object)
            .context("ctx missing")?;
        assert_eq!(
            ctx_value
                .get("tenant")
                .and_then(Value::as_str)
                .context("ctx tenant missing")?,
            config.tenant.as_str()
        );
        assert_eq!(
            ctx_value
                .get("flow_id")
                .and_then(Value::as_str)
                .context("ctx flow_id missing")?,
            flow.id.as_str()
        );
        assert_eq!(
            ctx_value
                .get("node_id")
                .and_then(Value::as_str)
                .context("ctx node_id missing")?,
            "run"
        );

        let payload = decode_binary_value(envelope.get("payload").context("payload missing")?)?;
        assert_eq!(payload, case.expected_payload);

        let metadata = decode_binary_value(envelope.get("metadata").context("metadata missing")?)?;
        assert_eq!(metadata, case.expected_metadata);
    }

    Ok(())
}

#[test]
fn emit_log_is_builtin_not_pack_component() -> Result<()> {
    // Regression: emit.log should be treated as a built-in, not looked up as a pack artifact.
    let rt = *RUNTIME;
    let temp = TempDir::new()?;
    let pack_path = temp.path().join("emit-log.gtpack");
    let bindings_path = temp.path().join("bindings.yaml");
    std::fs::write(&bindings_path, b"tenant: demo")?;

    let flow_yaml = r#"
id: emit.flow
type: messaging
start: exec
nodes:
  exec:
    component.exec:
      component: qa.process
      operation: process
      input:
        text: "hello"
    routing:
      - to: log
  log:
    emit.log:
      message: "logged"
    routing:
      - out: true
"#;
    build_pack(flow_yaml, &pack_path)?;

    let config = Arc::new(host_config(&bindings_path));
    let pack = Arc::new(rt.block_on(PackRuntime::load(
        &pack_path,
        Arc::clone(&config),
        None,
        None,
        None,
        None,
        Arc::new(greentic_runner_host::wasi::RunnerWasiPolicy::new()),
        greentic_runner_host::secrets::default_manager()?,
        None,
        false,
        ComponentResolution::default(),
    ))?);
    let engine = rt.block_on(FlowEngine::new(
        vec![Arc::clone(&pack)],
        Arc::clone(&config),
    ))?;

    let retry_config = config.retry.clone().into();
    let tenant = config.tenant.clone();
    let flow_id = "emit.flow".to_string();
    let ctx = FlowContext {
        tenant: tenant.as_str(),
        pack_id: pack.metadata().pack_id.as_str(),
        flow_id: flow_id.as_str(),
        node_id: None,
        tool: None,
        action: None,
        session_id: None,
        provider_id: None,
        retry_config,
        attempt: 1,
        observer: None,
        mocks: None,
    };

    let execution = rt
        .block_on(engine.execute(ctx, Value::Null))
        .context("emit.log flow run")?;
    match execution.status {
        FlowStatus::Completed => {}
        FlowStatus::Waiting(wait) => {
            anyhow::bail!("emit flow paused unexpectedly: {:?}", wait.reason);
        }
    }

    let output_str = execution.output.to_string();
    assert!(
        output_str.contains("logged"),
        "expected emit.log to produce output; got {output_str}"
    );
    Ok(())
}

#[test]
fn runtime_extension_flow_overrides_manifest_flow() -> Result<()> {
    let rt = *RUNTIME;
    let temp = TempDir::new()?;
    let pack_path = temp.path().join("runtime-extension.gtpack");
    let bindings_path = temp.path().join("bindings.yaml");
    std::fs::write(&bindings_path, b"tenant: demo")?;

    let legacy_flow = legacy_component_exec_flow("exec.flow", "legacy")?;
    let runtime_flow = serde_json::json!({
        "id": "exec.flow",
        "flow_type": "messaging",
        "start": "exec",
        "nodes": {
            "exec": {
                "component_id": "qa.process",
                "operation_name": "process",
                "operation_payload": {
                    "payload": { "message": "resolved" },
                    "metadata": { "__return_envelope": true }
                },
                "routing": "end"
            }
        }
    });
    let runtime_extension = serde_json::json!({ "flows": [runtime_flow] });
    build_pack_with_runtime_extension(vec![legacy_flow], runtime_extension, &pack_path)?;

    let config = Arc::new(host_config(&bindings_path));
    let pack = Arc::new(rt.block_on(PackRuntime::load(
        &pack_path,
        Arc::clone(&config),
        None,
        None,
        None,
        None,
        Arc::new(greentic_runner_host::wasi::RunnerWasiPolicy::new()),
        greentic_runner_host::secrets::default_manager()?,
        None,
        false,
        ComponentResolution::default(),
    ))?);
    let engine = rt.block_on(FlowEngine::new(
        vec![Arc::clone(&pack)],
        Arc::clone(&config),
    ))?;

    let retry_config = config.retry.clone().into();
    let ctx = FlowContext {
        tenant: config.tenant.as_str(),
        pack_id: pack.metadata().pack_id.as_str(),
        flow_id: "exec.flow",
        node_id: None,
        tool: None,
        action: None,
        session_id: None,
        provider_id: None,
        retry_config,
        attempt: 1,
        observer: None,
        mocks: None,
    };

    let execution = rt
        .block_on(engine.execute(ctx, Value::Null))
        .context("runtime extension flow run")?;
    match execution.status {
        FlowStatus::Completed => {}
        FlowStatus::Waiting(wait) => {
            anyhow::bail!("flow paused unexpectedly: {:?}", wait.reason);
        }
    }

    let payload = envelope_payload(&execution.output)?;
    assert_eq!(payload["message"], serde_json::json!("resolved"));
    Ok(())
}

fn decode_binary_value(value: &Value) -> Result<Value> {
    let bytes = to_bytes(value)?;
    serde_json::from_slice(&bytes).context("decode binary payload")
}

fn to_bytes(value: &Value) -> Result<Vec<u8>> {
    let array = value.as_array().context("binary payload is not an array")?;
    let mut bytes = Vec::with_capacity(array.len());
    for entry in array {
        let num = entry
            .as_u64()
            .context("binary payload entry is not an integer")?;
        if num > u64::from(u8::MAX) {
            return Err(anyhow!("binary payload entry {} exceeds byte range", num));
        }
        bytes.push(num as u8);
    }
    Ok(bytes)
}

fn envelope_payload(value: &Value) -> Result<Value> {
    let envelope = value
        .as_object()
        .context("expected component output envelope")?;
    let payload_value = envelope
        .get("payload")
        .context("envelope payload missing")?;
    decode_binary_value(payload_value)
}