iron-core 0.1.38

Core AgentIron loop, session state, and tool registry
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
//! WASM execution host for plugins (Extism-backed).
//!
//! `WasmHost` manages loaded plugin instances in memory and provides the
//! bridge between the lifecycle manager's artifact cache and the actual WASM
//! runtime powered by [Extism](https://extism.org).
//!
//! ## v1 Plugin Entrypoint Contract
//!
//! Iron-core plugins are WASM modules that export one or more functions. The
//! v1 contract defines:
//!
//! * **Manifest section**: A custom WASM section named `iron_manifest` containing
//!   a UTF-8 JSON payload (see `PluginManifest`).
//!
//! * **Tool entrypoints**: Each tool declared in the manifest has a corresponding
//!   exported function named `tool_{tool_name}`. For example, a tool named
//!   `greet` is invoked via the `tool_greet` export.
//!
//! * **Request envelope**: The host serializes arguments as JSON and passes them
//!   as a UTF-8 string via Extism's input buffer.
//!
//! * **Response envelope**: The plugin returns a UTF-8 JSON string via Extism's
//!   output buffer. The response must be a JSON object. On success the plugin
//!   returns `{"ok": <result_value>}`. On failure the plugin returns
//!   `{"error": "<message>"}`.
//!
//! * **Timeout**: The host sets a 30-second timeout on all plugin calls via the
//!   Extism manifest. Plugins that exceed this are interrupted.
//!
//! * **Error mapping**: Host-side errors (plugin not found, load failure, invalid
//!   input, malformed output, timeout) are mapped to structured `WasmError`
//!   variants.
//!
//! ## Thread safety
//!
//! `extism::Plugin::call()` requires `&mut self`, so the internal plugin map
//! is guarded by a `Mutex` rather than an `RwLock`.  The outer `WasmHost` is
//! `Clone` (cloning only bumps the `Arc` ref-count) and `Send + Sync`.

use crate::plugin::lifecycle::PluginLoader;
use crate::plugin::manifest::PluginManifest;
use crate::plugin::rich_output::normalize_plugin_tool_result;
use parking_lot::Mutex;
use serde_json::Value;
use std::collections::HashMap;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use tracing::{debug, info, warn};

/// Result type for WASM operations.
pub type WasmResult<T> = Result<T, WasmError>;

/// Future type for async WASM tool execution.
pub type WasmExecutionFuture = Pin<Box<dyn Future<Output = WasmResult<Value>> + Send>>;

/// Default WASM linear-memory ceiling per plugin: 128 MB.
pub const DEFAULT_PLUGIN_MAX_MEMORY_BYTES: u64 = 128 * 1024 * 1024;

/// WASM page size (64 KiB) — Extism's `with_memory_max` takes a page count.
const WASM_PAGE_SIZE: u64 = 64 * 1024;

/// Convert a byte budget to the page count Extism expects, rounding down and
/// clamping to `u32::MAX`. At least one page is always granted so the plugin
/// has a shadow stack.
fn bytes_to_pages(bytes: u64) -> u32 {
    let pages = bytes / WASM_PAGE_SIZE;
    pages.clamp(1, u32::MAX as u64) as u32
}

/// Bookkeeping for a single loaded plugin inside the WASM host.
struct LoadedPlugin {
    /// Path to the cached WASM artifact on disk.
    artifact_path: PathBuf,
    /// The Extism plugin instance.
    plugin: extism::Plugin,
    /// Manifest extracted during load (mirrors registry manifest).
    manifest: Option<PluginManifest>,
}

/// WASM execution host for running plugin code.
///
/// Thread-safe: internal state is guarded by a `Mutex` so that concurrent
/// tool execution (which requires `&mut` access to the Extism plugin) is
/// serialised correctly.  `WasmHost` is cheaply `Clone`-able — cloning only
/// bumps the `Arc` ref-count.
#[derive(Clone)]
pub struct WasmHost {
    inner: Arc<Mutex<WasmHostInner>>,
    max_memory_bytes: u64,
}

struct WasmHostInner {
    /// Plugins currently loaded into the host, keyed by plugin ID.
    loaded: HashMap<String, LoadedPlugin>,
}

impl WasmHost {
    /// Create a new WASM host with no loaded plugins and the default memory
    /// ceiling ([`DEFAULT_PLUGIN_MAX_MEMORY_BYTES`]).
    pub fn new() -> Self {
        Self::with_max_memory_bytes(DEFAULT_PLUGIN_MAX_MEMORY_BYTES)
    }

    /// Create a new WASM host with an explicit per-plugin memory ceiling.
    pub fn with_max_memory_bytes(max_memory_bytes: u64) -> Self {
        Self {
            inner: Arc::new(Mutex::new(WasmHostInner {
                loaded: HashMap::new(),
            })),
            max_memory_bytes,
        }
    }

    /// The per-plugin memory ceiling this host applies, in bytes.
    pub fn max_memory_bytes(&self) -> u64 {
        self.max_memory_bytes
    }

    /// Load a plugin into the WASM runtime.
    ///
    /// Reads the artifact from `artifact_path`, creates an Extism manifest
    /// with a 30-second timeout, the configured per-plugin memory ceiling,
    /// and WASI enabled, then instantiates the plugin.
    pub fn load_plugin(&self, plugin_id: &str, artifact_path: &Path) -> WasmResult<()> {
        self.load_plugin_with_limit(plugin_id, artifact_path, None)
    }

    /// Load a plugin, allowing the caller (typically the lifecycle layer) to
    /// pass the plugin's manifest-declared `max_memory_bytes`. The effective
    /// ceiling is the smaller of the declared value and the host ceiling.
    pub fn load_plugin_with_limit(
        &self,
        plugin_id: &str,
        artifact_path: &Path,
        plugin_declared_max_bytes: Option<u64>,
    ) -> WasmResult<()> {
        let wasm_bytes = std::fs::read(artifact_path).map_err(|e| {
            WasmError::LoadFailed(format!(
                "Failed to read artifact {}: {}",
                artifact_path.display(),
                e
            ))
        })?;

        let effective_bytes = plugin_declared_max_bytes
            .map(|declared| declared.min(self.max_memory_bytes))
            .unwrap_or(self.max_memory_bytes);
        let max_pages = bytes_to_pages(effective_bytes);

        let manifest = extism::Manifest::new([extism::Wasm::data(wasm_bytes)])
            .with_timeout(std::time::Duration::from_secs(30))
            .with_memory_max(max_pages);

        let plugin = extism::Plugin::new(manifest, [], true)
            .map_err(|e| WasmError::LoadFailed(format!("Extism plugin creation failed: {}", e)))?;

        let mut inner = self.inner.lock();
        inner.loaded.insert(
            plugin_id.to_string(),
            LoadedPlugin {
                artifact_path: artifact_path.to_path_buf(),
                plugin,
                manifest: None, // populated separately by lifecycle
            },
        );

        info!(
            plugin_id = %plugin_id,
            max_memory_bytes = effective_bytes,
            max_pages,
            "Plugin loaded into WASM host"
        );
        Ok(())
    }

    /// Unload a plugin from the WASM runtime.
    ///
    /// Removes the in-memory tracking.  Returns `Ok(())` even if the plugin
    /// was not loaded (idempotent).  Dropping the `LoadedPlugin` drops the
    /// underlying `extism::Plugin`.
    pub fn unload_plugin(&self, plugin_id: &str) -> WasmResult<()> {
        let mut inner = self.inner.lock();
        if inner.loaded.remove(plugin_id).is_some() {
            info!(plugin_id = %plugin_id, "Plugin unloaded from WASM host");
        } else {
            debug!(plugin_id = %plugin_id, "Unload requested but plugin was not loaded");
        }
        Ok(())
    }

    /// Execute a plugin tool (async version).
    ///
    /// Resolves the plugin, calls the Extism entrypoint `tool_{tool_name}`,
    /// and parses the response envelope `{"ok": ...}` / `{"error": ...}`.
    ///
    /// The actual Extism call is synchronous and requires `&mut self` on the
    /// plugin, so it is dispatched to a Tokio blocking thread.
    pub fn execute_tool(
        &self,
        plugin_id: &str,
        tool_name: &str,
        arguments: Value,
    ) -> WasmExecutionFuture {
        let plugin_id = plugin_id.to_string();
        let tool_name = tool_name.to_string();
        let inner = self.inner.clone();

        Box::pin(async move {
            // Execute on a blocking thread since Extism::call is sync
            let result = tokio::task::spawn_blocking(move || {
                let mut guard = inner.lock();
                let loaded = guard
                    .loaded
                    .get_mut(&plugin_id)
                    .ok_or_else(|| WasmError::NotFound(plugin_id.clone()))?;

                let entrypoint = format!("tool_{}", tool_name);

                // Check if the function exists
                if !loaded.plugin.function_exists(&entrypoint) {
                    return Err(WasmError::ExecutionFailed(format!(
                        "Plugin does not export function '{}'",
                        entrypoint
                    )));
                }

                // Serialize arguments
                let input = serde_json::to_string(&arguments).map_err(|e| {
                    WasmError::InvalidInput(format!("Failed to serialize arguments: {}", e))
                })?;

                // Call the plugin
                let output: &str = loaded.plugin.call(&entrypoint, &input).map_err(|e| {
                    let msg = e.to_string();
                    if msg.contains("timeout") || msg.contains("timed out") {
                        WasmError::Timeout
                    } else if msg.contains("trap") || msg.contains("panic") {
                        WasmError::PluginPanicked(msg)
                    } else {
                        WasmError::ExecutionFailed(msg)
                    }
                })?;

                // Parse the response envelope
                let response: Value = serde_json::from_str(output).map_err(|e| {
                    WasmError::ExecutionFailed(format!("Plugin returned invalid JSON: {}", e))
                })?;

                if let Some(error) = response.get("error") {
                    let msg = error.as_str().unwrap_or("Unknown plugin error");
                    return Err(WasmError::ExecutionFailed(msg.to_string()));
                }

                let result = response.get("ok").cloned().unwrap_or(Value::Null);
                normalize_plugin_tool_result(&plugin_id, &tool_name, result)
            })
            .await;

            match result {
                Ok(inner_result) => inner_result,
                Err(join_error) => Err(WasmError::ExecutionFailed(format!(
                    "Task join error: {}",
                    join_error
                ))),
            }
        })
    }

    /// Execute a plugin tool synchronously (for non-async contexts).
    pub fn execute_tool_sync(
        &self,
        plugin_id: &str,
        tool_name: &str,
        arguments: Value,
    ) -> WasmResult<Value> {
        let mut guard = self.inner.lock();
        let loaded = guard
            .loaded
            .get_mut(plugin_id)
            .ok_or_else(|| WasmError::NotFound(plugin_id.to_string()))?;

        let entrypoint = format!("tool_{}", tool_name);

        if !loaded.plugin.function_exists(&entrypoint) {
            return Err(WasmError::ExecutionFailed(format!(
                "Plugin does not export function '{}'",
                entrypoint
            )));
        }

        let input = serde_json::to_string(&arguments).map_err(|e| {
            WasmError::InvalidInput(format!("Failed to serialize arguments: {}", e))
        })?;

        let output: &str = loaded.plugin.call(&entrypoint, &input).map_err(|e| {
            let msg = e.to_string();
            if msg.contains("timeout") || msg.contains("timed out") {
                WasmError::Timeout
            } else if msg.contains("trap") || msg.contains("panic") {
                WasmError::PluginPanicked(msg)
            } else {
                WasmError::ExecutionFailed(msg)
            }
        })?;

        let response: Value = serde_json::from_str(output).map_err(|e| {
            WasmError::ExecutionFailed(format!("Plugin returned invalid JSON: {}", e))
        })?;

        if let Some(error) = response.get("error") {
            let msg = error.as_str().unwrap_or("Unknown plugin error");
            return Err(WasmError::ExecutionFailed(msg.to_string()));
        }

        let result = response.get("ok").cloned().unwrap_or(Value::Null);
        normalize_plugin_tool_result(plugin_id, tool_name, result)
    }

    /// Check if a plugin is loaded in the WASM host.
    pub fn is_plugin_loaded(&self, plugin_id: &str) -> bool {
        let inner = self.inner.lock();
        inner.loaded.contains_key(plugin_id)
    }

    /// Check if a plugin is loaded and considered healthy.
    ///
    /// A plugin is healthy if it is loaded and its artifact still exists on disk.
    pub fn is_plugin_healthy(&self, plugin_id: &str) -> bool {
        let inner = self.inner.lock();
        match inner.loaded.get(plugin_id) {
            Some(loaded) => loaded.artifact_path.exists(),
            None => false,
        }
    }

    /// Store the manifest for a loaded plugin.
    ///
    /// Called by the lifecycle manager after it extracts the manifest from the
    /// WASM binary.
    pub fn set_manifest(&self, plugin_id: &str, manifest: PluginManifest) {
        let mut inner = self.inner.lock();
        if let Some(loaded) = inner.loaded.get_mut(plugin_id) {
            loaded.manifest = Some(manifest);
        }
    }

    /// Get the manifest for a loaded plugin, if available.
    pub fn get_plugin_manifest(&self, plugin_id: &str) -> Option<PluginManifest> {
        let inner = self.inner.lock();
        inner.loaded.get(plugin_id).and_then(|l| l.manifest.clone())
    }

    /// List all currently loaded plugin IDs.
    pub fn loaded_plugins(&self) -> Vec<String> {
        let inner = self.inner.lock();
        inner.loaded.keys().cloned().collect()
    }
}

impl Default for WasmHost {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for WasmHost {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let inner = self.inner.lock();
        let ids: Vec<&String> = inner.loaded.keys().collect();
        f.debug_struct("WasmHost")
            .field("loaded_plugins", &ids)
            .finish()
    }
}

/// Implement `PluginLoader` so the lifecycle manager can delegate the
/// host-load step to `WasmHost` without coupling.
impl PluginLoader for WasmHost {
    fn load(&self, plugin_id: &str, artifact_path: &Path) -> Result<(), String> {
        self.load_plugin(plugin_id, artifact_path)
            .map_err(|e| e.to_string())
    }

    fn load_with_limit(
        &self,
        plugin_id: &str,
        artifact_path: &Path,
        plugin_declared_max_bytes: Option<u64>,
    ) -> Result<(), String> {
        self.load_plugin_with_limit(plugin_id, artifact_path, plugin_declared_max_bytes)
            .map_err(|e| e.to_string())
    }

    fn unload(&self, plugin_id: &str) {
        if let Err(e) = self.unload_plugin(plugin_id) {
            warn!(
                plugin_id = %plugin_id,
                error = %e,
                "Failed to unload plugin from WASM host during uninstall"
            );
        }
    }
}

/// Errors that can occur during WASM operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WasmError {
    /// Plugin not found in the WASM host.
    NotFound(String),
    /// Plugin failed to load.
    LoadFailed(String),
    /// Tool execution failed.
    ExecutionFailed(String),
    /// Invalid input arguments.
    InvalidInput(String),
    /// Plugin panicked during execution.
    PluginPanicked(String),
    /// Timeout during execution.
    Timeout,
}

impl std::fmt::Display for WasmError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(id) => write!(f, "Plugin not found: {}", id),
            Self::LoadFailed(msg) => write!(f, "Failed to load plugin: {}", msg),
            Self::ExecutionFailed(msg) => write!(f, "Tool execution failed: {}", msg),
            Self::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
            Self::PluginPanicked(msg) => write!(f, "Plugin panicked: {}", msg),
            Self::Timeout => write!(f, "Plugin execution timed out"),
        }
    }
}

impl std::error::Error for WasmError {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugin::manifest::{
        ExportedTool, PluginIdentity, PluginManifest, PluginPublisher, PresentationMetadata,
    };
    use crate::plugin::network::NetworkPolicy;

    fn sample_manifest() -> PluginManifest {
        PluginManifest {
            identity: PluginIdentity {
                id: "com.example.test".to_string(),
                name: "Test".to_string(),
                version: "1.0.0".to_string(),
            },
            publisher: PluginPublisher {
                name: "Test".to_string(),
                url: None,
                contact: None,
            },
            presentation: PresentationMetadata {
                description: "A test plugin".to_string(),
                long_description: None,
                icon: None,
                category: None,
                keywords: vec![],
            },
            network_policy: NetworkPolicy::Wildcard,
            auth: None,
            tools: vec![ExportedTool {
                name: "greet".to_string(),
                description: "Say hello".to_string(),
                input_schema: serde_json::json!({"type": "object"}),
                requires_approval: false,
                auth_requirements: None,
            }],
            max_memory_bytes: None,
            api_version: "1.0".to_string(),
        }
    }

    #[test]
    fn load_nonexistent_artifact_fails() {
        let host = WasmHost::new();
        let result = host.load_plugin("test", Path::new("/nonexistent/file.wasm"));
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), WasmError::LoadFailed(_)));
    }

    #[test]
    fn load_minimal_wasm_succeeds_but_no_functions() {
        // A bare WASM header is a valid but empty module. Extism accepts it,
        // but any attempt to call a tool function will fail because the module
        // exports nothing.
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("minimal.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::new();
        let result = host.load_plugin("test", &artifact);
        assert!(
            result.is_ok(),
            "Extism should accept a minimal valid WASM module, got {:?}",
            result
        );
        assert!(host.is_plugin_loaded("test"));
    }

    #[test]
    fn unload_nonexistent_plugin_is_ok() {
        let host = WasmHost::new();
        assert!(host.unload_plugin("no-such-plugin").is_ok());
    }

    #[tokio::test]
    async fn execute_tool_on_unloaded_plugin_returns_not_found() {
        let host = WasmHost::new();
        let result = host
            .execute_tool("no-such-plugin", "tool", serde_json::json!({}))
            .await;
        assert!(matches!(result.unwrap_err(), WasmError::NotFound(_)));
    }

    #[test]
    fn execute_tool_sync_on_unloaded_plugin_returns_not_found() {
        let host = WasmHost::new();
        let result = host.execute_tool_sync("no-such-plugin", "tool", serde_json::json!({}));
        assert!(matches!(result.unwrap_err(), WasmError::NotFound(_)));
    }

    #[test]
    fn is_plugin_loaded_initially_false() {
        let host = WasmHost::new();
        assert!(!host.is_plugin_loaded("any"));
    }

    #[test]
    fn is_plugin_healthy_initially_false() {
        let host = WasmHost::new();
        assert!(!host.is_plugin_healthy("any"));
    }

    #[test]
    fn get_plugin_manifest_initially_none() {
        let host = WasmHost::new();
        assert!(host.get_plugin_manifest("any").is_none());
    }

    #[test]
    fn loaded_plugins_initially_empty() {
        let host = WasmHost::new();
        assert!(host.loaded_plugins().is_empty());
    }

    #[test]
    fn plugin_loader_trait_load_accepts_minimal_wasm() {
        // Extism accepts a minimal WASM header as a valid (but empty) module.
        // The module loads successfully but exports no functions.
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("real.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::new();
        let result = host.load("test", &artifact);
        assert!(
            result.is_ok(),
            "Extism should accept a minimal valid WASM module"
        );
        assert!(host.is_plugin_loaded("test"));
    }

    #[tokio::test]
    async fn execute_tool_on_empty_plugin_returns_execution_failed() {
        // Load a minimal WASM that has no exported functions.
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("empty.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::new();
        host.load_plugin("empty-plugin", &artifact).unwrap();

        let result = host
            .execute_tool("empty-plugin", "greet", serde_json::json!({}))
            .await;
        assert!(
            matches!(result, Err(WasmError::ExecutionFailed(_))),
            "Expected ExecutionFailed for missing function, got {:?}",
            result
        );
    }

    #[test]
    fn plugin_loader_trait_unload_noop_for_unknown() {
        let host = WasmHost::new();
        // Unloading a plugin that was never loaded should be a no-op.
        host.unload("no-such-plugin");
        assert!(!host.is_plugin_loaded("no-such-plugin"));
    }

    #[test]
    fn debug_impl_works() {
        let host = WasmHost::new();
        let debug_str = format!("{:?}", host);
        assert!(debug_str.contains("WasmHost"));
    }

    #[test]
    fn clone_shares_state() {
        let host = WasmHost::new();
        let host2 = host.clone();
        // Both point to the same inner state
        assert!(host2.loaded_plugins().is_empty());
        assert!(host.loaded_plugins().is_empty());
    }

    #[test]
    fn set_manifest_on_nonexistent_plugin_is_noop() {
        let host = WasmHost::new();
        // Should not panic
        host.set_manifest("no-such-plugin", sample_manifest());
        assert!(host.get_plugin_manifest("no-such-plugin").is_none());
    }

    // ---- Phase 9.2: Additional host-level tests ----

    #[test]
    fn load_and_unload_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("rt.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::new();
        host.load_plugin("rt", &artifact).unwrap();
        assert!(host.is_plugin_loaded("rt"));
        assert!(host.loaded_plugins().contains(&"rt".to_string()));

        host.unload_plugin("rt").unwrap();
        assert!(!host.is_plugin_loaded("rt"));
        assert!(!host.loaded_plugins().contains(&"rt".to_string()));
    }

    #[test]
    fn load_same_plugin_id_replaces() {
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("replace.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::new();
        host.load_plugin("dup", &artifact).unwrap();
        // Loading again with the same ID should succeed (replace).
        host.load_plugin("dup", &artifact).unwrap();
        assert!(host.is_plugin_loaded("dup"));
    }

    #[test]
    fn health_check_delegates_to_artifact_existence() {
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("health.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::new();
        host.load_plugin("hp", &artifact).unwrap();
        assert!(host.is_plugin_healthy("hp"));

        // Delete the artifact — plugin is loaded but no longer healthy.
        std::fs::remove_file(&artifact).unwrap();
        assert!(!host.is_plugin_healthy("hp"));
        // Still loaded though.
        assert!(host.is_plugin_loaded("hp"));
    }

    #[test]
    fn set_and_get_manifest_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("manifest.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::new();
        host.load_plugin("mp", &artifact).unwrap();

        assert!(host.get_plugin_manifest("mp").is_none());

        let m = sample_manifest();
        host.set_manifest("mp", m.clone());
        let retrieved = host.get_plugin_manifest("mp").unwrap();
        assert_eq!(retrieved.identity.id, m.identity.id);
        assert_eq!(retrieved.tools.len(), m.tools.len());
    }

    #[test]
    fn sync_execution_on_unloaded_returns_not_found() {
        let host = WasmHost::new();
        let err = host
            .execute_tool_sync("nope", "tool", serde_json::json!({}))
            .unwrap_err();
        assert!(matches!(err, WasmError::NotFound(_)));
    }

    #[test]
    fn sync_execution_on_empty_plugin_returns_execution_failed() {
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("empty_sync.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::new();
        host.load_plugin("empty-sync", &artifact).unwrap();

        let err = host
            .execute_tool_sync("empty-sync", "greet", serde_json::json!({}))
            .unwrap_err();
        assert!(
            matches!(err, WasmError::ExecutionFailed(ref msg) if msg.contains("does not export")),
            "expected ExecutionFailed for missing export, got: {:?}",
            err
        );
    }

    #[test]
    fn default_constructor_applies_default_memory_ceiling() {
        let host = WasmHost::new();
        assert_eq!(host.max_memory_bytes(), DEFAULT_PLUGIN_MAX_MEMORY_BYTES);
    }

    #[test]
    fn explicit_memory_ceiling_is_stored() {
        let host = WasmHost::with_max_memory_bytes(4 * 1024 * 1024);
        assert_eq!(host.max_memory_bytes(), 4 * 1024 * 1024);
    }

    #[test]
    fn plugin_declared_limit_lower_than_host_wins() {
        // Host allows 128 MB, plugin asks for 4 MB — effective ceiling is 4 MB
        // (verified indirectly by the bytes_to_pages computation).
        let host_bytes: u64 = 128 * 1024 * 1024;
        let plugin_bytes: u64 = 4 * 1024 * 1024;
        let effective = plugin_bytes.min(host_bytes);
        assert_eq!(effective, plugin_bytes);
        assert_eq!(bytes_to_pages(effective), 64);
    }

    #[test]
    fn host_ceiling_overrides_plugin_declared_higher_limit() {
        // Plugin declares 512 MB but host only permits 128 MB.
        let host_bytes: u64 = 128 * 1024 * 1024;
        let plugin_bytes: u64 = 512 * 1024 * 1024;
        let effective = plugin_bytes.min(host_bytes);
        assert_eq!(effective, host_bytes);
    }

    #[test]
    fn bytes_to_pages_has_minimum_of_one() {
        assert_eq!(bytes_to_pages(0), 1);
        assert_eq!(bytes_to_pages(1), 1);
        assert_eq!(bytes_to_pages(WASM_PAGE_SIZE - 1), 1);
        assert_eq!(bytes_to_pages(WASM_PAGE_SIZE), 1);
        assert_eq!(bytes_to_pages(WASM_PAGE_SIZE * 2), 2);
    }

    #[test]
    fn load_plugin_with_limit_applies_smaller_of_two() {
        // Empty WASM loads successfully and records the applied limit via tracing.
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("cap.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host = WasmHost::with_max_memory_bytes(16 * 1024 * 1024);
        // Plugin declares 4 MB — smaller, so it wins.
        host.load_plugin_with_limit("cap", &artifact, Some(4 * 1024 * 1024))
            .unwrap();
        assert!(host.is_plugin_loaded("cap"));
    }

    #[test]
    fn clone_independent_lifecycle() {
        let dir = tempfile::tempdir().unwrap();
        let artifact = dir.path().join("clone.wasm");
        std::fs::write(&artifact, b"\x00asm\x01\x00\x00\x00").unwrap();

        let host1 = WasmHost::new();
        let host2 = host1.clone();

        // Load via host1, verify visible via host2.
        host1.load_plugin("shared", &artifact).unwrap();
        assert!(host2.is_plugin_loaded("shared"));

        // Unload via host2, verify gone via host1.
        host2.unload_plugin("shared").unwrap();
        assert!(!host1.is_plugin_loaded("shared"));
    }

    #[test]
    fn error_display_contains_useful_info() {
        let err = WasmError::NotFound("my-plugin".to_string());
        assert!(err.to_string().contains("my-plugin"));

        let err = WasmError::LoadFailed("bad wasm".to_string());
        assert!(err.to_string().contains("bad wasm"));

        let err = WasmError::Timeout;
        assert!(err.to_string().contains("timed out"));

        let err = WasmError::InvalidInput("bad json".to_string());
        assert!(err.to_string().contains("bad json"));

        let err = WasmError::PluginPanicked("trap".to_string());
        assert!(err.to_string().contains("trap"));
    }

    #[test]
    fn wasm_error_is_std_error() {
        let err = WasmError::LoadFailed("test".to_string());
        let _: &dyn std::error::Error = &err;
    }
}