refactor: extract neutral host contract and decouple plugin ABI (issue #13)
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was canceled

Implements the core M0-M3 boundary work from issue #13 / ADR-0071 without
changing language semantics or any public protocol:

- add marqdo-host-contract owning Host/HostOp/ExecutionContext/ResourceRead
  and the runtime observation facts; the engine depends on it only.
- marqdo-runtime no longer links marqdo-host; the native host implements the
  contract and has no reverse edge to runtime/frontend/IR.
- reduce marqdo-plugin-abi to the public C ABI/wire/error contract; move
  manifest/artifact/loader/worker execution into marqdo-host::plugin so the
  SDK carries no loader/worker/host dependency.
- add a real independent consumer (tests/embedding, own workspace+lock) that
  runs Markdown -> frontend -> IR -> runtime with bounded budgets and explicit
  effect refusal, plus differential CLI comparison.
- add an SDK-only third-party plugin fixture and real CLI invocation gate.
- replace the frozen-crate architecture test with a reviewed responsibility
  graph enforced from Cargo metadata, with negative unit cases.
- consolidate current docs/entry: ADR-0071, CURRENT responsibility map,
  developers/architecture indexes, historical banners, STATUS and evidence.
- record keep-in-workspace for Engine/Native Host; no empty candidate repo.

Evidence: docs/evidence/2026-11-26-issue-13-engine-host-boundary.md
Refs #13
This commit is contained in:
cflmy committed 2026-11-26 18:37:02 +08:00
1 parent 4bbefc9244
commit 9b4f0a0822
89 files changed
+3490 -545

No files matched your search

+1
View File
@@ -18,6 +18,7 @@ marqdo-frontend = { workspace = true }
marqdo-foreign = { workspace = true }
marqdo-plugin-abi = { workspace = true }
marqdo-host = { workspace = true }
marqdo-host-contract = { workspace = true }
marqdo-runtime = { workspace = true }
marqdo-package = { workspace = true }
marqdo-sandbox = { workspace = true }
+4 -3
View File
@@ -3,7 +3,8 @@
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use marqdo_host::{Host, StdHost};
use marqdo_host::StdHost;
use marqdo_host_contract::Host;
use marqdo_runtime::{run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictOutcome};
use marqdo_span::Span;
@@ -270,12 +271,12 @@ fn load_plugin_into_host(
.parent()
.map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let manifest = marqdo_plugin_abi::PluginManifest::load(&manifest_path)
let manifest = marqdo_host::plugin::PluginManifest::load(&manifest_path)
.map_err(|error| format!("{}: {}", error.code, error.message))?;
manifest
.validate()
.map_err(|error| format!("{}: {}", error.code, error.message))?;
if manifest.plugin.kind == marqdo_plugin_abi::PluginKind::Native && !trusted {
if manifest.plugin.kind == marqdo_host::plugin::PluginKind::Native && !trusted {
return Err(format!(
"loading `{}` in-process requires --trust-native-plugin; use `kind: worker` for crash isolation",
manifest.plugin.name
+3 -3
View File
@@ -274,7 +274,7 @@ pub fn execute(
&& static_plugins
.plugins
.iter()
.any(|plugin| plugin.kind == marqdo_plugin_abi::PluginKind::Native)
.any(|plugin| plugin.kind == marqdo_host::plugin::PluginKind::Native)
{
return fail(
stream,
@@ -558,9 +558,9 @@ mod tests {
base_dir: PathBuf::from("/fixtures/demo"),
package: "demo.ext".into(),
version: "0.1.0".into(),
kind: marqdo_plugin_abi::PluginKind::Worker,
kind: marqdo_host::plugin::PluginKind::Worker,
manifest_sha256: format!("sha256:{}", "b".repeat(64)),
artifact_target: marqdo_plugin_abi::HostTarget::current()
artifact_target: marqdo_host::plugin::HostTarget::current()
.triple()
.to_string(),
artifact_sha256: "a".repeat(64),
+2 -2
View File
@@ -44,7 +44,7 @@ pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
.parent()
.map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let manifest = match marqdo_plugin_abi::PluginManifest::load(&manifest_path) {
let manifest = match marqdo_host::plugin::PluginManifest::load(&manifest_path) {
Ok(manifest) => manifest,
Err(error) => {
report_plugin_error(&error, json);
@@ -55,7 +55,7 @@ pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
report_plugin_error(&error, json);
return 1;
}
let host_target = marqdo_plugin_abi::HostTarget::current();
let host_target = marqdo_host::plugin::HostTarget::current();
let artifact = match manifest.verify_artifact(&base_dir, &host_target) {
Ok((path, artifact)) => {
let abi = match manifest.abi_requirement() {
+1 -1
View File
@@ -10,9 +10,9 @@
use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
use marqdo_host::plugin::{HostTarget, PluginKind, PluginManifest};
use marqdo_ir::callable::{CallableDescriptor, CallableId, CallableOrigin, CallableSignature};
use marqdo_ir::SignatureKind;
use marqdo_plugin_abi::{HostTarget, PluginKind, PluginManifest};
use marqdo_span::Span;
use sha2::{Digest, Sha256};
+4 -4
View File
@@ -81,12 +81,12 @@ fn plugin_identity(extension: &ResolvedExtension) -> Result<LockedExtension, Pre
),
)
})?;
let manifest = marqdo_plugin_abi::PluginManifest::load(&extension.path)
let manifest = marqdo_host::plugin::PluginManifest::load(&extension.path)
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
manifest
.validate()
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
let host = marqdo_plugin_abi::HostTarget::current();
let host = marqdo_host::plugin::HostTarget::current();
let artifact = manifest
.resolve_artifact(&host)
.map_err(|error| PrepareError::option("ext.no_matching_artifact", error.message))?;
@@ -161,7 +161,7 @@ fn provider_identity(extension: &ResolvedExtension) -> Result<LockedExtension, P
format!("`{}` has no version", extension.path.display()),
)
})?;
let target = marqdo_plugin_abi::HostTarget::current()
let target = marqdo_host::plugin::HostTarget::current()
.triple()
.to_string();
let artifacts = manifest
@@ -293,7 +293,7 @@ fn kernel_identity(extension: &ResolvedExtension) -> Result<LockedExtension, Pre
version: format!("wire:{wire_version}"),
manifest_digest: hex(&Sha256::digest(&manifest_bytes)),
artifact_digest: digest.to_ascii_lowercase(),
selected_target: marqdo_plugin_abi::HostTarget::current()
selected_target: marqdo_host::plugin::HostTarget::current()
.triple()
.to_string(),
source: extension.from.clone(),
+1 -1
View File
@@ -500,7 +500,7 @@ fn dispatch() -> i32 {
},
Command::External(args) => tool::dispatch(&args),
Command::PluginWorker(args) => {
marqdo_plugin_abi::worker::serve(&args.manifest, &args.base_dir)
marqdo_host::plugin::worker::serve(&args.manifest, &args.base_dir)
}
}
}
+3 -3
View File
@@ -8,10 +8,10 @@ use std::rc::Rc;
use std::time::{SystemTime, UNIX_EPOCH};
use marqdo_host::{
FrameId, ObservationConfig, ObservationError, ObservationEvent, ObservationSink,
ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES,
ObservationConfig, ObservationError, ObservationEvent, ObservationSink, ValueState,
DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES,
};
use marqdo_host_contract::{FrameId, ParameterSource};
use marqdo_value::Value;
use serde_json::{json, Value as Json};
+2 -2
View File
@@ -16,8 +16,8 @@
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use marqdo_host::plugin::{HostTarget, TargetTriple};
use marqdo_host::StdHost;
use marqdo_plugin_abi::{HostTarget, TargetTriple};
use serde::Deserialize;
use sha2::{Digest, Sha256};
@@ -577,7 +577,7 @@ fn is_lowercase_sha256(value: &str) -> bool {
}
fn is_known_capability(name: &str) -> bool {
marqdo_plugin_abi::KNOWN_CAPABILITIES.contains(&name)
marqdo_host::plugin::KNOWN_CAPABILITIES.contains(&name)
}
/// A dotted vendor capability proposal (validation only, never a grant).
+225 -53
View File
@@ -1,10 +1,12 @@
//! Architecture boundary gate (review RFC-CM P0/P1).
//!
//! These checks pin the documented layering: the runtime depends on the host
//! platform layer, the bundled stdlib stays in this repository, `std:` import
//! targets resolve only inside the bundle, and the host keeps the documented
//! stdio/file/TCP resource endpoints. They are source and digest checks, not an
//! OS-sandbox proof.
//! These checks pin the documented layering: the engine depends on the neutral
//! Host contract (never the native host), the plugin ABI contract carries no
//! loader/worker execution side, the bundled stdlib stays in this repository,
//! `std:` import targets resolve only inside the bundle, and the host keeps the
//! documented stdio/file/TCP resource endpoints. They are source and digest
//! checks, not an OS-sandbox proof; `tools/ci/check_dependency_boundaries.py`
//! adds the Cargo-metadata graph gate.
use std::path::{Path, PathBuf};
@@ -23,66 +25,114 @@ fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display()))
}
const WORKSPACE_CRATES: &[&str] = &[
"marqdo-span",
"marqdo-value",
"marqdo-expression",
"marqdo-markdown",
"marqdo-ir",
"marqdo-frontend",
"marqdo-foreign",
"marqdo-plugin-abi",
"marqdo-provider-worker",
"marqdo-worker-ipc",
"marqdo-plugin-sdk",
"marqdo-host",
"marqdo-runtime",
"marqdo-package",
"marqdo-sandbox",
"cli",
];
/// Issue #13 / ADR-0071: the reviewed responsibility allowlist is the crate
/// table in the single current architecture overview, not a frozen count. A new
/// crate must be added there (and to the dependency gate's reviewed map) in the
/// same change.
#[test]
fn workspace_crates_match_the_documented_layers() {
let manifest = read(&repo_root().join("Cargo.toml"));
fn workspace_crates_are_documented_responsibilities() {
let root = repo_root();
let manifest = read(&root.join("Cargo.toml"));
let members = manifest
.split("members = [")
.nth(1)
.and_then(|rest| rest.split(']').next())
.expect("workspace members");
let names: Vec<&str> = members
let names: Vec<String> = members
.split(',')
.map(|item| item.trim().trim_matches('"'))
.filter(|item| !item.is_empty())
.map(|member| {
let directory = member
.strip_prefix("crates/")
.expect("workspace members are crates/<name>");
let manifest = read(&root.join(member).join("Cargo.toml"));
manifest
.lines()
.find_map(|line| line.strip_prefix("name = "))
.map(|name| name.trim().trim_matches('"').to_string())
.unwrap_or_else(|| directory.to_string())
})
.collect();
let expected: Vec<String> = WORKSPACE_CRATES
.iter()
.map(|name| format!("crates/{name}"))
.collect();
assert_eq!(
names,
expected.iter().map(String::as_str).collect::<Vec<_>>(),
"workspace members drifted; update docs/architecture/CURRENT.md with the layer"
);
let current = read(&root.join("docs/architecture/CURRENT.md"));
let responsibilities = current
.split("## Workspace crate responsibility map")
.nth(1)
.expect("CURRENT.md must own the reviewed crate responsibility map")
.split("\n## ")
.next()
.unwrap_or("");
for name in &names {
assert!(
responsibilities.contains(&format!("`{name}`")),
"workspace crate `{name}` has no documented responsibility in CURRENT.md"
);
}
for name in [
"marqdo-host-contract",
"marqdo-host",
"marqdo-plugin-abi",
"marqdo-cli",
] {
assert!(
names.iter().any(|crate_name| crate_name == name),
"required layer crate `{name}` is missing from the workspace"
);
}
assert!(
!names.contains(&"crates/marqdo-stdlib"),
"the stdlib must stay in this repository (ADR-0039), not become a crate"
!names.iter().any(|name| name == "marqdo-stdlib"),
"the stdlib is a Bundle input, not a workspace crate (ADR-0039/ADR-0070)"
);
}
#[test]
fn runtime_depends_on_the_host_platform_layer_without_a_cycle() {
let runtime = read(&repo_root().join("crates/marqdo-runtime/Cargo.toml"));
fn engine_depends_on_the_neutral_host_contract_only() {
let root = repo_root();
let runtime = read(&root.join("crates/marqdo-runtime/Cargo.toml"));
let runtime_dependencies = runtime
.split("[dependencies]")
.nth(1)
.expect("runtime dependencies")
.split("[dev-dependencies]")
.next()
.expect("runtime normal dependencies");
assert!(
runtime
runtime_dependencies
.lines()
.any(|line| line.trim() == "marqdo-host-contract = { workspace = true }"),
"runtime must depend on the neutral marqdo-host-contract crate"
);
assert!(
!runtime_dependencies
.lines()
.any(|line| line.trim() == "marqdo-host = { workspace = true }"),
"runtime must keep the documented marqdo-runtime -> marqdo-host direction"
"runtime normal/build dependencies must not link the native host"
);
let host = read(&repo_root().join("crates/marqdo-host/Cargo.toml"));
let contract = read(&root.join("crates/marqdo-host-contract/Cargo.toml"));
let contract_deps: Vec<&str> = contract
.split("[dependencies]")
.nth(1)
.expect("contract dependencies")
.lines()
.filter_map(|line| line.split('=').next())
.map(str::trim)
.filter(|name| !name.is_empty() && !name.starts_with('['))
.collect();
assert_eq!(
contract_deps,
["marqdo-span", "marqdo-value"],
"the host contract must stay platform neutral (value/span only)"
);
let host = read(&root.join("crates/marqdo-host/Cargo.toml"));
for forbidden in ["marqdo-runtime", "marqdo-frontend", "marqdo-ir ="] {
assert!(
!host.contains(forbidden),
"the native host must not depend back on `{forbidden}`"
);
}
assert!(
!host.contains("marqdo-runtime"),
"marqdo-host must not depend back on marqdo-runtime"
host.contains("marqdo-host-contract = { workspace = true }"),
"the native host must implement the neutral contract crate"
);
}
@@ -153,7 +203,6 @@ fn shared_worker_transport_is_neutral_and_not_duplicated() {
}
for user in [
"crates/marqdo-host/Cargo.toml",
"crates/marqdo-plugin-abi/Cargo.toml",
"crates/marqdo-provider-worker/Cargo.toml",
] {
assert!(
@@ -164,8 +213,8 @@ fn shared_worker_transport_is_neutral_and_not_duplicated() {
// The four-byte length prefix and its bounds live in exactly one crate.
for private in [
"crates/marqdo-host/src/plugin_worker.rs",
"crates/marqdo-host/src/plugin/worker.rs",
"crates/marqdo-host/src/provider_worker.rs",
"crates/marqdo-plugin-abi/src/worker.rs",
"crates/marqdo-provider-worker/src/main.rs",
] {
let text = read(&root.join(private));
@@ -409,12 +458,12 @@ fn builtin_names_and_aliases_are_reviewed() {
}
// Exhaustive matches make a new HostOp or Value variant require review under ADR-0064.
const _: fn(marqdo_host::HostOp) = |operation| match operation {
marqdo_host::HostOp::ForeignRun
| marqdo_host::HostOp::ForeignCall
| marqdo_host::HostOp::FsRead
| marqdo_host::HostOp::FsWrite
| marqdo_host::HostOp::PluginInvoke => (),
const _: fn(marqdo_host_contract::HostOp) = |operation| match operation {
marqdo_host_contract::HostOp::ForeignRun
| marqdo_host_contract::HostOp::ForeignCall
| marqdo_host_contract::HostOp::FsRead
| marqdo_host_contract::HostOp::FsWrite
| marqdo_host_contract::HostOp::PluginInvoke => (),
};
const _: fn(marqdo_value::Value) = |value| match value {
@@ -565,6 +614,129 @@ fn domain_math_kernel_is_not_part_of_the_core() {
}
}
/// E02/E03: there is exactly one Host trait/HostOp definition and it belongs to
/// the neutral contract; the native host only implements it.
#[test]
fn host_contract_is_the_single_side_effect_interface() {
let root = repo_root();
let mut host_traits = Vec::new();
let mut host_ops = Vec::new();
for source in walk_rs(&root.join("crates")) {
let relative = source
.strip_prefix(&root)
.unwrap()
.to_string_lossy()
.to_string();
if relative.contains("/tests/") {
continue;
}
let text = read(&source);
if text.contains("pub trait Host {") {
host_traits.push(relative.clone());
}
if text.contains("pub enum HostOp {") {
host_ops.push(relative);
}
}
assert_eq!(
host_traits,
["crates/marqdo-host-contract/src/host.rs"],
"the Host trait must be defined once in the neutral contract"
);
assert_eq!(
host_ops,
["crates/marqdo-host-contract/src/host.rs"],
"HostOp must be defined once in the neutral contract"
);
let runtime = read(&root.join("crates/marqdo-runtime/src/interpreter.rs"));
assert!(
runtime.contains("use marqdo_host_contract::{"),
"the interpreter must consume the neutral contract"
);
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
assert!(
host.contains("impl Host for StdHost"),
"StdHost remains the single native host implementation"
);
}
/// A05/S01: the public ABI crate is a contract, not a loader; execution side
/// lives in the native host and the SDK consumes only the contract.
#[test]
fn plugin_contract_carries_no_native_execution() {
let root = repo_root();
let abi = read(&root.join("crates/marqdo-plugin-abi/Cargo.toml"));
for forbidden in ["libloading", "marqdo-worker-ipc", "serde_yaml", "sha2"] {
assert!(
!abi.contains(forbidden),
"marqdo-plugin-abi must not depend on execution-side `{forbidden}`"
);
}
for module in ["loader", "worker", "manifest", "artifact"] {
assert!(
!root
.join(format!("crates/marqdo-plugin-abi/src/{module}.rs"))
.exists(),
"`{module}` is execution-side and belongs to the native host"
);
}
for module in ["loader", "worker", "manifest", "artifact"] {
assert!(
root.join(format!("crates/marqdo-host/src/plugin/{module}.rs"))
.exists(),
"native host must own plugin `{module}`"
);
}
let sdk = read(&root.join("crates/marqdo-plugin-sdk/Cargo.toml"));
for forbidden in [
"marqdo-host",
"marqdo-cli",
"libloading",
"marqdo-worker-ipc",
] {
assert!(
!sdk.contains(forbidden),
"the plugin SDK must not depend on `{forbidden}`"
);
}
}
/// E01/E04: the independent embedding consumer is a real package outside the
/// workspace and depends only on engine crates.
#[test]
fn embedding_consumer_is_engine_only() {
let root = repo_root();
let consumer = read(&root.join("tests/embedding/Cargo.toml"));
assert!(
consumer.contains("[workspace]"),
"the embedding consumer must be its own workspace to avoid feature unification"
);
assert!(
consumer.contains("marqdo-runtime"),
"the embedding consumer must execute through the real runtime"
);
for forbidden in [
"marqdo-host",
"marqdo-cli",
"marqdo-sandbox",
"marqdo-foreign",
] {
let dependency_line = format!("\n{forbidden} =");
assert!(
!consumer.contains(&dependency_line),
"the embedding consumer must not depend on `{forbidden}`"
);
}
assert!(
root.join("tests/embedding/Cargo.lock").is_file(),
"the independent consumer must pin its own lock file"
);
assert!(
root.join("tools/ci/check_engine_boundary.py").is_file(),
"the build-and-run engine gate must exist"
);
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
+1 -1
View File
@@ -11,7 +11,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0);
+2 -1
View File
@@ -22,7 +22,8 @@
use std::fs;
use std::path::{Path, PathBuf};
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_ir::{ModuleId, Program, ResolvedImport};
use marqdo_runtime::{run, EvaluatedArg};
use marqdo_sandbox::SandboxMode;
+1 -1
View File
@@ -9,7 +9,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0);
+1 -1
View File
@@ -783,7 +783,7 @@ fn lock_and_sync_locked_detect_dependency_tampering() {
/// the Linux-only example manifest. This is what makes the integration test a
/// real test on macOS/Windows rather than an accidental "no matching artifact".
fn host_triple() -> String {
marqdo_plugin_abi::artifact::current_target_triple()
marqdo_host::plugin::artifact::current_target_triple()
.as_str()
.to_string()
}
+1 -1
View File
@@ -280,7 +280,7 @@ fn native_plugin_is_fail_closed_in_event_mode() {
let digest = hex::encode(sha2::Sha256::digest(fs::read(&artifact).unwrap()));
let manifest = format!(
"plugin:\n name: demo.solver\n version: 0.1.0\n abi: \"^1.0\"\n kind: native\n exports:\n - name: solver.add\n signature: \"($a: Int, $b: Int) -> Int\"\n requires:\n - math.compute\n artifacts:\n - target: {}\n file: solver.so\n sha256: \"{}\"\n",
marqdo_plugin_abi::HostTarget::current().triple(),
marqdo_host::plugin::HostTarget::current().triple(),
digest
);
fs::write(plugin_dir.join("plugin.yaml"), manifest).unwrap();
+1 -1
View File
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget};
use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0);
+1 -1
View File
@@ -24,7 +24,7 @@ use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::OnceLock;
use marqdo_plugin_abi::HostTarget;
use marqdo_host::plugin::HostTarget;
use sha2::{Digest, Sha256};
const MARKER_ENV: &str = "MARQDO_TEST_PROVIDER_MARKER";
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "marqdo-host-contract"
description = "Platform-neutral Host contract: the only side-effect boundary the runtime may know"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
authors.workspace = true
[dependencies]
marqdo-span = { workspace = true }
marqdo-value = { workspace = true }
File renamed without changes.
+194
View File
@@ -0,0 +1,194 @@
//! The host boundary used by the interpreter and future frontends.
//!
//! The trait is implemented by the native CLI host, by the independent
//! embedding/test host and by any future host. Implementations own effects,
//! grants and budgets; the runtime only requests operations through this
//! interface and never performs external I/O itself.
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
use crate::context::ExecutionContext;
use crate::observe::{FrameId, RuntimeObservation};
use crate::resource::ResourceRead;
/// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostOp {
/// One-shot foreign execution.
ForeignRun,
/// Typed foreign call.
ForeignCall,
/// Read a project file.
FsRead,
/// Write a project file.
FsWrite,
/// Invoke a plugin export.
PluginInvoke,
}
impl HostOp {
/// Stable operation name used in traces and diagnostics.
pub const fn name(self) -> &'static str {
match self {
HostOp::ForeignRun => "foreign.run",
HostOp::ForeignCall => "foreign.call",
HostOp::FsRead => "fs.read",
HostOp::FsWrite => "fs.write",
HostOp::PluginInvoke => "plugin.invoke",
}
}
}
/// The host boundary used by the interpreter and future View/IDE frontends.
pub trait Host {
/// Invoke one operation with already-evaluated arguments.
fn invoke(
&mut self,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError>;
/// Open a resource/stream by kind, descriptor and requested rights.
///
/// Default: unavailable. Only the standard host implements the first
/// resource kinds (ADR-0025).
fn resource_open(
&mut self,
_kind: &str,
_descriptor: &str,
_rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Read up to `max_bytes` from a resource into host memory.
fn resource_read(
&mut self,
_handle: ResourceHandle,
_max_bytes: usize,
ctx: &ExecutionContext,
) -> Result<ResourceRead, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Write bytes to a resource; returns the accepted count.
fn resource_write(
&mut self,
_handle: ResourceHandle,
_bytes: &[u8],
ctx: &ExecutionContext,
) -> Result<usize, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Close a resource handle.
fn resource_close(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<(), RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Accept one inbound TCP connection from a `tcp-listener` handle.
///
/// Default: unavailable. The standard host returns a new `Resource` in a
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
fn resource_accept(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide tcp listeners",
))
}
/// Execute one non-streaming resource operation (ADR-0041).
///
/// Default: unavailable. The standard host implements the `fs.*` group;
/// every call is capability-checked and project-mode only.
fn resource_request(
&mut self,
_operation: &str,
_args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource operations",
))
}
/// Consume evaluation fuel.
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check call-stack depth.
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check the wall-clock deadline.
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError>;
/// Take the buffered program output.
fn take_output(&mut self) -> Vec<u8>;
/// Whether the host has an installed observation sink.
///
/// The default host is inert; the interpreter uses this to skip building
/// any observation event when there is no capture destination.
fn observation_enabled(&self) -> bool {
false
}
/// Announce a successfully bound call frame.
///
/// Returns the run-unique frame identity, or `None` when observation is
/// disabled. Argument binding must have completed before this is called;
/// a binding failure never produces a frame.
fn observation_begin_frame(
&mut self,
_function_id: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<Option<FrameId>, RuntimeError> {
Ok(None)
}
/// Close a previously announced frame, including failure paths.
fn observation_end_frame(
&mut self,
_frame_id: Option<FrameId>,
_status: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<(), RuntimeError> {
Ok(())
}
/// Emit one borrowed runtime observation event. Default: ignored.
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
Ok(())
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Platform-neutral Host contract.
//!
//! This crate owns the only side-effect interface the language engine knows:
//! the [`Host`] trait, its [`HostOp`] surface, the per-call
//! [`ExecutionContext`], the opaque resource read result and the runtime
//! observation notifications. It is a Rust compile-time interface inside one
//! codebase, not a wire protocol: there is no HTTP, RPC, C ABI or dynamic
//! loading boundary here.
//!
//! The crate is deliberately neutral. It depends only on the language value
//! and span types; it must never link the native host, the CLI, the sandbox,
//! foreign kernels, the plugin loader or a project filesystem. Native and
//! embedded hosts implement [`Host`] without re-implementing any language
//! semantics. Authorization, budgets, resource identity and OS isolation stay
//! owned by the trusted host implementation that consumes this contract.
pub mod context;
pub mod host;
pub mod observe;
pub mod resource;
pub use context::ExecutionContext;
pub use host::{Host, HostOp};
pub use observe::{FrameId, LoopTransfer, ParameterSource, RuntimeObservation};
pub use resource::ResourceRead;
+118
View File
@@ -0,0 +1,118 @@
//! Runtime observation facts shared by the interpreter and the host contract.
//!
//! Only the types the interpreter itself produces and hands to [`crate::Host`]
//! live here. The host implementation keeps the concrete sink, redaction,
//! encoding and budget state; the public Observation protocol remains the
//! CLI's single producer. This module must not grow a second event vocabulary.
use marqdo_span::Span;
use marqdo_value::Value;
/// Opaque run-scoped call-instance identity.
///
/// Not a function identity, not a source location and never a memory pointer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FrameId(pub u64);
impl FrameId {
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
pub fn as_wire(self) -> String {
format!("f{}", self.0)
}
}
/// Where a bound parameter's value came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParameterSource {
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
Provided,
/// Evaluated from the declared default expression.
Default,
}
impl ParameterSource {
/// Stable wire name.
pub const fn as_str(self) -> &'static str {
match self {
ParameterSource::Provided => "provided",
ParameterSource::Default => "default",
}
}
}
/// The action carried by a structured loop transfer observation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopTransfer {
/// Exit the enclosing loop.
Break,
/// Proceed to the enclosing loop's next condition check.
Continue,
}
impl LoopTransfer {
/// The event kind in Observation.
pub fn event_kind(self) -> &'static str {
match self {
Self::Break => "control.break",
Self::Continue => "control.continue",
}
}
}
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
///
/// Value and control observations carry the owning call frame.
#[derive(Debug)]
pub enum RuntimeObservation<'a> {
/// A local memory operation committed.
Effect {
operation: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A `return` statement committed (before the call exits).
Return {
frame_id: Option<FrameId>,
value_type: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A branch condition evaluated.
BranchEval {
frame_id: Option<FrameId>,
result: bool,
module_id: &'a str,
span: Option<Span>,
},
/// A loop condition evaluated.
LoopIteration {
frame_id: Option<FrameId>,
decision: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: Option<FrameId>,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// A local variable assignment committed.
VariableAssigned {
frame_id: Option<FrameId>,
name: &'a str,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
/// A parameter was bound.
ParameterBound {
frame_id: Option<FrameId>,
name: &'a str,
source: ParameterSource,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
}
@@ -0,0 +1,10 @@
//! Values crossing the resource stream methods of [`crate::Host`].
/// Bytes returned by one stream read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceRead {
/// Bytes actually read (may be empty at EOF).
pub bytes: Vec<u8>,
/// Whether the stream has reached EOF.
pub eof: bool,
}
+4
View File
@@ -12,6 +12,7 @@ authors.workspace = true
libloading = { workspace = true }
rustls = { workspace = true }
rustls-native-certs = { workspace = true }
marqdo-host-contract = { workspace = true }
marqdo-plugin-abi = { workspace = true }
marqdo-worker-ipc = { workspace = true }
flate2 = { workspace = true }
@@ -23,6 +24,9 @@ marqdo-value = { workspace = true }
marqdo-foreign = { workspace = true }
marqdo-sandbox = { workspace = true }
serde = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
serde_yaml = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+15 -194
View File
@@ -9,27 +9,30 @@ use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use marqdo_plugin_abi::{
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
use crate::plugin::{
CapabilityHandler, HostTarget, LoadOptions, LoadedPlugin, PluginKind, PluginManifest,
};
use marqdo_host_contract::{
ExecutionContext, FrameId, Host, HostOp, ResourceRead, RuntimeObservation,
};
use marqdo_plugin_abi::{ErrorKind as PluginErrorKind, PluginError};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
use rustls::pki_types::CertificateDer;
use crate::budget::Budget;
use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
use crate::context::ExecutionContext;
use crate::fs::ProjectFs;
use crate::handles::{contains_plugin_handle, PluginHandleTable};
use crate::observe::{
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError,
ObservationEvent, ObservationSink, ObservationState, RuntimeObservation,
encode_value, estimate_event_bytes, ObservationConfig, ObservationError, ObservationEvent,
ObservationSink, ObservationState,
};
use crate::plugin_worker::WorkerPlugin;
use crate::provider_c::{load_package, CResourceProvider};
use crate::provider_worker::WorkerResourceProvider;
use crate::resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
is_core_resource_kind, ResourceProvider, ResourceTable, SharedResourceProvider,
};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
@@ -38,187 +41,6 @@ mod providers;
mod resource_ops;
mod resource_requests;
/// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostOp {
/// One-shot foreign execution.
ForeignRun,
/// Typed foreign call.
ForeignCall,
/// Read a project file.
FsRead,
/// Write a project file.
FsWrite,
/// Invoke a plugin export.
PluginInvoke,
}
impl HostOp {
/// Stable operation name used in traces and diagnostics.
pub const fn name(self) -> &'static str {
match self {
HostOp::ForeignRun => "foreign.run",
HostOp::ForeignCall => "foreign.call",
HostOp::FsRead => "fs.read",
HostOp::FsWrite => "fs.write",
HostOp::PluginInvoke => "plugin.invoke",
}
}
}
/// The host boundary used by the interpreter and future View/IDE frontends.
pub trait Host {
/// Invoke one operation with already-evaluated arguments.
fn invoke(
&mut self,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError>;
/// Open a resource/stream by kind, descriptor and requested rights.
///
/// Default: unavailable. Only the standard host implements the first
/// resource kinds (ADR-0025).
fn resource_open(
&mut self,
_kind: &str,
_descriptor: &str,
_rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Read up to `max_bytes` from a resource into host memory.
fn resource_read(
&mut self,
_handle: ResourceHandle,
_max_bytes: usize,
ctx: &ExecutionContext,
) -> Result<ResourceRead, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Write bytes to a resource; returns the accepted count.
fn resource_write(
&mut self,
_handle: ResourceHandle,
_bytes: &[u8],
ctx: &ExecutionContext,
) -> Result<usize, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Close a resource handle.
fn resource_close(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<(), RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Accept one inbound TCP connection from a `tcp-listener` handle.
///
/// Default: unavailable. The standard host returns a new `Resource` in a
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
fn resource_accept(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide tcp listeners",
))
}
/// Execute one non-streaming resource operation (ADR-0041).
///
/// Default: unavailable. The standard host implements the `fs.*` group;
/// every call is capability-checked and project-mode only.
fn resource_request(
&mut self,
_operation: &str,
_args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource operations",
))
}
/// Consume evaluation fuel.
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check call-stack depth.
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check the wall-clock deadline.
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError>;
/// Take the buffered program output.
fn take_output(&mut self) -> Vec<u8>;
/// Whether the host has an installed observation sink.
///
/// The default host is inert; the interpreter uses this to skip building
/// any observation event when there is no capture destination.
fn observation_enabled(&self) -> bool {
false
}
/// Announce a successfully bound call frame.
///
/// Returns the run-unique frame identity, or `None` when observation is
/// disabled. Argument binding must have completed before this is called;
/// a binding failure never produces a frame.
fn observation_begin_frame(
&mut self,
_function_id: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<Option<FrameId>, RuntimeError> {
Ok(None)
}
/// Close a previously announced frame, including failure paths.
fn observation_end_frame(
&mut self,
_frame_id: Option<FrameId>,
_status: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<(), RuntimeError> {
Ok(())
}
/// Emit one borrowed runtime observation event. Default: ignored.
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
Ok(())
}
}
/// Default capability host implementation.
pub struct StdHost {
/// Requested sandbox mode.
@@ -372,7 +194,7 @@ impl StdHost {
exports.insert(export.name.clone(), export.signature.clone());
}
let artifact = manifest
.resolve_artifact(&marqdo_plugin_abi::HostTarget::current())
.resolve_artifact(&HostTarget::current())
.map_err(map_plugin_error)?;
let manifest_digest = artifact.sha256.clone();
let transport = match manifest.plugin.kind {
@@ -398,8 +220,8 @@ impl StdHost {
broker.allow_vendor(capability.clone());
}
let package = manifest.plugin.name.clone();
let options = marqdo_plugin_abi::LoadOptions {
host_target: marqdo_plugin_abi::HostTarget::current(),
let options = LoadOptions {
host_target: HostTarget::current(),
capability_handler: Some(Box::new(move |capability, request| {
broker.execute(&package, capability, request)
})),
@@ -419,10 +241,9 @@ impl StdHost {
broker.allow_vendor(capability.clone());
}
let package = manifest.plugin.name.clone();
let handler: marqdo_plugin_abi::CapabilityHandler =
Box::new(move |capability, request| {
broker.execute(&package, capability, request)
});
let handler: CapabilityHandler = Box::new(move |capability, request| {
broker.execute(&package, capability, request)
});
PluginTransport::Worker(
WorkerPlugin::spawn(manifest, base_dir, Some(handler))
.map_err(map_plugin_error)?,
+2 -2
View File
@@ -11,8 +11,8 @@ use std::time::Duration;
use marqdo_value::{to_wire, ErrorCategory, RuntimeError, Value};
use crate::context::ExecutionContext;
use crate::host::{HostOp, StdHost};
use crate::host::StdHost;
use marqdo_host_contract::{ExecutionContext, HostOp};
pub(crate) fn foreign(
host: &mut StdHost,
+21 -12
View File
@@ -1,17 +1,28 @@
//! CapabilityHost: capability checks, resource budgets, observation and the
//! only bridge to math, foreign kernels, files and plugins.
//! Native Host: the one concrete implementation of the neutral
//! [`marqdo_host_contract::Host`] boundary.
//!
//! Blueprint §9 and §7.3: every side effect goes through this boundary, checks
//! happen at the point of execution, and host failures are structured errors.
//! Every side effect goes through this crate, checks happen at the point of
//! execution, and host failures are structured errors. The crate owns the OS
//! adapters, capability grants, resource handles, observation sink and trusted
//! extension execution; it never owns language semantics and never depends back
//! on the runtime, frontend or IR.
//!
//! Responsibility map (ADR-0071):
//! - [`capability`]/[`budget`]: grants, broker, audit, fuel/stack/deadline/output;
//! - [`resource`], [`fs`], `process`: resource kinds, handles and OS effects;
//! - [`plugin`], `plugin_worker`, `provider_c`, `provider_worker`, [`kernels`]:
//! trusted plugin/provider/foreign execution (no second static binder);
//! - [`observe`]: the runtime observation sink, redaction, budget and encoding;
//! - [`host`]: `StdHost` assembly and the single dispatch table.
pub mod budget;
pub mod capability;
pub mod context;
pub mod fs;
pub mod handles;
pub mod host;
pub mod kernels;
pub mod observe;
pub mod plugin;
mod plugin_worker;
mod process;
mod provider_c;
@@ -23,18 +34,16 @@ pub use capability::{
Capabilities, CapabilityAudit, CapabilityBroker, CapabilityHandler, CapabilityRequest,
FsReadHandler, CORE_CAPABILITIES, RESERVED_HANDLER_PREFIXES,
};
pub use context::ExecutionContext;
pub use fs::ProjectFs;
pub use handles::{contains_plugin_handle, PluginHandleTable};
pub use host::{arity, expect_text, Host, HostOp, StdHost};
pub use host::{arity, expect_text, StdHost};
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
pub use observe::{
encode_value, estimate_event_bytes, FrameId, LoopTransfer, ObservationConfig, ObservationError,
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation,
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
encode_value, estimate_event_bytes, ObservationConfig, ObservationError, ObservationEvent,
ObservationSink, ObservedValue, ValueState, DEFAULT_MAX_OBSERVATION_BYTES,
DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
};
pub use resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
is_core_resource_kind, ResourceProvider, ResourceTable, SharedResourceProvider,
CORE_RESOURCE_KINDS,
};
+1 -109
View File
@@ -12,6 +12,7 @@
use std::collections::BTreeSet;
use marqdo_host_contract::{FrameId, LoopTransfer, ParameterSource};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError, Value};
@@ -24,38 +25,6 @@ pub const DEFAULT_MAX_VALUE_BYTES: usize = 256;
/// Maximum committed stdio bytes carried by one chunk event.
pub const MAX_STREAM_CHUNK_BYTES: usize = 64 * 1024;
/// Opaque run-scoped call-instance identity.
///
/// Not a function identity, not a source location and never a memory pointer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FrameId(pub u64);
impl FrameId {
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
pub fn as_wire(self) -> String {
format!("f{}", self.0)
}
}
/// Where a bound parameter's value came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParameterSource {
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
Provided,
/// Evaluated from the declared default expression.
Default,
}
impl ParameterSource {
/// Stable wire name.
pub const fn as_str(self) -> &'static str {
match self {
ParameterSource::Provided => "provided",
ParameterSource::Default => "default",
}
}
}
/// Observation policy for one run.
///
/// `structural` always implies frame identity; value events only exist for
@@ -238,83 +207,6 @@ pub enum ObservationEvent<'a> {
},
}
/// The action carried by a structured loop transfer observation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopTransfer {
/// Exit the enclosing loop.
Break,
/// Proceed to the enclosing loop's next condition check.
Continue,
}
impl LoopTransfer {
/// The event kind in Observation.
pub fn event_kind(self) -> &'static str {
match self {
Self::Break => "control.break",
Self::Continue => "control.continue",
}
}
}
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
///
/// Value and control observations carry the owning call frame.
#[derive(Debug)]
pub enum RuntimeObservation<'a> {
/// A local memory operation committed.
Effect {
operation: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A `return` statement committed (before the call exits).
Return {
frame_id: Option<FrameId>,
value_type: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A branch condition evaluated.
BranchEval {
frame_id: Option<FrameId>,
result: bool,
module_id: &'a str,
span: Option<Span>,
},
/// A loop condition evaluated.
LoopIteration {
frame_id: Option<FrameId>,
decision: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: Option<FrameId>,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// A local variable assignment committed.
VariableAssigned {
frame_id: Option<FrameId>,
name: &'a str,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
/// A parameter was bound.
ParameterBound {
frame_id: Option<FrameId>,
name: &'a str,
source: ParameterSource,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
}
/// Sink installed by the composition root (the CLI JSONL writer in product
/// builds, an in-memory recorder in tests).
pub trait ObservationSink {
@@ -11,7 +11,7 @@ use std::path::Path;
use sha2::{Digest, Sha256};
use crate::error::PluginError;
use marqdo_plugin_abi::PluginError;
/// Length of a lowercase hexadecimal sha256 digest.
pub const SHA256_HEX_LEN: usize = 64;
@@ -16,16 +16,16 @@ use std::ptr;
use libloading::{Library, Symbol};
use serde::Deserialize;
use crate::abi::{
use super::artifact::HostTarget;
use super::manifest::{PluginKind, PluginManifest};
use marqdo_plugin_abi::abi::{
check_host_api, negotiate, result, AbiVersion, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes,
MqPluginApi, MqPluginEntryV1, MqPluginInvoke, PluginMetadata, ABI_MAJOR, ABI_MINOR,
ENTRY_SYMBOL, MAX_CAPABILITY_REPLY_BYTES, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
MAX_RESULT_WIRE_BYTES, MAX_SIGNATURE_WIRE_BYTES,
};
use crate::artifact::HostTarget;
use crate::error::PluginError;
use crate::manifest::{PluginKind, PluginManifest};
use crate::wire::{WireRequest, WireResponse};
use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
use marqdo_plugin_abi::PluginError;
/// A callback the host installs to answer capability requests from a plugin.
///
@@ -304,13 +304,13 @@ impl LoadedPlugin {
/// This is primarily for ABI conformance tests; prefer
/// [`LoadedPlugin::invoke`] for normal use.
pub fn invoke_raw(&mut self, function: &str, args_wire: &[u8]) -> Result<Vec<u8>, PluginError> {
if args_wire.len() > crate::abi::MAX_REQUEST_WIRE_BYTES {
if args_wire.len() > marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES {
return Err(PluginError::wire(
"request_too_large",
format!(
"request wire is {} bytes, limit is {}",
args_wire.len(),
crate::abi::MAX_REQUEST_WIRE_BYTES
marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES
),
));
}
@@ -10,12 +10,12 @@ use std::path::{Component, Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::abi::{
use super::artifact::{is_valid_sha256_hex, TargetTriple};
use super::artifact::{verify_sha256_file, HostTarget};
use marqdo_plugin_abi::abi::{
AbiVersion, ABI_MAJOR, ABI_MINOR, MAX_EXPORT_NAME_BYTES, MAX_SIGNATURE_WIRE_BYTES,
};
use crate::artifact::{is_valid_sha256_hex, TargetTriple};
use crate::artifact::{verify_sha256_file, HostTarget};
use crate::error::PluginError;
use marqdo_plugin_abi::PluginError;
/// Maximum number of exports a single plugin may register.
pub const MAX_EXPORTS: usize = 256;
@@ -648,7 +648,7 @@ plugin:
#[test]
fn malformed_yaml_is_rejected() {
let error = PluginManifest::parse_str("plugin: [unclosed").expect_err("must fail");
assert_eq!(error.kind, crate::error::ErrorKind::Manifest);
assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Manifest);
assert_eq!(error.code, "manifest_parse_failed");
assert!(PluginManifest::parse_str("not_a_plugin: 1").is_err());
}
@@ -683,7 +683,7 @@ plugin:
),
Err(error) => assert_eq!(
error.kind,
crate::error::ErrorKind::Manifest,
marqdo_plugin_abi::ErrorKind::Manifest,
"`{field}` = `{value}` should fail manifest handling"
),
}
+26
View File
@@ -0,0 +1,26 @@
//! Execution side of the Callable Plugin ABI: manifest/artifact validation,
//! native loading, invocation dispatch and the worker process.
//!
//! The public contract (C layout, wire envelope and protocol errors) lives in
//! `marqdo-plugin-abi`; this module owns `dlopen`, process spawning, artifact
//! file selection and trusted invocation. The CLI may consume the static
//! descriptor types for `check`/`inspect` preparation, but preparation never
//! loads a library or starts a process.
//!
//! The `include/marqdo_plugin_abi_v1.h` header and the Rust layout assertions
//! in `marqdo_plugin_abi::abi` remain the single ABI authority.
pub mod artifact;
pub mod loader;
pub mod manifest;
pub mod worker;
pub use artifact::{
current_target_triple, is_valid_sha256_hex, sha256_bytes, sha256_file, verify_sha256_file,
HostTarget, TargetTriple,
};
pub use loader::{CapabilityHandler, LoadOptions, LoadedPlugin, RegisteredExport};
pub use manifest::{
AbiRequirement, Artifact, Export, PackageVersion, PluginInfo, PluginKind, PluginManifest,
KNOWN_CAPABILITIES,
};
@@ -13,10 +13,10 @@ use std::sync::{Arc, Mutex};
use serde_json::{json, Value};
use crate::error::PluginError;
use crate::loader::{LoadOptions, LoadedPlugin};
use crate::manifest::{PluginKind, PluginManifest};
use crate::wire::{WireRequest, WireResponse};
use super::loader::{LoadOptions, LoadedPlugin};
use super::manifest::{PluginKind, PluginManifest};
use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
use marqdo_plugin_abi::PluginError;
/// Hidden CLI command name used to start a worker.
pub const WORKER_COMMAND: &str = "__plugin-worker";
@@ -91,7 +91,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
let handler_stdout = Arc::clone(&stdout);
let handler_ids = Arc::clone(&next_request_id);
let handler_calls = Arc::clone(&capability_calls);
let capability_handler: crate::loader::CapabilityHandler = Box::new(
let capability_handler: super::loader::CapabilityHandler = Box::new(
move |capability, request| {
if handler_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CAPABILITY_REQUESTS {
return Err(PluginError::capability(
@@ -185,7 +185,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
},
);
let options = LoadOptions {
host_target: crate::artifact::HostTarget::current(),
host_target: super::artifact::HostTarget::current(),
capability_handler: Some(capability_handler),
};
let mut plugin = match LoadedPlugin::open_with(&native_manifest, base_dir, options) {
+3 -4
View File
@@ -15,13 +15,12 @@ use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use marqdo_plugin_abi::worker::{
use crate::plugin::worker::{
response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES,
WORKER_COMMAND,
};
use marqdo_plugin_abi::{
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
};
use crate::plugin::{CapabilityHandler, PluginManifest};
use marqdo_plugin_abi::{PluginError, WireRequest, WireResponse};
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
use serde_json::json;
+1 -1
View File
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
use marqdo_value::{ErrorCategory, RuntimeError, Value};
use crate::context::ExecutionContext;
use marqdo_host_contract::ExecutionContext;
fn process_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
+2 -1
View File
@@ -12,7 +12,8 @@ use libloading::Library;
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError};
use crate::resource::{ResourceProvider, ResourceRead};
use crate::resource::ResourceProvider;
use marqdo_host_contract::ResourceRead;
const ABI_VERSION: u32 = 1;
const ERROR_MAX: usize = 1024;
+2 -1
View File
@@ -18,7 +18,8 @@ use marqdo_span::Span;
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
use serde_json::{json, Value as Json};
use crate::resource::{ResourceProvider, ResourceRead};
use crate::resource::ResourceProvider;
use marqdo_host_contract::ResourceRead;
use marqdo_value::{ErrorCategory, RuntimeError};
const MAX_FRAME_BYTES: usize = 1024 * 1024;
+1 -9
View File
@@ -13,6 +13,7 @@ use rustls::{ClientConnection, StreamOwned};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use marqdo_host_contract::ResourceRead;
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
@@ -83,15 +84,6 @@ pub trait ResourceProvider: Send {
/// Shared provider handle registered on the host.
pub type SharedResourceProvider = Arc<Mutex<Box<dyn ResourceProvider>>>;
/// Bytes returned by one stream read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceRead {
/// Bytes actually read (may be empty at EOF).
pub bytes: Vec<u8>,
/// Whether the stream has reached EOF.
pub eof: bool,
}
struct StdinCursor {
bytes: Vec<u8>,
position: usize,
+4 -3
View File
@@ -3,12 +3,13 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_sandbox::SandboxMode;
use marqdo_value::ErrorCategory;
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
fn context() -> marqdo_host_contract::ExecutionContext {
marqdo_host_contract::ExecutionContext::new("test".to_string(), None)
}
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
@@ -5,8 +5,9 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_host::{Capabilities, Host, HostOp, StdHost};
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest};
use marqdo_host::plugin::{sha256_file, HostTarget, PluginManifest};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{Host, HostOp};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
@@ -11,9 +11,9 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{
sha256_file, ErrorKind, HostTarget, LoadedPlugin, PluginManifest, Value, WireRequest,
};
use marqdo_host::plugin::{sha256_file, HostTarget, LoadedPlugin, PluginManifest};
use marqdo_plugin_abi::{ErrorKind, WireRequest};
use marqdo_value::Value;
static TEMP_COUNTER: AtomicU32 = AtomicU32::new(0);
+3 -3
View File
@@ -8,10 +8,10 @@ use std::cell::RefCell;
use std::rc::Rc;
use marqdo_host::{
encode_value, Capabilities, ExecutionContext, FrameId, Host, ObservationConfig,
ObservationError, ObservationEvent, ObservationSink, ParameterSource, RuntimeObservation,
StdHost, ValueState,
encode_value, Capabilities, ObservationConfig, ObservationError, ObservationEvent,
ObservationSink, StdHost, ValueState,
};
use marqdo_host_contract::{ExecutionContext, FrameId, Host, ParameterSource, RuntimeObservation};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
+3 -2
View File
@@ -6,8 +6,9 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_host::{Capabilities, Host, HostOp, StdHost};
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest};
use marqdo_host::plugin::{sha256_file, HostTarget, PluginManifest};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{Host, HostOp};
use marqdo_sandbox::SandboxMode;
use marqdo_value::Value;
+4 -3
View File
@@ -2,7 +2,8 @@
use std::path::Path;
use marqdo_host::{Capabilities, ExecutionContext, Host, HostOp, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{ExecutionContext, Host, HostOp};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
@@ -325,12 +326,12 @@ impl marqdo_host::ResourceProvider for MockProvider {
token: u64,
max_bytes: usize,
_span: Option<marqdo_span::Span>,
) -> Result<marqdo_host::ResourceRead, marqdo_value::RuntimeError> {
) -> Result<marqdo_host_contract::ResourceRead, marqdo_value::RuntimeError> {
assert_eq!(token, 7);
let start = self.position;
let end = start.saturating_add(max_bytes).min(self.data.len());
self.position = end;
Ok(marqdo_host::ResourceRead {
Ok(marqdo_host_contract::ResourceRead {
bytes: self.data[start..end].to_vec(),
eof: end >= self.data.len(),
})
+4 -3
View File
@@ -1,9 +1,10 @@
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_sandbox::SandboxMode;
use marqdo_value::ErrorCategory;
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
fn context() -> marqdo_host_contract::ExecutionContext {
marqdo_host_contract::ExecutionContext::new("test".to_string(), None)
}
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
+1 -7
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-plugin-abi"
description = "Versioned C ABI v1 bindings, manifest validation and artifact loading"
description = "Public plugin ABI v1 contract: C layout, wire envelope and protocol errors"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
@@ -9,13 +9,7 @@ repository.workspace = true
authors.workspace = true
[dependencies]
marqdo-span = { workspace = true }
marqdo-value = { workspace = true }
marqdo-worker-ipc = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serde_yaml = { workspace = true }
thiserror = { workspace = true }
libloading = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
+7 -2
View File
@@ -255,12 +255,17 @@ pub struct MqCallContext {
impl MqCallContext {
/// Mint a context for a host invocation.
pub(crate) fn new(host_data: *mut c_void) -> Self {
///
/// Host-side execution API: the native host owns the invocation lifetime
/// and passes an opaque pointer the plugin never dereferences.
pub fn new(host_data: *mut c_void) -> Self {
Self { host_data }
}
/// Opaque host data pointer carried by this context.
pub(crate) fn host_data(&self) -> *mut c_void {
///
/// Host-side execution API; not part of the C layout exposed to plugins.
pub fn host_data(&self) -> *mut c_void {
self.host_data
}
}
+13 -30
View File
@@ -1,31 +1,23 @@
//! Versioned plugin C ABI v1 bindings, manifest validation and artifact
//! loading (host side).
//! Public contract for the versioned plugin C ABI v1.
//!
//! This crate is the host-side counterpart of
//! `include/marqdo_plugin_abi_v1.h` (the frozen C ABI) and of the
//! `marqdo-plugin-sdk` crate (the plugin-developer side). It implements the
//! blueprint section 10 contract:
//! This crate is the single normative Rust side of
//! `include/marqdo_plugin_abi_v1.h`: the stable `#[repr(C)]` types with layout
//! assertions and major/minor negotiation ([`abi`]), the `wire_version` 1
//! JSON request/response envelope with typed value tags ([`wire`]), and the
//! structured protocol [`PluginError`].
//!
//! - stable `#[repr(C)]` Rust mirrors of the C types, with compile-time layout
//! assertions and major/minor negotiation ([`abi`]),
//! - `plugin.yaml` parsing and validation ([`manifest`]),
//! - target-triple artifact selection and sha256 verification ([`artifact`]),
//! - `wire_version` 1 JSON request/response envelopes with typed value tags
//! ([`wire`]),
//! - a native loader/invocation bridge built on `libloading` ([`loader`]),
//! - structured, serializable [`PluginError`]s ([`error`]).
//! It is a contract crate, not a loader. Native loading (`dlopen`), artifact
//! selection on disk, manifest file validation, worker process management and
//! capability dispatch live in the native host (`marqdo-host::plugin`). The
//! SDK consumes only this crate. There is no second wire encoding here: the
//! wire envelope reuses the single [`marqdo_value`] encoding.
//!
//! A C ABI is not a sandbox: native plugins run in-process and require an
//! explicit trust decision. This crate only validates and loads what the
//! caller already decided to trust; it never grants capabilities.
//! A C ABI is not a sandbox. A host that loads native code must separately make
//! and enforce an explicit trust decision; this crate grants no capability.
pub mod abi;
pub mod artifact;
pub mod error;
pub mod loader;
pub mod manifest;
pub mod wire;
pub mod worker;
pub use abi::result as result_code;
pub use abi::{
@@ -33,16 +25,7 @@ pub use abi::{
MqOwnedBytes, MqPluginApi, MqPluginEntryV1, MqPluginInvoke, MqRegisterFunctionFn,
MqRequestCapabilityFn, PluginMetadata, ABI_MAJOR, ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL,
};
pub use artifact::{
current_target_triple, is_valid_sha256_hex, sha256_bytes, sha256_file, verify_sha256_file,
HostTarget, TargetTriple,
};
pub use error::{ErrorKind, PluginError};
pub use loader::{CapabilityHandler, LoadOptions, LoadedPlugin, RegisteredExport};
pub use manifest::{
AbiRequirement, Artifact, Export, PackageVersion, PluginInfo, PluginKind, PluginManifest,
KNOWN_CAPABILITIES,
};
pub use marqdo_value::Value;
pub use wire::{
bool_from_value, int_from_value, text_from_value, to_wire_json, WireContext, WireErrorBody,
+1
View File
@@ -15,6 +15,7 @@ serde_json = { workspace = true }
marqdo-worker-ipc = { workspace = true }
[dev-dependencies]
marqdo-host-contract = { workspace = true }
marqdo-host = { path = "../marqdo-host" }
marqdo-sandbox = { path = "../marqdo-sandbox" }
marqdo-value = { path = "../marqdo-value" }
@@ -3,12 +3,13 @@
use std::path::Path;
use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{ExecutionContext, Host};
use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value};
fn context() -> marqdo_host::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None)
fn context() -> ExecutionContext {
ExecutionContext::new("test".to_string(), None)
}
fn handle(value: Value) -> marqdo_value::ResourceHandle {
+2 -1
View File
@@ -13,7 +13,7 @@ marqdo-span = { workspace = true }
marqdo-value = { workspace = true }
marqdo-ir = { workspace = true }
marqdo-expression = { workspace = true }
marqdo-host = { workspace = true }
marqdo-host-contract = { workspace = true }
num-bigint = { workspace = true }
num-rational = { workspace = true }
num-traits = { workspace = true }
@@ -21,6 +21,7 @@ thiserror = { workspace = true }
[dev-dependencies]
marqdo-host = { workspace = true }
marqdo-frontend = { workspace = true }
marqdo-sandbox = { workspace = true }
tempfile = { workspace = true }
+1 -1
View File
@@ -6,7 +6,7 @@
use std::collections::BTreeMap;
use marqdo_host::{HostOp, ResourceRead};
use marqdo_host_contract::{HostOp, ResourceRead};
use marqdo_ir::builtins::Builtin;
use marqdo_ir::Resource;
use marqdo_span::Span;
+1 -1
View File
@@ -3,7 +3,7 @@
use std::collections::BTreeMap;
use marqdo_expression::{BinaryOp, Expr, RecordEntry};
use marqdo_host::{
use marqdo_host_contract::{
ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead,
RuntimeObservation,
};
+1 -1
View File
@@ -3,7 +3,7 @@
//! The interpreter is Marqdo's own execution engine: expressions, scoping,
//! calls, branches, loops and returns are evaluated here, never by translating
//! to Python or another language. Every side effect goes through
//! [`marqdo_host::Host`]; prose never reaches this layer because it is absent
//! [`marqdo_host_contract::Host`]; prose never reaches this layer because it is absent
//! from the IR.
mod builtins_impl;
+2 -1
View File
@@ -1,6 +1,7 @@
//! End-to-end interpreter tests: Markdown source → frontend IR → execution.
use marqdo_host::{Capabilities, Host, StdHost};
use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_ir::{ModuleId, Program};
use marqdo_runtime::{run, run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
use marqdo_sandbox::SandboxMode;
+3 -2
View File
@@ -8,9 +8,10 @@ use std::cell::RefCell;
use std::rc::Rc;
use marqdo_host::{
Capabilities, ObservationConfig, ObservationError, ObservationEvent, ObservationSink,
ParameterSource, StdHost, ValueState,
Capabilities, ObservationConfig, ObservationError, ObservationEvent, ObservationSink, StdHost,
ValueState,
};
use marqdo_host_contract::ParameterSource;
use marqdo_ir::{ModuleId, Program};
use marqdo_runtime::run;
use marqdo_sandbox::SandboxMode;