traverse-runtime 0.9.0

Core execution engine for the Traverse capability runtime.
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
//! Wasmtime-backed WASM executor.
//!
//! Executes `wasm32-wasi` capability binaries inside a sandboxed Wasmtime engine.
//! Input is fed via WASI stdin; output is captured from WASI stdout.
//! No ambient WASI authority is granted — all capabilities are deny-by-default.

use chrono::Utc;
use serde::Deserialize;
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;
use std::fs;
use std::sync::{LazyLock, Mutex};
use uuid::Uuid;
use wasmtime::{
    Caller, Config, Engine, Extern, Linker, Module, Store, StoreLimits, StoreLimitsBuilder,
};
use wasmtime_wasi::WasiCtxBuilder;
use wasmtime_wasi::p1::WasiP1Ctx;
use wasmtime_wasi::p2::pipe::{MemoryInputPipe, MemoryOutputPipe};

use super::{ArtifactType, CapabilityExecutor, ExecutorCapability, ExecutorError, ExecutorOutput};
use crate::events::types::{LifecycleStatus, TraverseEvent};
use traverse_contracts::{EventReference, ServiceType};

/// Traverse Host ABI v1 is independently versioned from the runtime crate.
pub const SUPPORTED_HOST_ABI_VERSION: &str = "1.0.0";

const HOST_ABI_V1_WHITELIST: &str = include_str!("host_abi_v1.json");
const DEFAULT_FUEL_BUDGET: u64 = 5_000_000;
const DEFAULT_MEMORY_LIMIT_BYTES: usize = 8 * 1024 * 1024;
const DEFAULT_TABLE_ELEMENT_LIMIT: usize = 1_024;
const DEFAULT_INSTANCE_LIMIT: usize = 1;
const DEFAULT_TABLE_LIMIT: usize = 8;
const DEFAULT_LINEAR_MEMORY_LIMIT: usize = 1;
const DEFAULT_MODULE_CACHE_MAX_ENTRIES: usize = 64;

/// Maximum bytes accepted for one `traverse_host::emit_event` payload
/// (spec 098-capability-event-host-abi FR-008). Enforced before the guest
/// memory read, and before deserialization.
const MAX_EVENT_EMIT_PAYLOAD_BYTES: usize = 64 * 1024;

/// `traverse_host::emit_event` accepted the event; it will be published to
/// `EventBroker` once execution completes (spec 098 acceptance scenario 1).
const EMIT_EVENT_OK: i32 = 0;
/// The guest-supplied pointer/length was out of the guest's linear memory
/// bounds, or the payload exceeded [`MAX_EVENT_EMIT_PAYLOAD_BYTES`], or the
/// bytes were not a valid JSON object with `event_id`/`version` string
/// fields (spec 098 FR-008, acceptance scenario 5).
const EMIT_EVENT_ERR_INVALID_PAYLOAD: i32 = -1;
/// The event type/version is not declared in the calling capability's
/// contract `emits` list (spec 098 FR-002, acceptance scenario 2).
const EMIT_EVENT_ERR_UNDECLARED_EVENT: i32 = -2;
/// The calling capability's `service_type` is not `Subscribable` (spec 098
/// FR-003, acceptance scenario 3).
const EMIT_EVENT_ERR_NOT_SUBSCRIBABLE: i32 = -3;

static HOST_ABI_V1_WHITELIST_CACHE: LazyLock<Result<HostAbiWhitelist, String>> =
    LazyLock::new(|| {
        serde_json::from_str::<HostAbiWhitelist>(HOST_ABI_V1_WHITELIST).map_err(|e| e.to_string())
    });

/// A host import observed in a WASM module.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostAbiImport {
    /// Imported module namespace.
    pub module: String,
    /// Imported function or item name.
    pub name: String,
}

/// Successful load-time ABI validation evidence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostAbiValidation {
    /// ABI version used for whitelist validation.
    pub abi_version: String,
    /// All imports observed in deterministic module/name order.
    pub imports: Vec<HostAbiImport>,
}

#[derive(Debug, Clone, Deserialize)]
struct HostAbiWhitelist {
    abi_version: String,
    imports: Vec<HostAbiWhitelistImport>,
}

#[derive(Debug, Clone, Deserialize)]
struct HostAbiWhitelistImport {
    module: String,
    name: String,
}

/// Return the Traverse Host ABI versions supported by this runtime.
#[must_use]
pub fn supported_host_abi_versions() -> &'static [&'static str] {
    &[SUPPORTED_HOST_ABI_VERSION]
}

/// Validate a WASM binary against the declared Traverse Host ABI import whitelist.
///
/// # Errors
///
/// Returns [`ExecutorError`] when the binary is malformed, the ABI version is unsupported,
/// or a module imports a host function outside the whitelist.
pub fn verify_wasm_host_abi_bytes(
    wasm_bytes: &[u8],
    abi_version: &str,
) -> Result<HostAbiValidation, ExecutorError> {
    let engine = Engine::default();
    let module = Module::from_binary(&engine, wasm_bytes).map_err(|e| {
        ExecutorError::MalformedWasmArtifact {
            error_code: "malformed_wasm_artifact".to_string(),
            detail: format!("module compile: {e}"),
        }
    })?;
    validate_module_imports(&module, abi_version)
}

/// Executes `.wasm32-wasi` capability binaries via Wasmtime.
///
/// Every invocation creates a fresh Wasmtime `Store` — no state leaks between calls.
#[derive(Debug)]
pub struct WasmExecutor {
    engine: Engine,
    limits: WasmExecutionLimits,
    module_cache: Mutex<CompiledModuleCache>,
}

impl WasmExecutor {
    /// Create a new [`WasmExecutor`] with a default Wasmtime engine.
    ///
    /// # Errors
    ///
    /// Returns [`ExecutorError::RuntimeSetupFailed`] if Wasmtime cannot initialise.
    pub fn new() -> Result<Self, ExecutorError> {
        Self::with_limits(WasmExecutionLimits::default())
    }

    /// Create a [`WasmExecutor`] with explicit per-invocation resource limits.
    ///
    /// # Errors
    ///
    /// Returns [`ExecutorError::RuntimeSetupFailed`] if Wasmtime cannot initialise.
    pub fn with_limits(limits: WasmExecutionLimits) -> Result<Self, ExecutorError> {
        Self::with_limits_and_cache_config(limits, WasmModuleCacheConfig::default())
    }

    /// Create a [`WasmExecutor`] with explicit resource limits and module cache bounds.
    ///
    /// # Errors
    ///
    /// Returns [`ExecutorError::RuntimeSetupFailed`] if Wasmtime cannot initialise.
    pub fn with_limits_and_cache_config(
        limits: WasmExecutionLimits,
        cache_config: WasmModuleCacheConfig,
    ) -> Result<Self, ExecutorError> {
        let mut config = Config::new();
        config.consume_fuel(true);
        let engine = Engine::new(&config)
            .map_err(|e| ExecutorError::RuntimeSetupFailed(format!("engine config: {e}")))?;
        Ok(Self {
            engine,
            limits,
            module_cache: Mutex::new(CompiledModuleCache::new(cache_config.max_entries)),
        })
    }

    /// Return current compiled-module cache counters.
    #[must_use]
    pub fn module_cache_stats(&self) -> WasmModuleCacheStats {
        let cache = self
            .module_cache
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        cache.stats()
    }
}

/// Per-invocation resource limits for [`WasmExecutor`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WasmExecutionLimits {
    /// Fuel units available for guest code before it traps as a timeout.
    pub fuel_budget: u64,
    /// Maximum bytes for each guest linear memory.
    pub memory_bytes: usize,
    /// Maximum elements for each guest table.
    pub table_elements: usize,
    /// Maximum instances in the store.
    pub instances: usize,
    /// Maximum tables in the store.
    pub tables: usize,
    /// Maximum linear memories in the store.
    pub memories: usize,
}

impl Default for WasmExecutionLimits {
    fn default() -> Self {
        Self {
            fuel_budget: DEFAULT_FUEL_BUDGET,
            memory_bytes: DEFAULT_MEMORY_LIMIT_BYTES,
            table_elements: DEFAULT_TABLE_ELEMENT_LIMIT,
            instances: DEFAULT_INSTANCE_LIMIT,
            tables: DEFAULT_TABLE_LIMIT,
            memories: DEFAULT_LINEAR_MEMORY_LIMIT,
        }
    }
}

/// Bounded compiled-module cache configuration for [`WasmExecutor`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WasmModuleCacheConfig {
    /// Maximum number of compiled modules retained by checksum.
    pub max_entries: usize,
}

impl Default for WasmModuleCacheConfig {
    fn default() -> Self {
        Self {
            max_entries: DEFAULT_MODULE_CACHE_MAX_ENTRIES,
        }
    }
}

/// Snapshot of compiled-module cache counters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WasmModuleCacheStats {
    /// Current retained compiled modules.
    pub entries: usize,
    /// Number of executions served from cache.
    pub hits: u64,
    /// Number of executions that compiled a module before insertion.
    pub misses: u64,
    /// Number of deterministic oldest-entry evictions.
    pub evictions: u64,
}

#[derive(Debug, Clone)]
struct CachedModule {
    module: Module,
    validation: HostAbiValidation,
}

#[derive(Debug)]
struct CompiledModuleCache {
    max_entries: usize,
    entries: HashMap<String, CachedModule>,
    insertion_order: VecDeque<String>,
    hits: u64,
    misses: u64,
    evictions: u64,
}

impl CompiledModuleCache {
    fn new(max_entries: usize) -> Self {
        Self {
            max_entries: max_entries.max(1),
            entries: HashMap::new(),
            insertion_order: VecDeque::new(),
            hits: 0,
            misses: 0,
            evictions: 0,
        }
    }

    fn get(&mut self, checksum: &str, abi_version: &str) -> Option<CachedModule> {
        let cached = self.entries.get(checksum)?;
        if cached.validation.abi_version != abi_version {
            self.misses += 1;
            return None;
        }
        self.hits += 1;
        Some(cached.clone())
    }

    fn insert(&mut self, checksum: String, cached: CachedModule) {
        self.misses += 1;
        while self.entries.len() >= self.max_entries {
            if let Some(oldest) = self.insertion_order.pop_front()
                && self.entries.remove(&oldest).is_some()
            {
                self.evictions += 1;
            }
        }
        self.insertion_order.push_back(checksum.clone());
        self.entries.insert(checksum, cached);
    }

    fn stats(&self) -> WasmModuleCacheStats {
        WasmModuleCacheStats {
            entries: self.entries.len(),
            hits: self.hits,
            misses: self.misses,
            evictions: self.evictions,
        }
    }
}

struct WasmStoreState {
    wasi: WasiP1Ctx,
    limits: StoreLimits,
    /// Calling capability's id, `emits`, and `service_type` — used by the
    /// `traverse_host::emit_event` host function to validate emissions
    /// synchronously, at call time (spec 098-capability-event-host-abi
    /// FR-002/FR-003).
    capability_id: String,
    emits: Vec<EventReference>,
    service_type: ServiceType,
    /// Events accepted via `traverse_host::emit_event` during this call.
    emitted_events: Vec<TraverseEvent>,
}

impl CapabilityExecutor for WasmExecutor {
    fn execute(
        &self,
        capability: &ExecutorCapability,
        input: &Value,
    ) -> Result<ExecutorOutput, ExecutorError> {
        if capability.artifact_type != ArtifactType::Wasm {
            return Err(ExecutorError::UnsupportedArtifactType);
        }

        // --- Load binary ---
        let wasm_path = capability.wasm_binary_path.as_deref().ok_or_else(|| {
            ExecutorError::BinaryLoadFailed("no wasm_binary_path set".to_string())
        })?;

        let binary = fs::read(wasm_path).map_err(|e| {
            ExecutorError::BinaryLoadFailed(format!("cannot read {wasm_path}: {e}"))
        })?;

        // --- Checksum validation ---
        if let Some(expected) = capability.wasm_checksum.as_deref() {
            let actual = sha256_hex(&binary);
            if actual != expected {
                return Err(ExecutorError::ChecksumMismatch {
                    expected: expected.to_string(),
                    actual,
                });
            }
        }

        let abi_version = capability
            .host_abi_version
            .as_deref()
            .unwrap_or(SUPPORTED_HOST_ABI_VERSION);

        self.run_wasm(
            &binary,
            input,
            abi_version,
            &capability.capability_id,
            &capability.emits,
            capability.service_type.clone(),
        )
    }
}

impl WasmExecutor {
    /// Execute pre-loaded WASM bytes with the given input.
    ///
    /// Exposed separately so tests can pass raw bytes without needing a file on disk.
    /// The capability is treated as `Stateless` with no declared `emits` — it
    /// cannot call `traverse_host::emit_event`. Use
    /// [`run_bytes_with_capability`](Self::run_bytes_with_capability) to
    /// exercise the event-emit host function.
    ///
    /// # Errors
    ///
    /// Returns [`ExecutorError`] if input serialization fails, the WASM module cannot be
    /// compiled or linked, execution fails, or stdout is not valid JSON.
    pub fn run_bytes(&self, wasm_bytes: &[u8], input: &Value) -> Result<Value, ExecutorError> {
        self.run_bytes_with_host_abi(wasm_bytes, input, SUPPORTED_HOST_ABI_VERSION)
    }

    /// Execute pre-loaded WASM bytes with an explicit Traverse Host ABI version.
    ///
    /// # Errors
    ///
    /// Returns [`ExecutorError`] if ABI validation fails or execution cannot complete.
    pub fn run_bytes_with_host_abi(
        &self,
        wasm_bytes: &[u8],
        input: &Value,
        abi_version: &str,
    ) -> Result<Value, ExecutorError> {
        self.run_wasm(
            wasm_bytes,
            input,
            abi_version,
            "test-capability",
            &[],
            ServiceType::Stateless,
        )
        .map(|output| output.value)
    }

    /// Execute pre-loaded WASM bytes as a specific capability, exercising
    /// `traverse_host::emit_event` validation against `emits`/`service_type`
    /// exactly as [`CapabilityExecutor::execute`] does.
    ///
    /// # Errors
    ///
    /// Returns [`ExecutorError`] if ABI validation fails or execution cannot complete.
    pub fn run_bytes_with_capability(
        &self,
        wasm_bytes: &[u8],
        input: &Value,
        capability_id: &str,
        emits: &[EventReference],
        service_type: ServiceType,
    ) -> Result<ExecutorOutput, ExecutorError> {
        self.run_wasm(
            wasm_bytes,
            input,
            SUPPORTED_HOST_ABI_VERSION,
            capability_id,
            emits,
            service_type,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn run_wasm(
        &self,
        wasm_bytes: &[u8],
        input: &Value,
        abi_version: &str,
        capability_id: &str,
        emits: &[EventReference],
        service_type: ServiceType,
    ) -> Result<ExecutorOutput, ExecutorError> {
        let input_json = serde_json::to_string(input)
            .map_err(|e| ExecutorError::ExecutionFailed(format!("input serialization: {e}")))?;

        let cached_module = self.compiled_module(wasm_bytes, abi_version)?;

        // Clone pipe reference before passing to builder — needed to read output after execution
        let stdout_pipe = MemoryOutputPipe::new(65536);
        let stdout_ref = stdout_pipe.clone();

        // Build a WASI context: stdin = input JSON, stdout = captured buffer
        // No filesystem, no network, no env vars — deny-by-default
        let wasi_ctx: WasiP1Ctx = WasiCtxBuilder::new()
            .stdin(MemoryInputPipe::new(input_json.into_bytes()))
            .stdout(stdout_pipe)
            .build_p1();

        let mut linker: Linker<WasmStoreState> = Linker::new(&self.engine);
        wasmtime_wasi::p1::add_to_linker_sync(&mut linker, |s| &mut s.wasi)
            .map_err(|e| ExecutorError::RuntimeSetupFailed(e.to_string()))?;
        linker
            .func_wrap("traverse_host", "emit_event", handle_emit_event)
            .map_err(|e| ExecutorError::RuntimeSetupFailed(format!("func_wrap emit_event: {e}")))?;

        let mut store = Store::new(
            &self.engine,
            WasmStoreState {
                wasi: wasi_ctx,
                limits: self.store_limits(),
                capability_id: capability_id.to_string(),
                emits: emits.to_vec(),
                service_type,
                emitted_events: Vec::new(),
            },
        );
        store.limiter(|state| &mut state.limits);
        store
            .set_fuel(self.limits.fuel_budget)
            .map_err(|e| ExecutorError::RuntimeSetupFailed(format!("set fuel: {e}")))?;

        linker
            .module(&mut store, "", &cached_module.module)
            .map_err(|e| ExecutorError::RuntimeSetupFailed(format!("module link: {e}")))?;

        linker
            .get_default(&mut store, "")
            .map_err(|e| ExecutorError::RuntimeSetupFailed(format!("get_default: {e}")))?
            .typed::<(), ()>(&store)
            .map_err(|e| ExecutorError::RuntimeSetupFailed(format!("typed: {e}")))?
            .call(&mut store, ())
            .map_err(|error| classify_wasm_execution_error(&error))?;

        // Extract captured stdout — contents() reads the buffer without consuming it
        let raw_output = stdout_ref.contents();

        let value = serde_json::from_slice::<Value>(&raw_output).map_err(|e| {
            ExecutorError::OutputDeserializationFailed(format!(
                "stdout is not valid JSON: {e} — raw: {}",
                String::from_utf8_lossy(&raw_output)
            ))
        })?;

        Ok(ExecutorOutput {
            value,
            emitted_events: store.into_data().emitted_events,
        })
    }

    fn store_limits(&self) -> StoreLimits {
        StoreLimitsBuilder::new()
            .memory_size(self.limits.memory_bytes)
            .table_elements(self.limits.table_elements)
            .instances(self.limits.instances)
            .tables(self.limits.tables)
            .memories(self.limits.memories)
            .trap_on_grow_failure(true)
            .build()
    }

    fn compiled_module(
        &self,
        wasm_bytes: &[u8],
        abi_version: &str,
    ) -> Result<CachedModule, ExecutorError> {
        let checksum = sha256_hex(wasm_bytes);
        {
            let mut cache = self
                .module_cache
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if let Some(cached) = cache.get(&checksum, abi_version) {
                return Ok(cached);
            }
        }

        let module = Module::from_binary(&self.engine, wasm_bytes).map_err(|e| {
            ExecutorError::MalformedWasmArtifact {
                error_code: "malformed_wasm_artifact".to_string(),
                detail: format!("module compile: {e}"),
            }
        })?;
        let validation = validate_module_imports(&module, abi_version)?;
        let cached = CachedModule { module, validation };

        let mut cache = self
            .module_cache
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        cache.insert(checksum, cached.clone());
        Ok(cached)
    }
}

/// Host implementation of `traverse_host::emit_event` (spec
/// 098-capability-event-host-abi FR-001). The guest passes a pointer/length
/// into its own linear memory holding a JSON payload shaped
/// `{"event_id": "...", "version": "...", "payload": {...}}`; this function
/// validates it synchronously, at call time, and never panics or traps on a
/// malformed or out-of-bounds guest pointer (FR-008) — every failure path
/// returns a negative status code to the guest instead.
fn handle_emit_event(mut caller: Caller<'_, WasmStoreState>, ptr: i32, len: i32) -> i32 {
    // FR-003: checked before any guest memory is touched — rejected
    // regardless of payload.
    if caller.data().service_type != ServiceType::Subscribable {
        return EMIT_EVENT_ERR_NOT_SUBSCRIBABLE;
    }

    // FR-008: bounds/size checked before any read or deserialization.
    if ptr < 0 || len < 0 {
        return EMIT_EVENT_ERR_INVALID_PAYLOAD;
    }
    #[allow(clippy::cast_sign_loss)]
    let (ptr, len) = (ptr as usize, len as usize);
    if len > MAX_EVENT_EMIT_PAYLOAD_BYTES {
        return EMIT_EVENT_ERR_INVALID_PAYLOAD;
    }

    let Some(Extern::Memory(memory)) = caller.get_export("memory") else {
        return EMIT_EVENT_ERR_INVALID_PAYLOAD;
    };

    let mut buffer = vec![0u8; len];
    // `Memory::read` bounds-checks `ptr + len` against actual guest memory
    // size and returns `Err` rather than panicking or reading out of bounds.
    if memory.read(&caller, ptr, &mut buffer).is_err() {
        return EMIT_EVENT_ERR_INVALID_PAYLOAD;
    }

    let Ok(payload) = serde_json::from_slice::<Value>(&buffer) else {
        return EMIT_EVENT_ERR_INVALID_PAYLOAD;
    };
    let Some(event_type) = payload
        .get("event_id")
        .and_then(Value::as_str)
        .map(str::to_string)
    else {
        return EMIT_EVENT_ERR_INVALID_PAYLOAD;
    };
    let Some(version) = payload
        .get("version")
        .and_then(Value::as_str)
        .map(str::to_string)
    else {
        return EMIT_EVENT_ERR_INVALID_PAYLOAD;
    };
    let data = payload
        .get("payload")
        .cloned()
        .unwrap_or_else(|| Value::Object(serde_json::Map::new()));

    // FR-002: declared-emission check, synchronous, at call time.
    let declared = caller
        .data()
        .emits
        .iter()
        .any(|decl| decl.event_id == event_type && decl.version == version);
    if !declared {
        return EMIT_EVENT_ERR_UNDECLARED_EVENT;
    }

    let capability_id = caller.data().capability_id.clone();
    let event = TraverseEvent {
        id: Uuid::new_v4().to_string(),
        source: format!("traverse-runtime/{capability_id}"),
        event_type: event_type.clone(),
        datacontenttype: "application/json".to_string(),
        time: Utc::now().to_rfc3339(),
        data,
        owner: capability_id.clone(),
        version: version.clone(),
        lifecycle_status: LifecycleStatus::Active,
        deduplication_id: Some(format!("{capability_id}:{event_type}:{version}")),
        ordering_scope: Some(capability_id),
        correlation_id: None,
        causation_id: None,
        subject_id: None,
        actor_id: None,
    };
    caller.data_mut().emitted_events.push(event);
    EMIT_EVENT_OK
}

fn classify_wasm_execution_error(error: &wasmtime::Error) -> ExecutorError {
    let display = error.to_string();
    let debug = format!("{error:?}");
    if display.contains("all fuel consumed by WebAssembly")
        || debug.contains("all fuel consumed by WebAssembly")
    {
        return ExecutorError::Timeout(debug);
    }
    if display.contains("forcing trap when growing") || debug.contains("forcing trap when growing")
    {
        return ExecutorError::ResourceExhausted(debug);
    }
    ExecutorError::ExecutionFailed(display)
}

fn sha256_hex(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    hasher
        .finalize()
        .iter()
        .fold(String::new(), |mut acc, byte| {
            let _ = write!(acc, "{byte:02x}");
            acc
        })
}

fn validate_module_imports(
    module: &Module,
    abi_version: &str,
) -> Result<HostAbiValidation, ExecutorError> {
    let whitelist = host_abi_whitelist(abi_version)?;
    let mut imports = module
        .imports()
        .map(|import| HostAbiImport {
            module: import.module().to_string(),
            name: import.name().to_string(),
        })
        .collect::<Vec<_>>();
    imports.sort_by(|a, b| a.module.cmp(&b.module).then_with(|| a.name.cmp(&b.name)));

    for import in &imports {
        if !whitelist
            .imports
            .iter()
            .any(|allowed| allowed.module == import.module && allowed.name == import.name)
        {
            return Err(ExecutorError::UnauthorizedHostImport {
                error_code: "unauthorized_host_import".to_string(),
                abi_version: abi_version.to_string(),
                module: import.module.clone(),
                name: import.name.clone(),
            });
        }
    }

    Ok(HostAbiValidation {
        abi_version: whitelist.abi_version,
        imports,
    })
}

fn host_abi_whitelist(abi_version: &str) -> Result<HostAbiWhitelist, ExecutorError> {
    if abi_version != SUPPORTED_HOST_ABI_VERSION {
        return Err(ExecutorError::UnsupportedAbiVersion {
            error_code: "unsupported_abi_version".to_string(),
            requested: abi_version.to_string(),
            supported: supported_host_abi_versions().join(", "),
        });
    }

    HOST_ABI_V1_WHITELIST_CACHE
        .as_ref()
        .cloned()
        .map_err(|e| ExecutorError::RuntimeSetupFailed(format!("invalid ABI whitelist: {e}")))
}