From 98d256f5a2f535eb98d0979a4607d4562bb63a97 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 21:21:41 +0800 Subject: [PATCH] refactor: keep the plugin SDK in the CLI workspace (revert split) The pre-stable line prioritizes atomic ABI/header/spec/SDK/loader changes over a premature repository boundary. ADR-0073 supersedes ADR-0072: - restore crates/marqdo-plugin-sdk as a contract-only CLI workspace crate (marqdo-plugin-abi + serde; no loader/host/worker dependency); - restore tests/sdk-plugin and tools/ci/check_plugin_sdk.py, including the real CLI invocation and tampered-digest negative case; - restore workspace/lock/architecture/dependency/docs/CI references; the SDK is a reviewed workspace member again and must not become a remote repo, mirror or submodule in this stage; - ADR-0072 and the old issue #15 evidence are marked superseded; ADR-0073 and the split-revert evidence record the decision and the deleted remote repo; - logical ADR-0071 boundaries are unchanged. Workspace: 636 passed / 0 failed / 2 ignored; fmt, clippy, docs, architecture, dependency, SDK gate and engine differential all PASS. Refs #13, #15 --- .github/workflows/ci.yml | 2 + .woodpecker/main.yml | 1 + AGENTS.md | 6 +- Cargo.lock | 9 + Cargo.toml | 1 + README.md | 4 +- crates/cli/tests/architecture_boundaries.rs | 28 +- crates/marqdo-plugin-sdk/Cargo.toml | 14 + crates/marqdo-plugin-sdk/src/bytes.rs | 156 +++++++++++ crates/marqdo-plugin-sdk/src/call.rs | 115 ++++++++ crates/marqdo-plugin-sdk/src/entry.rs | 199 ++++++++++++++ crates/marqdo-plugin-sdk/src/lib.rs | 143 ++++++++++ crates/marqdo-plugin-sdk/src/tests.rs | 245 ++++++++++++++++++ crates/marqdo-plugin-sdk/src/wire.rs | 98 +++++++ docs/STATUS.md | 47 ++-- .../adr/0071-engine-host-contract-boundary.md | 12 +- docs/adr/0072-sdk-independent-repository.md | 4 +- docs/adr/0073-sdk-stays-in-cli-workspace.md | 99 +++++++ docs/adr/README.md | 6 +- docs/architecture/CURRENT.md | 21 +- docs/architecture/README.md | 5 +- docs/ci.md | 1 + docs/developers/README.md | 4 +- ...026-11-26-issue-13-engine-host-boundary.md | 2 +- ...-26-issue-15-sdk-independent-repository.md | 6 + .../2026-11-26-issue-15-sdk-split-reverted.md | 61 +++++ tests/README.md | 2 + tests/sdk-plugin/Cargo.lock | 198 ++++++++++++++ tests/sdk-plugin/Cargo.toml | 16 ++ tests/sdk-plugin/call.mq.md | 5 + tests/sdk-plugin/src/lib.rs | 33 +++ tools/ci/check_dependency_boundaries.py | 25 +- tools/ci/check_plugin_sdk.py | 164 ++++++++++++ tools/ci/test_dependency_boundaries.py | 14 +- 34 files changed, 1661 insertions(+), 85 deletions(-) create mode 100644 crates/marqdo-plugin-sdk/Cargo.toml create mode 100644 crates/marqdo-plugin-sdk/src/bytes.rs create mode 100644 crates/marqdo-plugin-sdk/src/call.rs create mode 100644 crates/marqdo-plugin-sdk/src/entry.rs create mode 100644 crates/marqdo-plugin-sdk/src/lib.rs create mode 100644 crates/marqdo-plugin-sdk/src/tests.rs create mode 100644 crates/marqdo-plugin-sdk/src/wire.rs create mode 100644 docs/adr/0073-sdk-stays-in-cli-workspace.md create mode 100644 docs/evidence/2026-11-26-issue-15-sdk-split-reverted.md create mode 100644 tests/sdk-plugin/Cargo.lock create mode 100644 tests/sdk-plugin/Cargo.toml create mode 100644 tests/sdk-plugin/call.mq.md create mode 100644 tests/sdk-plugin/src/lib.rs create mode 100644 tools/ci/check_plugin_sdk.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 46c5990..51fbe50 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,8 @@ jobs: run: python3 tools/ci/check_dependency_boundaries.py - name: Engine independence and CLI differential execution run: python3 tools/ci/check_engine_boundary.py + - name: Plugin SDK real consumption + run: python3 tools/ci/check_plugin_sdk.py - name: CI evidence tool tests run: python3 -m unittest discover -s tools/ci -p "test_*.py" - name: Whole stdlib product tests diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index 9860b0f..18d6948 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -50,6 +50,7 @@ steps: - cargo test -p marqdo-cli --test architecture_boundaries - python3 tools/ci/check_dependency_boundaries.py - python3 tools/ci/check_engine_boundary.py + - python3 tools/ci/check_plugin_sdk.py - python3 -m unittest discover -s tools/ci -p "test_*.py" - cargo test -p marqdo-cli --test stdlib_product # Windows compile gate: runtime lanes are native on GitHub; this catches diff --git a/AGENTS.md b/AGENTS.md index 2d113ea..901ac28 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,8 +34,8 @@ correctness and release evidence before expanding the surface. 9. Side effects go through `CapabilityHost`; do not invent host bypasses for tests, plugins, math or foreign kernels. `check` and `inspect` cannot execute untrusted project code. 10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates. 11. RFC-LANG-0002 is implemented by the frontend, `marqdo-expression`, IR lowering, runtime and the bundled stdlib. Keep `spec/`, implementation, fixtures, stdlib digest and docs in lockstep; there is no legacy mapper or per-file syntax switch to fall back to. Do not make a release claim beyond the evidence recorded in `docs/STATUS.md`. -12. The language engine depends on the neutral `marqdo-host-contract` only; it must never link `marqdo-host`, the sandbox, foreign kernels, the plugin loader/worker, package or CLI in normal/build dependencies. `marqdo-host-contract` depends on `Value`/`Span` only. The native host implements the contract and must not depend back on the runtime/frontend/IR. The plugin ABI crate is a contract (no `dlopen`/worker/manifest execution); the standalone public SDK repository `cflmy/marqdo-plugin-sdk` consumes one pinned CLI contract revision and the CLI must not depend on it (ADR-0072). CLI is the one assembly point. This is enforced by `tools/ci/check_dependency_boundaries.py`, `tools/ci/check_engine_boundary.py` and `crates/cli/tests/architecture_boundaries.rs`; see ADR-0071/ADR-0072. -13. Do not create empty candidate repositories (for example `marqdo-engine`/`marqdo-host`/`marqdo-cli-*`) to "solve" architecture. A repository split requires a separate accepted ADR with ownership/release evidence; "keep in workspace" is a valid recorded decision. The only split approved so far is the independent public SDK (ADR-0072); the SDK is pinned to a CLI contract `rev` and must not return as a workspace member or copied source. Do not add a second Host trait, Value encoding, wire/RPC engine protocol or compatibility re-export path. +12. The language engine depends on the neutral `marqdo-host-contract` only; it must never link `marqdo-host`, the sandbox, foreign kernels, the plugin loader/worker, package or CLI in normal/build dependencies. `marqdo-host-contract` depends on `Value`/`Span` only. The native host implements the contract and must not depend back on the runtime/frontend/IR. The plugin ABI crate is a contract (no `dlopen`/worker/manifest execution); the SDK consumes the contract only. CLI is the one assembly point. This is enforced by `tools/ci/check_dependency_boundaries.py`, `tools/ci/check_engine_boundary.py`, `tools/ci/check_plugin_sdk.py` and `crates/cli/tests/architecture_boundaries.rs`; see ADR-0071. +13. Do not create empty candidate repositories (for example `marqdo-engine`/`marqdo-host`/`marqdo-cli-*`) to "solve" architecture. A repository split requires the issue #13 §9.2 evidence and a separate accepted ADR; "keep in workspace" is a valid recorded decision. The plugin SDK stays in this CLI workspace as a contract-only crate (ADR-0073); do not re-create an independent SDK repository, mirror or submodule for the pre-stable line. Do not add a second Host trait, Value encoding, wire/RPC engine protocol or compatibility re-export path. ## Pre-stable protocol changes @@ -54,7 +54,7 @@ closing a protocol replacement issue. 2. Update the normative spec **in place** first; there is never a second active syntax spec. 3. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST, execution IR and diagnostics. 4. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, expression parser, runtime and host separated. -5. Run formatting, clippy, unit tests, golden tests, the architecture/dependency gates and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`, `python3 tools/ci/check_dependency_boundaries.py`, `python3 tools/ci/check_engine_boundary.py`). +5. Run formatting, clippy, unit tests, golden tests, the architecture/dependency gates and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`, `python3 tools/ci/check_dependency_boundaries.py`, `python3 tools/ci/check_engine_boundary.py`, `python3 tools/ci/check_plugin_sdk.py`). 6. Write the tradeoff and state of completion in the PR. Never say a feature is finished because a design example looks executable. Update `spec/` and `docs/STATUS.md` when behavior or status changes; the docs describe what the code does and flag divergences explicitly. ## Unresolved design topics diff --git a/Cargo.lock b/Cargo.lock index 74d182e..8c4b141 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -561,6 +561,15 @@ dependencies = [ "thiserror", ] +[[package]] +name = "marqdo-plugin-sdk" +version = "3.0.0-rc.4" +dependencies = [ + "marqdo-plugin-abi", + "serde", + "serde_json", +] + [[package]] name = "marqdo-provider-worker" version = "3.0.0-rc.4" diff --git a/Cargo.toml b/Cargo.toml index eb42f4a..6e49e37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ members = [ "crates/marqdo-plugin-abi", "crates/marqdo-provider-worker", "crates/marqdo-worker-ipc", + "crates/marqdo-plugin-sdk", "crates/marqdo-host", "crates/marqdo-host-contract", "crates/marqdo-runtime", diff --git a/README.md b/README.md index d84673c..c8dfbbe 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ CI: the source of truth is the Gitea remote [git.cflmy.cn/cflmy/marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) with Woodpecker at [ci.cflmy.cn](https://ci.cflmy.cn); [`.woodpecker/main.yml`](.woodpecker/main.yml) runs fmt, clippy, workspace tests with `--locked`, the dependency-direction and -engine-independence gates, the Windows +engine-independence gates, the plugin SDK consumption gate, the Windows cross-target compile gate and a release build of both binaries. The strict OS-isolation lane requires the disposable VM described in [docs/ci.md](docs/ci.md); a GitHub mirror is not used as the authoritative lane for this beta. @@ -297,7 +297,7 @@ crates/marqdo-foreign Python/Node one-shot kernel supervisor crates/marqdo-sandbox mode parsing + platform isolation detection crates/marqdo-host-contract neutral Host trait, HostOp, context and runtime facts crates/marqdo-plugin-abi public C ABI v1 contract: layout, wire envelope, errors - (the Rust SDK lives in cflmy/marqdo-plugin-sdk) +crates/marqdo-plugin-sdk Rust plugin SDK and entry macro (contract-only) crates/marqdo-host Native Host: capability, resources, OS, plugin loader/worker crates/marqdo-runtime tree-walk interpreter (depends only on the neutral contract) crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery diff --git a/crates/cli/tests/architecture_boundaries.rs b/crates/cli/tests/architecture_boundaries.rs index 2431680..c9c3002 100644 --- a/crates/cli/tests/architecture_boundaries.rs +++ b/crates/cli/tests/architecture_boundaries.rs @@ -687,22 +687,18 @@ fn plugin_contract_carries_no_native_execution() { "native host must own plugin `{module}`" ); } - // ADR-0072: the SDK is an independent repository pinned to a contract - // revision. It must not be reintroduced as a second in-workspace copy. - assert!( - !root.join("crates/marqdo-plugin-sdk").exists(), - "the plugin SDK moved to cflmy/marqdo-plugin-sdk (ADR-0072)" - ); - let manifest = read(&root.join("Cargo.toml")); - assert!( - !manifest.contains("marqdo-plugin-sdk"), - "the plugin SDK must not return as a CLI workspace member" - ); - let current = read(&root.join("docs/architecture/CURRENT.md")); - assert!( - current.contains("cflmy/marqdo-plugin-sdk") && current.contains("ADR-0072"), - "CURRENT.md must name the independent SDK repository decision" - ); + 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 diff --git a/crates/marqdo-plugin-sdk/Cargo.toml b/crates/marqdo-plugin-sdk/Cargo.toml new file mode 100644 index 0000000..c971ca4 --- /dev/null +++ b/crates/marqdo-plugin-sdk/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "marqdo-plugin-sdk" +description = "Rust SDK for writing Marqdo plugins against ABI v1" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true + +[dependencies] +marqdo-plugin-abi = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/marqdo-plugin-sdk/src/bytes.rs b/crates/marqdo-plugin-sdk/src/bytes.rs new file mode 100644 index 0000000..90b3a4f --- /dev/null +++ b/crates/marqdo-plugin-sdk/src/bytes.rs @@ -0,0 +1,156 @@ +//! Safe wrappers around the raw `MqBytes` / `MqOwnedBytes` ABI buffers. +//! +//! Ownership rules (see the canonical header): +//! - [`BytesRef`] is a borrowed, validated view of host input; it is only +//! valid for the call that produced it. +//! - [`HostBuffer`] is plugin output allocated with the host allocator and +//! handed back to the host, which frees it after copying. + +use std::ffi::c_void; +use std::marker::PhantomData; +use std::ptr; + +use marqdo_plugin_abi::abi::{MqBytes, MqHostApi, MqOwnedBytes}; + +use crate::PluginError; + +/// Validated borrowed view of an ABI byte buffer (`MqBytes`). +pub struct BytesRef<'a> { + raw: MqBytes, + _marker: PhantomData<&'a [u8]>, +} + +impl<'a> BytesRef<'a> { + /// Validate a raw borrowed buffer. + /// + /// # Safety + /// + /// If `raw.len > 0`, `raw.data` must point to `raw.len` initialized bytes + /// that stay alive for `'a`. Within the ABI, `'a` must not outlive the + /// call that produced the buffer. + pub unsafe fn from_raw(raw: MqBytes) -> Result { + raw.validate()?; + Ok(Self { + raw, + _marker: PhantomData, + }) + } + + /// The underlying raw ABI view. + pub fn as_raw(&self) -> MqBytes { + self.raw + } + + /// The bytes as a slice (valid for `'a`). + pub fn as_slice(&self) -> &'a [u8] { + if self.raw.len == 0 { + return &[]; + } + // SAFETY: `from_raw` validated the pointer/length pair and `'a` is + // tied to the caller's borrow guarantee. + unsafe { std::slice::from_raw_parts(self.raw.data, self.raw.len) } + } + + /// Length in bytes. + pub fn len(&self) -> usize { + self.raw.len + } + + /// Whether the buffer is empty. + pub fn is_empty(&self) -> bool { + self.raw.len == 0 + } +} + +/// A byte buffer allocated with the host allocator and owned by the host. +/// +/// The plugin writes its response/error wire into a [`HostBuffer`] and +/// transfers ownership through the ABI output parameter. The plugin must +/// never free this buffer itself; the host frees it after copying. +pub struct HostBuffer { + raw: MqOwnedBytes, +} + +impl HostBuffer { + /// The empty buffer `{NULL, 0}`. + pub fn empty() -> Self { + Self { + raw: MqOwnedBytes::EMPTY, + } + } + + /// Allocate a host buffer and copy `bytes` into it. + /// + /// `host` must be the host API table provided to the entry point (the SDK + /// stores it for the plugin lifetime). Returns an out-of-memory error if + /// the host allocator returns NULL. + pub fn copy_from(host: &MqHostApi, bytes: &[u8]) -> Result { + if bytes.is_empty() { + return Ok(Self::empty()); + } + // SAFETY: host alloc/free pointers are non-NULL and valid for the + // plugin lifetime (validated during the entry call). + let pointer = unsafe { (host.alloc)(host.host_data, bytes.len()) }; + if pointer.is_null() { + return Err(PluginError::invoke( + "out_of_memory", + "host allocator returned NULL for a plugin output buffer", + )); + } + // SAFETY: pointer has bytes.len() writable bytes and does not overlap + // the source slice. + unsafe { + ptr::copy_nonoverlapping(bytes.as_ptr(), pointer as *mut u8, bytes.len()); + } + Ok(Self { + raw: MqOwnedBytes::new(pointer as *mut u8, bytes.len()), + }) + } + + /// The raw owner-transfer buffer. + pub fn into_raw(self) -> MqOwnedBytes { + self.raw + } + + /// Length in bytes. + pub fn len(&self) -> usize { + self.raw.len + } + + /// Whether the buffer is empty. + pub fn is_empty(&self) -> bool { + self.raw.len == 0 + } +} + +/// Borrowed view of a capability reply or other host-allocated buffer. +/// +/// The plugin copies what it needs and then must release the buffer with the +/// host allocator; use [`release_host_buffer`]. +/// +/// # Safety +/// +/// `buffer` must be a host-allocated buffer that is still alive; the returned +/// slice must not outlive the release of that buffer. +pub unsafe fn reply_slice<'a>(buffer: MqOwnedBytes) -> &'a [u8] { + if buffer.len == 0 { + return &[]; + } + // SAFETY: host-allocated buffer is initialized for `buffer.len` bytes; the + // caller must not retain the slice beyond the release point. + unsafe { std::slice::from_raw_parts(buffer.data, buffer.len) } +} + +/// Release a host-allocated buffer through the host allocator. +/// +/// # Safety +/// +/// `buffer.data` must be NULL or a pointer returned by the host allocator +/// (`MqHostApi::alloc`) that has not been freed yet. +pub unsafe fn release_host_buffer(host: &MqHostApi, buffer: MqOwnedBytes) { + if buffer.data.is_null() { + return; + } + // SAFETY: alloc/free pair and non-NULL pointer per the caller contract. + unsafe { (host.free)(host.host_data, buffer.data as *mut c_void) }; +} diff --git a/crates/marqdo-plugin-sdk/src/call.rs b/crates/marqdo-plugin-sdk/src/call.rs new file mode 100644 index 0000000..a484e91 --- /dev/null +++ b/crates/marqdo-plugin-sdk/src/call.rs @@ -0,0 +1,115 @@ +//! Per-invocation context passed to plugin handlers. +//! +//! The context is valid only for the duration of one invocation. It exists to +//! carry host capabilities into the plugin: capability requests are answered +//! by the host's authorization layer and can never be escalated by plugin +//! code. Do not cache this value, its raw pointer or any capability token. + +use marqdo_plugin_abi::abi::{ + MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MAX_CAPABILITY_REPLY_BYTES, +}; +use marqdo_plugin_abi::PluginError; + +use crate::bytes; + +/// Context for one plugin invocation. +pub struct CallContext { + raw: *mut MqCallContext, + host: &'static MqHostApi, +} + +impl CallContext { + /// Wrap the host-provided context pointer. + /// + /// # Safety + /// + /// `raw` must be the context pointer provided by the host for the current + /// invocation, and `host` must be the validated host API table. + pub(crate) unsafe fn new(raw: *mut MqCallContext, host: &'static MqHostApi) -> Self { + Self { raw, host } + } + + /// The host API table of this plugin instance. + pub fn host(&self) -> &'static MqHostApi { + self.host + } + + /// Request an already-authorized host capability for this call. + /// + /// `request` is a UTF-8 JSON capability request; the reply is opaque bytes + /// owned by the host. The SDK copies the reply and releases the host buffer. + pub fn capability_request( + &mut self, + name: &str, + request: &[u8], + ) -> Result, PluginError> { + if self.raw.is_null() { + return Err(PluginError::capability( + "missing_call_context", + "capability request requires an active invocation context", + )); + } + let mut reply = MqOwnedBytes::EMPTY; + // SAFETY: raw context and host table are valid for this invocation. + let code = unsafe { + (self.host.request_capability)( + self.raw, + MqBytes::from_slice(name.as_bytes()), + MqBytes::from_slice(request), + &mut reply, + ) + }; + // SAFETY: host-allocated reply is initialized for `reply.len` bytes. + let reply_bytes = unsafe { reply.to_vec() }; + // SAFETY: the host allocated `reply` with its allocator for us; release + // it exactly once after copying. + unsafe { bytes::release_host_buffer(self.host, reply) }; + let reply_bytes = reply_bytes.map_err(|error| { + PluginError::capability( + "invalid_capability_reply", + "host capability reply violates the buffer contract", + ) + .with_detail(error.to_string()) + })?; + if reply_bytes.len() > MAX_CAPABILITY_REPLY_BYTES { + return Err(PluginError::capability( + "capability_reply_too_large", + format!( + "capability reply is {} bytes, limit is {MAX_CAPABILITY_REPLY_BYTES}", + reply_bytes.len() + ), + )); + } + if code != crate::result_code::OK { + return Err(PluginError::capability( + "capability_request_failed", + format!("host rejected capability request `{name}`"), + ) + .with_detail(format!( + "result code `{}` ({code})", + crate::result_code::name(code) + ))); + } + Ok(reply_bytes) + } + + /// Best-effort structured log through the `log` capability. + pub fn log(&mut self, level: &str, message: &str) -> Result<(), PluginError> { + let request = serde_json::json!({"level": level, "message": message}); + let request = serde_json::to_vec(&request).map_err(|error| { + PluginError::capability("log_encode_failed", "could not encode log request") + .with_detail(error.to_string()) + })?; + let _ = self.capability_request("log", &request)?; + Ok(()) + } +} + +impl std::fmt::Debug for CallContext { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CallContext") + .field("raw", &self.raw) + .field("host", &(self.host as *const MqHostApi)) + .finish() + } +} diff --git a/crates/marqdo-plugin-sdk/src/entry.rs b/crates/marqdo-plugin-sdk/src/entry.rs new file mode 100644 index 0000000..84743e5 --- /dev/null +++ b/crates/marqdo-plugin-sdk/src/entry.rs @@ -0,0 +1,199 @@ +//! Entry-point plumbing used by [`mq_plugin_entry!`](crate::mq_plugin_entry). +//! +//! These functions are the "runtime" of the SDK macro. They are public so the +//! macro can reference them through `$crate` from a plugin crate, but they are +//! not intended for direct use. + +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::{AtomicPtr, Ordering}; + +use marqdo_plugin_abi::abi::{ + check_host_api, result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, + MqPluginInvoke, ABI_MAJOR, ABI_MINOR, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES, + MAX_RESULT_WIRE_BYTES, +}; +use marqdo_plugin_abi::{PluginError, WireResponse}; + +use crate::bytes::{release_host_buffer, HostBuffer}; +use crate::call::CallContext; +use crate::HandlerFn; + +/// Host API table captured by the entry point for the plugin lifetime. +static CURRENT_HOST: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); + +/// The host API table captured at load time, if a plugin is loaded. +pub(crate) fn current_host() -> Option<&'static MqHostApi> { + let pointer = CURRENT_HOST.load(Ordering::SeqCst); + if pointer.is_null() { + return None; + } + // SAFETY: the pointer was stored from a validated host table and the host + // guarantees it is valid for the plugin lifetime (single-threaded model). + Some(unsafe { &*pointer }) +} + +/// Initialize the ABI tables for the generated entry point. +/// +/// # Safety +/// +/// `host` and `plugin` must be the pointers provided by the host to +/// `mq_plugin_entry_v1` and must satisfy the header contract. +pub unsafe fn initialize( + host: *const MqHostApi, + plugin: *mut MqPluginApi, + metadata: &'static [u8], +) -> i32 { + if plugin.is_null() { + return result::INVALID_ARGUMENT; + } + // SAFETY: host pointer comes from the host and is checked before use. + let negotiated = match unsafe { check_host_api(host) } { + Ok(version) => version, + Err(_) => return result::ABI_MISMATCH, + }; + if negotiated.major != ABI_MAJOR { + return result::ABI_MISMATCH; + } + CURRENT_HOST.store(host as *mut MqHostApi, Ordering::SeqCst); + // SAFETY: plugin table is host-provided, writable and valid for this call. + unsafe { + (*plugin).struct_size = std::mem::size_of::() as u32; + (*plugin).abi_major = ABI_MAJOR; + (*plugin).abi_minor = ABI_MINOR; + (*plugin).plugin_metadata_wire = MqBytes::from_slice(metadata); + } + result::OK +} + +/// Register one export through the host table. +/// +/// # Safety +/// +/// `host` must be the table validated by [`initialize`]; both strings must be +/// valid UTF-8 dotted export names/signatures declared in `plugin.yaml`. +pub unsafe fn register_export( + host: *const MqHostApi, + name: &str, + signature: &str, + invoke: MqPluginInvoke, +) -> i32 { + if host.is_null() || name.is_empty() || name.len() > MAX_EXPORT_NAME_BYTES { + return result::INVALID_ARGUMENT; + } + // SAFETY: host pointer is non-NULL and valid for the plugin lifetime. + let host = unsafe { &*host }; + let signature_wire = match serde_json::to_vec(&serde_json::json!({"signature": signature})) { + Ok(bytes) => bytes, + Err(_) => return result::BAD_WIRE, + }; + // SAFETY: host table was validated; strings outlive the call. + unsafe { + (host.register_function)( + host.host_data, + MqBytes::from_slice(name.as_bytes()), + MqBytes::from_slice(&signature_wire), + invoke, + ) + } +} + +/// Dispatch one invocation to a plugin handler and write the response. +/// +/// # Safety +/// +/// Must be called as the body of a `MqPluginInvoke` callback with the buffers +/// provided by the host for that invocation. +pub unsafe fn dispatch( + handler: HandlerFn, + ctx: *mut MqCallContext, + args: MqBytes, + result_out: *mut MqOwnedBytes, + error_out: *mut MqOwnedBytes, +) -> i32 { + if result_out.is_null() || error_out.is_null() { + return result::INVALID_ARGUMENT; + } + // SAFETY: output pointers are non-NULL host-provided out-parameters. + unsafe { + *result_out = MqOwnedBytes::EMPTY; + *error_out = MqOwnedBytes::EMPTY; + } + let Some(host) = current_host() else { + return result::INTERNAL; + }; + // SAFETY: borrowed request buffer is valid for this callback. + let args_bytes = match unsafe { args.as_slice() } { + Ok(bytes) => bytes.to_vec(), + Err(_) => return result::INVALID_ARGUMENT, + }; + + // SAFETY: context pointer is the host-minted context for this invocation. + let mut context = unsafe { CallContext::new(ctx, host) }; + let outcome = catch_unwind(AssertUnwindSafe(|| handler(&mut context, &args_bytes))); + let response = match outcome { + Ok(Ok(bytes)) => Ok(bytes), + Ok(Err(error)) => Err(error), + Err(_) => Err(PluginError::invoke( + "plugin_panic", + "plugin handler panicked; the panic was caught at the ABI boundary", + )), + }; + + match response { + Ok(bytes) => { + if bytes.len() > MAX_RESULT_WIRE_BYTES { + return write_error( + host, + error_out, + &PluginError::wire( + "result_too_large", + format!( + "plugin result is {} bytes, limit is {MAX_RESULT_WIRE_BYTES}", + bytes.len() + ), + ), + ); + } + match HostBuffer::copy_from(host, &bytes) { + Ok(buffer) => { + // SAFETY: result_out is a valid out-parameter. + unsafe { *result_out = buffer.into_raw() }; + result::OK + } + Err(error) => write_error(host, error_out, &error), + } + } + Err(error) => write_error(host, error_out, &error), + } +} + +fn write_error(host: &'static MqHostApi, error_out: *mut MqOwnedBytes, error: &PluginError) -> i32 { + let encoded = match WireResponse::from_error(error).to_json_bytes() { + Ok(bytes) if bytes.len() <= MAX_ERROR_WIRE_BYTES => bytes, + _ => br#"{"wire_version":1,"kind":"response","error":{"kind":"invoke","code":"plugin_error","message":"plugin failed with an unencodable error"}}"#.to_vec(), + }; + let code = match error.kind { + marqdo_plugin_abi::ErrorKind::Wire => result::BAD_WIRE, + marqdo_plugin_abi::ErrorKind::Capability => result::CAPABILITY, + marqdo_plugin_abi::ErrorKind::Unsupported => result::UNSUPPORTED, + _ => result::INTERNAL, + }; + match HostBuffer::copy_from(host, &encoded) { + Ok(buffer) => { + // SAFETY: error_out is a valid out-parameter. + unsafe { *error_out = buffer.into_raw() }; + code + } + Err(_) => result::OUT_OF_MEMORY, + } +} + +/// Free a host-owned buffer (used by generated code/tests). +/// +/// # Safety +/// +/// `buffer` must have been allocated by the host allocator and not freed yet. +pub unsafe fn free_host_buffer(host: &MqHostApi, buffer: MqOwnedBytes) { + // SAFETY: caller guarantees the alloc/free pair. + unsafe { release_host_buffer(host, buffer) }; +} diff --git a/crates/marqdo-plugin-sdk/src/lib.rs b/crates/marqdo-plugin-sdk/src/lib.rs new file mode 100644 index 0000000..5833938 --- /dev/null +++ b/crates/marqdo-plugin-sdk/src/lib.rs @@ -0,0 +1,143 @@ +//! Rust SDK for writing Marqdo native plugins against plugin ABI v1. +//! +//! The SDK is the plugin-developer side of `include/marqdo_plugin_abi_v1.h`. +//! It hides the raw C layout behind safe wrappers and provides the +//! [`mq_plugin_entry!`] macro that exports the required +//! `mq_plugin_entry_v1` symbol: +//! +//! ``` +//! use marqdo_plugin_sdk::{mq_plugin_entry, CallContext, PluginError, Value}; +//! +//! fn add(_ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { +//! let request = marqdo_plugin_sdk::wire::decode_request(args)?; +//! let values = request.typed_args()?; +//! let a = marqdo_plugin_sdk::wire::int_arg(&values, "a")?; +//! let b = marqdo_plugin_sdk::wire::int_arg(&values, "b")?; +//! marqdo_plugin_sdk::wire::success(Some(Value::Int((a + b).into()))) +//! } +//! +//! mq_plugin_entry! { +//! name: "demo.solver", +//! version: "0.1.0", +//! exports: { +//! "solver.add" => "($a: Int, $b: Int) -> Int" => add, +//! } +//! } +//! ``` +//! +//! The SDK never depends on host-only crates: it only uses the shared ABI +//! types and the JSON wire envelope from `marqdo-plugin-abi`. Building a +//! plugin does not grant it any capability; authorization is a separate host +//! decision performed before loading. + +#![deny(missing_docs)] + +pub use marqdo_plugin_abi::abi::result as result_code; +pub use marqdo_plugin_abi::abi::{ + MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke, ABI_MAJOR, + ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL, +}; +pub use marqdo_plugin_abi::{PluginError, Value, WireRequest, WireResponse, WIRE_VERSION}; + +pub mod bytes; +pub mod call; +pub mod entry; +pub mod wire; + +pub use bytes::{BytesRef, HostBuffer}; +pub use call::CallContext; +pub use wire::{ + bool_arg, decode_request, error_response, int_arg, response_value, success, success_raw, + text_arg, value_arg, +}; + +/// Plugin handler signature. +/// +/// A handler receives the per-call context (for capability requests and +/// logging) and the raw request envelope bytes, and returns the raw response +/// envelope bytes on success. +/// +/// Use [`wire::decode_request`] and [`wire::success`] to build the response; +/// handlers should never panic: panics are caught by the SDK and converted +/// into a structured error, but the plugin process stays healthy only if the +/// panic does not corrupt plugin state. +pub type HandlerFn = fn(&mut CallContext, &[u8]) -> Result, PluginError>; + +/// Declare a plugin and export `mq_plugin_entry_v1`. +/// +/// ```ignore +/// marqdo_plugin_sdk::mq_plugin_entry! { +/// name: "demo.solver", +/// version: "0.1.0", +/// exports: { +/// "solver.add" => "($a: Int, $b: Int) -> Int" => add, +/// "solver.echo" => "($text: Text) -> Text" => echo, +/// } +/// } +/// ``` +/// +/// Each handler is a path (or non-capturing closure) with the [`HandlerFn`] +/// signature. The macro: +/// - validates the host ABI table (major version and `struct_size`), +/// - reports the plugin ABI version and a metadata envelope, +/// - registers every export and fails the load if registration fails. +#[macro_export] +macro_rules! mq_plugin_entry { + ( + name: $name:literal, + version: $version:literal, + exports: { + $( $export_name:literal => $signature:literal => $handler:expr ),* $(,)? + } + ) => { + /// Marqdo plugin ABI v1 entry point (generated by the SDK macro). + #[unsafe(no_mangle)] + pub unsafe extern "C" fn mq_plugin_entry_v1( + host: *const $crate::MqHostApi, + plugin: *mut $crate::MqPluginApi, + ) -> i32 { + const METADATA: &[u8] = concat!( + "{\"name\":\"", $name, "\",\"version\":\"", $version, "\"}" + ) + .as_bytes(); + let metadata: &'static [u8] = METADATA; + // SAFETY: the host provides the ABI tables per the header contract. + let init = unsafe { $crate::entry::initialize(host, plugin, metadata) }; + if init != 0 { + return init; + } + $( + { + extern "C" fn invoke( + ctx: *mut $crate::MqCallContext, + args: $crate::MqBytes, + result: *mut $crate::MqOwnedBytes, + error: *mut $crate::MqOwnedBytes, + ) -> i32 { + // Expand the user's handler expression in a safe + // context (also required by `macro_metavars_in_unsafe`). + let handler: $crate::HandlerFn = $handler; + // SAFETY: the host owns the invocation buffers; the SDK + // validates them and never retains them. + unsafe { + $crate::entry::dispatch(handler, ctx, args, result, error) + } + } + let export_name: &str = $export_name; + let signature: &str = $signature; + // SAFETY: host table is valid for the plugin lifetime and + // was validated by `initialize`. + let code = + unsafe { $crate::entry::register_export(host, export_name, signature, invoke) }; + if code != 0 { + return code; + } + } + )* + $crate::result_code::OK + } + }; +} + +#[cfg(test)] +mod tests; diff --git a/crates/marqdo-plugin-sdk/src/tests.rs b/crates/marqdo-plugin-sdk/src/tests.rs new file mode 100644 index 0000000..2483884 --- /dev/null +++ b/crates/marqdo-plugin-sdk/src/tests.rs @@ -0,0 +1,245 @@ +//! End-to-end SDK tests: run the macro-generated entry point against a tiny +//! in-process host table and invoke the registered export. + +use std::ffi::c_void; +use std::ptr; + +use marqdo_plugin_abi::abi::{ + result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke, + ABI_MAJOR, ABI_MINOR, +}; + +use crate::wire; +use crate::{CallContext, PluginError, Value, WireRequest, WireResponse}; + +/// ABI v1 is single-threaded: the generated plugin stores the host table in a +/// process-global. Serialize tests that call the entry point so they do not +/// race (the SDK's own contract, not a test-only limitation). +static ABI_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn abi_test_lock() -> std::sync::MutexGuard<'static, ()> { + ABI_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +#[derive(Default)] +struct TestHostState { + registrations: Vec<(String, String, MqPluginInvoke)>, +} + +unsafe extern "C" fn test_alloc(_host_data: *mut c_void, size: usize) -> *mut c_void { + const HEADER: usize = 16; + if size == 0 { + return ptr::null_mut(); + } + let Ok(layout) = std::alloc::Layout::from_size_align(size + HEADER, 16) else { + return ptr::null_mut(); + }; + // SAFETY: non-zero layout. + let base = unsafe { std::alloc::alloc(layout) }; + if base.is_null() { + return ptr::null_mut(); + } + // SAFETY: allocation has room for the header. + unsafe { (base as *mut usize).write(size) }; + // SAFETY: offset within the allocation. + unsafe { base.add(HEADER) as *mut c_void } +} + +unsafe extern "C" fn test_free(_host_data: *mut c_void, pointer: *mut c_void) { + const HEADER: usize = 16; + if pointer.is_null() { + return; + } + // SAFETY: only pointers from test_alloc are freed. + unsafe { + let base = (pointer as *mut u8).sub(HEADER); + let size = (base as *const usize).read(); + std::alloc::dealloc( + base, + std::alloc::Layout::from_size_align_unchecked(size + HEADER, 16), + ); + } +} + +unsafe extern "C" fn test_register( + host_data: *mut c_void, + export_name: MqBytes, + signature_wire: MqBytes, + invoke: MqPluginInvoke, +) -> i32 { + if host_data.is_null() { + return result::INVALID_ARGUMENT; + } + // SAFETY: host_data points at TestHostState for the test. + let state = unsafe { &mut *(host_data as *mut TestHostState) }; + // SAFETY: buffers are valid for this callback. + let name = match unsafe { export_name.as_slice() } { + Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(), + Err(_) => return result::INVALID_ARGUMENT, + }; + // SAFETY: buffers are valid for this callback. + let signature = match unsafe { signature_wire.as_slice() } { + Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(), + Err(_) => return result::INVALID_ARGUMENT, + }; + state.registrations.push((name, signature, invoke)); + result::OK +} + +unsafe extern "C" fn test_capability( + _ctx: *mut MqCallContext, + _name: MqBytes, + _request: MqBytes, + reply: *mut MqOwnedBytes, +) -> i32 { + if !reply.is_null() { + // SAFETY: output pointer is non-NULL. + unsafe { *reply = MqOwnedBytes::EMPTY }; + } + result::UNSUPPORTED +} + +fn add(_ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { + let request = wire::decode_request(args)?; + let values = request.typed_args()?; + let a = wire::int_arg(&values, "a")?; + let b = wire::int_arg(&values, "b")?; + wire::success(Some(Value::Int((a + b).into()))) +} + +crate::mq_plugin_entry! { + name: "sdk.test", + version: "0.1.0", + exports: { + "test.add" => "($a: Int, $b: Int) -> Int" => add, + } +} + +struct TestHost { + _state: Box, + api: MqHostApi, +} + +fn test_host() -> TestHost { + let mut state = Box::new(TestHostState::default()); + let api = MqHostApi { + struct_size: std::mem::size_of::() as u32, + abi_major: ABI_MAJOR, + abi_minor: ABI_MINOR, + host_data: (&mut *state) as *mut TestHostState as *mut c_void, + alloc: test_alloc, + free: test_free, + register_function: test_register, + request_capability: test_capability, + }; + TestHost { _state: state, api } +} + +#[test] +fn macro_exports_and_registers() { + let _guard = abi_test_lock(); + let host = test_host(); + let mut plugin_api = MqPluginApi::host_initialized(); + // SAFETY: test host table follows the ABI contract. + let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) }; + assert_eq!(code, result::OK); + assert_eq!(plugin_api.abi_major, ABI_MAJOR); + assert_eq!(plugin_api.abi_minor, ABI_MINOR); + // SAFETY: metadata is plugin static data valid during the entry call. + let metadata = unsafe { plugin_api.plugin_metadata_wire.as_slice() }.expect("metadata"); + let metadata = String::from_utf8_lossy(metadata); + assert!(metadata.contains("\"name\":\"sdk.test\"")); + assert_eq!(host._state.registrations.len(), 1); + assert_eq!(host._state.registrations[0].0, "test.add"); + assert!(host._state.registrations[0] + .1 + .contains("($a: Int, $b: Int) -> Int")); +} + +#[test] +fn registered_export_roundtrips_wire_request() { + let _guard = abi_test_lock(); + let host = test_host(); + let mut plugin_api = MqPluginApi::host_initialized(); + // SAFETY: test host table follows the ABI contract. + let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) }; + assert_eq!(code, result::OK); + + let request = WireRequest::new("test.add") + .with_arg("a", &Value::Int(20_i64.into())) + .with_arg("b", &Value::Int(22_i64.into())); + let request_bytes = request.to_json_bytes().expect("request"); + let (_, _, invoke) = &host._state.registrations[0]; + let mut result_buffer = MqOwnedBytes::EMPTY; + let mut error_buffer = MqOwnedBytes::EMPTY; + // SAFETY: invoke is the SDK callback; null ctx is fine because the handler + // does not request a capability. Buffers are valid out-parameters. + let code = unsafe { + invoke( + ptr::null_mut(), + MqBytes::from_slice(&request_bytes), + &mut result_buffer, + &mut error_buffer, + ) + }; + assert_eq!(code, result::OK); + assert!(error_buffer.is_empty()); + // SAFETY: result buffer was allocated by test_alloc for us. + let response_bytes = unsafe { result_buffer.to_vec() }.expect("result"); + // SAFETY: allocated by test_alloc; release exactly once. + unsafe { test_free(ptr::null_mut(), result_buffer.data as *mut c_void) }; + + let response = WireResponse::from_json_bytes(&response_bytes).expect("response"); + assert_eq!( + response.typed_value().expect("typed"), + Some(Value::Int(42_i64.into())) + ); +} + +#[test] +fn handler_error_is_written_as_error_envelope() { + let _guard = abi_test_lock(); + let host = test_host(); + let mut plugin_api = MqPluginApi::host_initialized(); + // SAFETY: test host table follows the ABI contract. + let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) }; + assert_eq!(code, result::OK); + + let request = WireRequest::new("test.add"); // missing arguments + let request_bytes = request.to_json_bytes().expect("request"); + let (_, _, invoke) = &host._state.registrations[0]; + let mut result_buffer = MqOwnedBytes::EMPTY; + let mut error_buffer = MqOwnedBytes::EMPTY; + // SAFETY: invoke is the SDK callback with valid out-parameters. + let code = unsafe { + invoke( + ptr::null_mut(), + MqBytes::from_slice(&request_bytes), + &mut result_buffer, + &mut error_buffer, + ) + }; + assert_ne!(code, result::OK); + assert!(result_buffer.is_empty()); + // SAFETY: error buffer was allocated by test_alloc for us. + let error_bytes = unsafe { error_buffer.to_vec() }.expect("error"); + // SAFETY: allocated by test_alloc; release exactly once. + unsafe { test_free(ptr::null_mut(), error_buffer.data as *mut c_void) }; + let response = WireResponse::from_error_json_bytes(&error_bytes).expect("decode"); + let error = response.into_result().expect_err("error"); + assert_eq!(error.code, "missing_argument"); + assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Invoke); +} + +#[test] +fn initialization_rejects_bad_host_major() { + let _guard = abi_test_lock(); + let mut host = test_host(); + host.api.abi_major = 2; + let mut plugin_api = MqPluginApi::host_initialized(); + // SAFETY: intentionally inconsistent host table; entry must reject it. + let code = unsafe { mq_plugin_entry_v1(&host.api as *const MqHostApi, &mut plugin_api) }; + assert_eq!(code, result::ABI_MISMATCH); +} diff --git a/crates/marqdo-plugin-sdk/src/wire.rs b/crates/marqdo-plugin-sdk/src/wire.rs new file mode 100644 index 0000000..9266abb --- /dev/null +++ b/crates/marqdo-plugin-sdk/src/wire.rs @@ -0,0 +1,98 @@ +//! Wire envelope helpers for plugin handlers. +//! +//! The canonical envelope is defined by `marqdo-plugin-abi` and documented in +//! `spec/value-wire.md`: UTF-8 JSON, `wire_version == 1`, type-tagged values. +//! Handlers normally do: +//! +//! ```ignore +//! fn add(ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { +//! let request = decode_request(args)?; +//! let values = request.typed_args()?; +//! success(Some(Value::Int((int_arg(&values, "a")? + int_arg(&values, "b")?).into()))) +//! } +//! ``` + +use std::collections::BTreeMap; + +use marqdo_plugin_abi::{ + bool_from_value, int_from_value, text_from_value, PluginError, Value, WireRequest, WireResponse, +}; +use serde_json::Value as Json; + +/// Decode and validate a request envelope received from the host. +pub fn decode_request(bytes: &[u8]) -> Result { + WireRequest::from_json_bytes(bytes) +} + +/// Look up a typed argument by name. +pub fn value_arg<'a>( + values: &'a BTreeMap, + name: &str, +) -> Result<&'a Value, PluginError> { + values.get(name).ok_or_else(|| { + PluginError::invoke( + "missing_argument", + format!("required argument `{name}` is missing"), + ) + }) +} + +/// Look up an integer argument (must fit in `i64`). +pub fn int_arg(values: &BTreeMap, name: &str) -> Result { + let value = value_arg(values, name)?; + int_from_value(value).ok_or_else(|| { + PluginError::invoke( + "invalid_argument_type", + format!("argument `{name}` must be an Int"), + ) + }) +} + +/// Look up a text argument. +pub fn text_arg<'a>( + values: &'a BTreeMap, + name: &str, +) -> Result<&'a str, PluginError> { + let value = value_arg(values, name)?; + text_from_value(value).ok_or_else(|| { + PluginError::invoke( + "invalid_argument_type", + format!("argument `{name}` must be Text"), + ) + }) +} + +/// Look up a boolean argument. +pub fn bool_arg(values: &BTreeMap, name: &str) -> Result { + let value = value_arg(values, name)?; + bool_from_value(value).ok_or_else(|| { + PluginError::invoke( + "invalid_argument_type", + format!("argument `{name}` must be Bool"), + ) + }) +} + +/// Encode a successful response envelope. +pub fn success(value: Option) -> Result, PluginError> { + success_raw(value.as_ref().map(marqdo_plugin_abi::to_wire_json)) +} + +/// Encode a successful response with an already-encoded type-tagged value. +pub fn success_raw(value: Option) -> Result, PluginError> { + WireResponse::success_raw(value).to_json_bytes() +} + +/// Encode an error response envelope. +/// +/// The SDK's dispatch layer uses this automatically when a handler returns an +/// error; handlers may also build custom error responses with it. +pub fn error_response(error: &PluginError) -> Result, PluginError> { + WireResponse::from_error(error).to_json_bytes() +} + +/// Decode a response value back into a typed [`Value`] (useful in tests and +/// plugins that compose calls). +pub fn response_value(bytes: &[u8]) -> Result, PluginError> { + WireResponse::from_json_bytes(bytes)?.typed_value() +} diff --git a/docs/STATUS.md b/docs/STATUS.md index 4b0c435..be56b13 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -125,31 +125,32 @@ SDK physical repository after S07/S08, regex/compression replacement under ADR-0062, foreign F-B (ADR-0063), platform and strict evidence, and the Engine/ Native Host split only if the ADR-0071 reopening conditions appear. -## 0.13 Independent plugin SDK repository — issue #15 (unreleased candidate) +## 0.13 Plugin SDK remains in the CLI workspace — split reverted (unreleased candidate) -This is a repository-ownership/architecture change, not a new product release. -The contract and plugin ABI behaviour are unchanged. Evidence: -[`evidence/2026-11-26-issue-15-sdk-independent-repository.md`](evidence/2026-11-26-issue-15-sdk-independent-repository.md); -decision: [ADR-0072](adr/0072-sdk-independent-repository.md). +This is an architecture correction, not a product/protocol change. Decision: +[ADR-0073](adr/0073-sdk-stays-in-cli-workspace.md) (supersedes +[ADR-0072](adr/0072-sdk-independent-repository.md)). Evidence: +[`evidence/2026-11-26-issue-15-sdk-split-reverted.md`](evidence/2026-11-26-issue-15-sdk-split-reverted.md). -- The Rust SDK moved to the public repository - [`cflmy/marqdo-plugin-sdk`](https://git.cflmy.cn/cflmy/marqdo-plugin-sdk) - (commit `b31187a`), with its own workspace/lock, AGENTS rules, README, license - and Woodpecker pipeline definition. -- It consumes `marqdo-plugin-abi` from the CLI repository at the exact - `rev = 2585915e16906dac75f8571bed02e7f6f868c6bc`; it never uses a `../cli` - path, a floating branch, a submodule or a copied ABI/Value Wire. -- The CLI repository no longer contains `crates/marqdo-plugin-sdk`, - `tests/sdk-plugin` or the CLI-side SDK gate; the SDK does not appear in the - workspace or `Cargo.lock`. The CLI does not depend on the SDK. -- Clean-clone SDK build/tests and a real integration against the frozen - released `3.0.0-rc.4` CLI pass (`Int 42`, tampered digest rejected). CLI - workspace tests: 631 passed / 0 failed / 0 ignored (the five SDK tests moved - to the SDK repository). The SDK - repository's CI repeats those checks; enabling the Woodpecker project for the - new repository is an administrative follow-up, not a code claim. -- Engine/Native Host remain in the CLI workspace under ADR-0071; no other - repository split is approved by this change. +- The public `cflmy/marqdo-plugin-sdk` repository was **deleted**. The SDK + source is restored as the CLI workspace crate `crates/marqdo-plugin-sdk`, with + the same contract-only dependency graph (`marqdo-plugin-abi` + serde); it is + not a remote repository, mirror or submodule. +- The CLI keeps the atomic plugin-development surface: C header, `spec/`, the + `marqdo-plugin-abi` contract, SDK helpers, fixture and real CLI invocation + test change in one workspace/lock/candidate SHA. No cross-repository `rev` + pin remains. +- `tests/sdk-plugin` and `tools/ci/check_plugin_sdk.py` are restored; the gate + builds the fixture with only the public SDK and invokes it through the real + CLI with explicit trust/grant, rejecting a tampered artifact digest. +- Logical ADR-0071 boundaries are unchanged: the runtime depends only on the + neutral contract, `marqdo-plugin-abi` is a pure contract, loader/worker live + in `marqdo-host::plugin`, CLI is the single assembly point. +- External plugin access is unchanged: the CLI product and public repository + carry the header/spec/SDK/loader; plugin authors compile their plugin, not the + CLI. Engine/Native Host remain in the workspace; no other split is planned. +- ADR-0072 and the old issue-#15 evidence carry Superseded banners. The remote + replica is gone; Git history retains the decision/implementation record. ## 0.10 Closed public Analysis boundary — issue #10 (RC.4 released) diff --git a/docs/adr/0071-engine-host-contract-boundary.md b/docs/adr/0071-engine-host-contract-boundary.md index 7d0b905..c652e48 100644 --- a/docs/adr/0071-engine-host-contract-boundary.md +++ b/docs/adr/0071-engine-host-contract-boundary.md @@ -1,10 +1,6 @@ # ADR-0071 — Engine / Host Contract / Native Host / CLI boundaries Status: **Accepted** for the pre-stable 3.0 line (2026-11-26). -The SDK portion of the repository decision was later implemented by -[ADR-0072](0072-sdk-independent-repository.md) (independent public SDK -repository pinned to this contract); the Engine/Native Host keep-in-workspace -decision is unchanged. Supersedes the historical review-RFC position that a Host contract crate is a second-step, optional move. It does not supersede the language contract @@ -95,10 +91,10 @@ maintainer, and an empty candidate repository would be a prohibited boundary violation. This ADR records **keep in workspace** as the legal conclusion and names the reopening conditions in `docs/architecture/CURRENT.md` §7. -The plugin SDK's physical move landed as [ADR-0072](0072-sdk-independent-repository.md): -a standalone public repository consumes this contract at one pinned CLI `rev`. -The Engine and Native Host stay here; no gitlink/submodule or empty -`marqdo-cli-*` repository is created by this ADR. +The plugin SDK's physical move is a follow-up: the contract is decoupled now, +and the move requires a clean-directory build against a fixed contract revision +(issue #13 S07/S08). No gitlink/submodule or empty `marqdo-cli-*` repository is +created by this ADR. ## Verification diff --git a/docs/adr/0072-sdk-independent-repository.md b/docs/adr/0072-sdk-independent-repository.md index d9369f5..65f4b3f 100644 --- a/docs/adr/0072-sdk-independent-repository.md +++ b/docs/adr/0072-sdk-independent-repository.md @@ -1,6 +1,8 @@ # ADR-0072 — Independent `marqdo-plugin-sdk` repository -Status: **Accepted** (2026-11-26). +Status: **Superseded by [ADR-0073](0073-sdk-stays-in-cli-workspace.md)** +(2026-11-26). The independent repository was deleted and the SDK returned to +the CLI workspace; this document is kept as decision history only. Complements [ADR-0071](0071-engine-host-contract-boundary.md) and implements the SDK follow-up tracked by issue [#15](https://git.cflmy.cn/cflmy/marqdo-cli/issues/15) diff --git a/docs/adr/0073-sdk-stays-in-cli-workspace.md b/docs/adr/0073-sdk-stays-in-cli-workspace.md new file mode 100644 index 0000000..f201e1e --- /dev/null +++ b/docs/adr/0073-sdk-stays-in-cli-workspace.md @@ -0,0 +1,99 @@ +# ADR-0073 — Keep the plugin SDK in the CLI workspace; defer the repository split + +Status: **Accepted** (2026-11-26). +Supersedes [ADR-0072](0072-sdk-independent-repository.md). + +## Context + +ADR-0072 split `marqdo-plugin-sdk` into the public repository +`cflmy/marqdo-plugin-sdk` and pinned it to one CLI contract `rev`. The +implementation itself was technically sound (clean-clone build, frozen-CLI +integration, no second ABI), but a re-evaluation against the pre-stable project's +architecture showed that the **repository boundary was premature**, even though +the **logical contract boundary is correct and stays**. + +The relevant facts at this point in the prerelease line: + +- the SDK is a small, contract-only consumer (six source files; dependencies are + `marqdo-plugin-abi`, `serde`, `serde_json`); +- plugin ABI 1.0, Value Wire 1 and the C header are frozen; the SDK has no + independent version or release story beyond the ABI generation; +- the C header, `spec/plugin-abi.md`, the `marqdo-plugin-abi` contract, the + loader/worker and the SDK helpers evolve together and are owned by the same + maintainers; +- no registry publication or independent maintenance exists for the SDK; +- the CLI product supports external plugin integration without the SDK (C ABI + + loader are in the CLI), so the SDK is a developer kit, not a runtime feature. + +Under issue #13's own criteria, "keep in workspace" is a legal conclusion when +independent consumer/release evidence is absent. The split added a cross-repo +`rev` pin, a second CI lane, a second source location and a documentation +integrity burden (stale in-repo paths, weak entry links) without a current +release or consumer benefit. The CLI's developer-facing contract, header, spec, +SDK and examples should form one atomic change domain. + +## Decision + +1. **The plugin SDK returns to the CLI workspace** as + `crates/marqdo-plugin-sdk`, a contract-only crate. It keeps its current clean + dependency graph: `marqdo-plugin-abi` + `serde`/`serde_json`; no loader, + worker, host, sandbox or CLI dependency. +2. **The independent repository is deleted.** Its source was restored from CLI + Git history; no second copy of the SDK or contract remains. The SDK must not + be reintroduced as a remote repository or as a submodule in this stage. +3. **Logical boundaries stay exactly as ADR-0071 defined them**: the runtime + depends only on `marqdo-host-contract`; `marqdo-plugin-abi` is a pure + contract; execution-side loader/worker/manifest/artifact live in + `marqdo-host::plugin`; the CLI is the single assembly point. +4. **Atomicity is the priority for the pre-stable line.** ABI layout, header, + spec, contract crate, SDK helpers, fixture and the real CLI invocation test + land in one commit/PR/lock. There is no cross-repository pin to bump and no + second current source tree. +5. **External access remains in the CLI product.** The release archive and + repository carry the C header, public plugin spec, loader/worker and the SDK + source; plugin authors build their plugin against this repository (or use + the header from another language). The CLI itself is not compiled by plugin + users. +6. **Future extraction is a new decision, not an implicit step.** It requires + new evidence: independent SDK release (for example a published contract + artifact), a real non-CLI consumer/maintainer, or a distribution need that + the atomic workspace cannot serve. It then needs a new Accepted ADR and must + not create a CLI↔SDK gitlink cycle. + +## Verification + +- SDK crate, fixture, CLI-side SDK gate and workspace/lock are restored; the + CLI builds and tests them in the same workspace. +- `tools/ci/check_dependency_boundaries.py` enforces the SDK's contract-only + normal/build dependencies and its presence in the workspace as a reviewed + crate. +- `tools/ci/check_plugin_sdk.py` builds the SDK fixture with only the public SDK + and loads it through the real CLI with explicit trust/grant; a tampered + artifact digest is rejected. +- The remote split repository was deleted after this decision; no temporary + branch was created for the revert. +- Full evidence: `docs/evidence/2026-11-26-issue-15-sdk-split-reverted.md`. + +## Rejected alternatives + +- **Keep the split because it was already implemented.** Sunk-cost reasoning; + it does not satisfy the "necessary split" criterion for this stage. +- **Keep the remote repository as a mirror/copy.** Two current SDK sources and + a second contract consumer tree are explicitly forbidden; Git history already + preserves ADR-0072's implementation. +- **Make the SDK a submodule of the CLI.** Inverts the dependency direction and + risks the CLI gitlink ↔ SDK → CLI contract cycle; the CLI does not consume + the SDK at build time. +- **Turn the SDK into a prebuilt binary so users need not compile.** Native + plugins are compiled by their authors by definition; the SDK is a source-level + helper. A prebuilt SDK is neither a plugin nor a compiler target. + +## Consequences + +- One atomic language/plugin-development change domain; one lock and one + candidate SHA for ABI/header/spec/SDK/loader changes. +- External plugin integration keeps working through the CLI's contract and + loader; the SDK is discoverable in the same public repository as the header + and spec. +- The split work remains in Git history (ADR-0072, former PR #16) as decision + history; it is not current architecture. diff --git a/docs/adr/README.md b/docs/adr/README.md index 436edd9..b9f6eb4 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -74,5 +74,7 @@ Files: `0001`–`0050`, plus: Native Host / CLI responsibilities, dependency rules, plugin ABI contract split and the keep-in-workspace repository decision. -* [0072](0072-sdk-independent-repository.md) — independent public - `cflmy/marqdo-plugin-sdk` repository pinned to one CLI contract `rev`. +* [0072](0072-sdk-independent-repository.md) — **superseded**: the independent + public SDK repository was deleted and the SDK returned to the CLI workspace. +* [0073](0073-sdk-stays-in-cli-workspace.md) — keep the plugin SDK in the CLI + workspace for the pre-stable atomic line; repository split deferred. diff --git a/docs/architecture/CURRENT.md b/docs/architecture/CURRENT.md index 78461a9..632717a 100644 --- a/docs/architecture/CURRENT.md +++ b/docs/architecture/CURRENT.md @@ -19,7 +19,8 @@ resources, OS adapters and trusted extension execution; `crates/cli` remains the single product assembly. The plugin ABI crate is a public contract only: native loading, artifact/manifest execution and worker processes live in `marqdo-host::plugin`. The SDK depends on the contract, not on a loader or a -host. +host, and stays in this workspace as a contract-only developer crate +([ADR-0073](../adr/0073-sdk-stays-in-cli-workspace.md)). The Engine and the Native Host stay in **this workspace**. Issue #13 §9.2 admission for a separate repository is not met yet: there is no real external @@ -48,6 +49,7 @@ in the same change. | `marqdo-sandbox` | Native Host support | OS isolation probe and strict launch | | `marqdo-foreign` | Native Host support | Controlled one-shot foreign kernels (F-A) | | `marqdo-plugin-abi` | Public contract | C ABI v1 layout, wire envelope and protocol errors | +| `marqdo-plugin-sdk` | Public contract consumer | Third-party plugin development helpers | | `marqdo-worker-ipc` | Shared plumbing | One bounded worker frame transport | | `marqdo-provider-worker` | Shipped worker | Provider helper process | | `marqdo-package` | Product support | Project manifest, lock and dependency resolution | @@ -207,7 +209,7 @@ marqdo-host-contract -> marqdo-value, marqdo-span marqdo-host -> marqdo-host-contract, marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox, marqdo-worker-ipc marqdo-plugin-abi -> marqdo-value, serde/serde_json (contract only) -[cflmy/marqdo-plugin-sdk] -> cflmy/marqdo-cli#marqdo-plugin-abi @ pinned rev +marqdo-plugin-sdk -> marqdo-plugin-abi (contract only) marqdo-provider-worker -> marqdo-worker-ipc ``` @@ -325,15 +327,17 @@ that a phase is complete. |---|---|---| | Engine (`span`/`value`/`expression`/`markdown`/`ir`/`frontend`/`runtime`/`host-contract`) | **Keep in this workspace** as one atomic semantic-change domain | A real, non-in-repo consumer needs independent build/release, and the semantic change cost is acceptable | | Native Host (`host`/`sandbox`/`foreign`/plugin loader) | **Keep in this workspace**, dependent on the neutral contract | An independent platform maintainer or second product consumes it; security/conformance can be verified separately | -| `marqdo-plugin-sdk` | **Moved to independent public repository** `cflmy/marqdo-plugin-sdk` ([ADR-0072](../adr/0072-sdk-independent-repository.md)) | Contract input is a pinned CLI git `rev`; clean-clone build + frozen-CLI integration are the SDK repository's gates. CLI must not depend on it or re-add a copy | +| `marqdo-plugin-sdk` | **Keep in this workspace** as a contract-only developer crate. The ADR-0072 independent repository was deleted and the source restored ([ADR-0073](../adr/0073-sdk-stays-in-cli-workspace.md)); atomic ABI/header/spec/SDK changes are the priority for the pre-stable line | Independent SDK release/registry publication, a real non-CLI consumer or maintainer, and a new Accepted ADR. No submodule/gitlink | | Stdlib | Separate issue #11/#12 (Phase A build input); runtime contract unchanged | Ecosystem-assembled Bundle and extension replacement accepted; then retire the in-repo source authority | | Regex/compression domain services | **DEFERRED** under ADR-0062 ownership; no new domain operation may be added | A separately installable extension replaces the host-held service and the old entries are removed atomically | | Foreign F-A | Retained; no F-B, session or new transport in this change | Separate ADR and milestone | No candidate empty `marqdo-engine`, `marqdo-host` or `marqdo-cli-*` repository -is created by this decision. Git repository boundaries are ownership and release -boundaries, not a mechanical projection of Cargo crates. The engine and native -host are one source tree until the reopening evidence above exists. +is created by this decision. The former independent SDK repository was deleted +under ADR-0073; the SDK is back in this workspace and no remote copy is kept. +Git repository boundaries are ownership and release boundaries, not a mechanical +projection of Cargo crates. The engine, native host and plugin developer kit are +one source tree until the reopening evidence above exists. ## 8. References @@ -357,9 +361,10 @@ host are one source tree until the reopening evidence above exists. - [Compute-machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) and [core/stdlib RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) — design input. - [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) — historical review input; the current boundary decision is ADR-0071. - [ADR-0071: Engine / Host Contract / Native Host boundaries](../adr/0071-engine-host-contract-boundary.md) — accepted responsibility split and keep-in-workspace decision for issue #13. -- [ADR-0072: Independent `marqdo-plugin-sdk` repository](../adr/0072-sdk-independent-repository.md) — the one deliberate repository split (public SDK leaf pinned to the CLI contract). -- [Issue #15 SDK split evidence](../evidence/2026-11-26-issue-15-sdk-independent-repository.md) — clean-clone build and frozen-CLI integration. +- [ADR-0073: Keep the plugin SDK in the CLI workspace](../adr/0073-sdk-stays-in-cli-workspace.md) — current decision: SDK atomicity, no split, no remote copy; supersedes ADR-0072. +- [ADR-0072: Independent SDK repository](../adr/0072-sdk-independent-repository.md) — **superseded** decision history; the repository was deleted. - [Issue #13 engine/host evidence](../evidence/2026-11-26-issue-13-engine-host-boundary.md) — executed candidate commands and results. +- [Issue #15 SDK split-revert evidence](../evidence/2026-11-26-issue-15-sdk-split-reverted.md) — repository deletion, source restoration and gates. - [RFC-EXT-0001](RFC-EXT-0001.md) — extensibility closure task specification (implementation status tracked here and in STATUS). - [ADR-0054: single callable binding](../adr/0054-callable-binding-single-source.md) — one registry/binding pass, runtime dispatch by identity. - [ADR-0055: resource provider CLI v2](../adr/0055-resource-provider-cli-v2.md) — provider v2 manifest/worker CLI closure and trust boundary. diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 694692f..117ff45 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -83,8 +83,9 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and | Resource operations and core kinds | [0062](../adr/0062-resource-operation-ownership-and-core-kinds.md) | Accepted and implemented; architecture gate pins the reviewed lists | | Foreign F-A transition | [0063](../adr/0063-foreign-kernel-transition-fa.md) | Accepted: retained F-A primitive; F-B deferred | | Stable core inventory and external gate | [0064](../adr/0064-stable-core-extension-boundary.md) | Accepted and wired into Linux CI | -| Engine / Host Contract / Native Host / CLI boundaries | [0071](../adr/0071-engine-host-contract-boundary.md) | Accepted and implemented by issue #13: runtime depends on the neutral contract, native host implements it, plugin ABI is contract-only, Engine/Native Host keep-in-workspace decision | -| Independent plugin SDK repository | [0072](../adr/0072-sdk-independent-repository.md) | Accepted and implemented: public `cflmy/marqdo-plugin-sdk`, pinned to CLI contract commit, CLI does not depend on it | +| Independent plugin SDK repository | [0072](../adr/0072-sdk-independent-repository.md) | **Superseded by ADR-0073**: repository deleted, SDK restored to the CLI workspace | +| Plugin SDK stays in the CLI workspace | [0073](../adr/0073-sdk-stays-in-cli-workspace.md) | Accepted: atomic pre-stable changes, no split, no remote copy | +| Engine / Host Contract / Native Host / CLI boundaries | [0071](../adr/0071-engine-host-contract-boundary.md) | Accepted and implemented by issue #13: runtime depends on the neutral contract, native host implements it, plugin ABI is contract-only, keep-in-workspace repository decision | | Manifest-driven Resource Control | [0065](../adr/0065-resource-control-vnext.md) | Proposed | | Structured Tasks and Channels | [0066](../adr/0066-structured-tasks-v1.md) | Proposed | | Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication | diff --git a/docs/ci.md b/docs/ci.md index 14ac6a8..e4744ea 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -34,6 +34,7 @@ test (rust:1.100-bookworm, clippy/rustfmt, Node.js 22, MinGW, both binaries): docs_consistency / architecture_boundaries / stdlib_product check_dependency_boundaries.py (Cargo-metadata responsibility graph) check_engine_boundary.py (independent consumer build/run + CLI differential) + check_plugin_sdk.py (real third-party SDK plugin via the real CLI) python3 -m unittest discover -s tools/ci -p "test_*.py" rustup target add x86_64-pc-windows-gnu cargo check --workspace --all-targets --target x86_64-pc-windows-gnu diff --git a/docs/developers/README.md b/docs/developers/README.md index 7fbff30..d771621 100644 --- a/docs/developers/README.md +++ b/docs/developers/README.md @@ -18,7 +18,7 @@ Foreign wire v1, Provider manifest v2, lock v4 and markdown profile |---|---|---| | AI/math/data/quantum/SKILL libraries, pure algorithms | `.mq.md` package | `index.mq.md`, `marqdo.yaml`, README, tests | | Knowledge/Proof/View/IDE/lint/analysis tools | CLI Tool protocol | standalone executable + `tool.json` + Analysis/Observation consumer | -| High-performance native callable functions | Callable Plugin ABI v1 | `plugin.yaml`, host-targeted library, public SDK (`cflmy/marqdo-plugin-sdk`) + header | +| High-performance native callable functions | Callable Plugin ABI v1 | `plugin.yaml`, host-targeted library, SDK/header | | New foreign language backend (R/Python/Julia/…) | Foreign Kernel | `kernel.json`, executable provider, pinned environment | | Hardware/device/external-stream resources | Resource Provider v2 | `provider.json`, C ABI library, worker helper | | Change `@exec` semantics, add keywords/types | **not** a third-party extension | core language RFC + migration + full conformance | @@ -61,7 +61,7 @@ only on `marqdo-host-contract`; the native host implements it; the plugin ABI crate is a contract (no loader/worker); the CLI is the only assembly point. Run `python3 tools/ci/check_dependency_boundaries.py`, `python3 tools/ci/check_engine_boundary.py` and -the independent SDK repository's frozen-CLI check with the Rust suits. Do not create an +`python3 tools/ci/check_plugin_sdk.py` with the Rust suits. Do not create an empty candidate repository for a boundary; a split needs the evidence and a new ADR. diff --git a/docs/evidence/2026-11-26-issue-13-engine-host-boundary.md b/docs/evidence/2026-11-26-issue-13-engine-host-boundary.md index 66706b6..1efecb5 100644 --- a/docs/evidence/2026-11-26-issue-13-engine-host-boundary.md +++ b/docs/evidence/2026-11-26-issue-13-engine-host-boundary.md @@ -42,7 +42,7 @@ to a different commit. | Dependency gate | `python3 tools/ci/check_dependency_boundaries.py` | PASS | | Dependency gate negative cases | `python3 -m unittest tools.ci.test_dependency_boundaries` / `python3 -m unittest discover -s tools/ci` | PASS (54 tool tests) | | Engine independence and differential execution | `python3 tools/ci/check_engine_boundary.py` | PASS | -| Plugin SDK real consumption | `python3 tools/ci/check_plugin_sdk.py` | PASS at that candidate; the SDK and this gate moved to the independent repository under issue #15 / ADR-0072 (evidence: `2026-11-26-issue-15-sdk-independent-repository.md`) | +| Plugin SDK real consumption | `python3 tools/ci/check_plugin_sdk.py` | PASS | | Existing product/conformance suites | included in workspace run; stdlib product suite additionally run | PASS | Behavioral facts from the engine gate: diff --git a/docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md b/docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md index d8c2988..5d9eb43 100644 --- a/docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md +++ b/docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md @@ -1,5 +1,11 @@ # Evidence — issue #15 independent `marqdo-plugin-sdk` repository +> **Superseded.** This snapshot records the (later reverted) ADR-0072 split. +> The SDK is back in the CLI workspace under +> [ADR-0073](../adr/0073-sdk-stays-in-cli-workspace.md); the remote repository +> was deleted. See `2026-11-26-issue-15-sdk-split-reverted.md`. Do not read this +> file as current architecture. + Date: 2026-11-26 (Asia/Shanghai) Tracking issue: Decision: [ADR-0072](../adr/0072-sdk-independent-repository.md) diff --git a/docs/evidence/2026-11-26-issue-15-sdk-split-reverted.md b/docs/evidence/2026-11-26-issue-15-sdk-split-reverted.md new file mode 100644 index 0000000..112e631 --- /dev/null +++ b/docs/evidence/2026-11-26-issue-15-sdk-split-reverted.md @@ -0,0 +1,61 @@ +# Evidence — issue #15 plugin SDK split reverted to the CLI workspace + +Date: 2026-11-26 (Asia/Shanghai) +Tracking issue: +Decision: [ADR-0073](../adr/0073-sdk-stays-in-cli-workspace.md) (supersedes +[ADR-0072](../adr/0072-sdk-independent-repository.md)) +Parent: issue #13 / [ADR-0071](../adr/0071-engine-host-contract-boundary.md) + +## Decision + +Parent CLI contract merge: `2585915e16906dac75f8571bed02e7f6f868c6bc`. +Deleted split repository commits: `b31187a` / `c3134e4` (kept in Git history +of the former repository only; no source copy remains). + +The plugin SDK stays in the CLI workspace as a contract-only crate. The public +repository `cflmy/marqdo-plugin-sdk` created by ADR-0072 was deleted; its source +was restored from CLI Git history. The pre-stable line prioritizes atomic +ABI/header/spec/SDK/loader changes in one workspace, lock and candidate SHA. +The logical ADR-0071 boundaries are unchanged. + +## Actions executed + +| Step | Result | +|---|---| +| Restore `crates/marqdo-plugin-sdk` from CLI history | Restored contract-only crate (`marqdo-plugin-abi` + serde/serde_json); no loader/host/worker dependency | +| Restore workspace member and lock | `cargo check --workspace --all-targets --locked` resolves the SDK in the workspace; `Cargo.lock` contains it again | +| Restore `tests/sdk-plugin` and `tools/ci/check_plugin_sdk.py` | Real fixture/gate back in the CLI; builds only against the public SDK and invokes via the real CLI | +| Restore architecture/dependency/docs references | `architecture_boundaries.rs`, `check_dependency_boundaries.py`, `docs_consistency` paths, README/AGENTS/spec/developer guides point at the in-repo crate again | +| Delete remote `cflmy/marqdo-plugin-sdk` | Authorized by the maintainer; the repository and its branches are gone, no mirror remains | +| No temporary branch | The revert is committed directly on `master` and pushed; old merged feature branches are deleted separately | +| Record superseded history | ADR-0072 and the old issue-#15 evidence carry Superseded banners; ADR-0073 is the current decision | + +## Verification (local, Linux x86_64, Rust 1.100) + +| Gate | Command | Result | +|---|---|---| +| Formatting | `cargo fmt --all -- --check` | PASS | +| Clippy | `cargo clippy --workspace --all-targets --locked -- -D warnings` | PASS | +| Rust tests | `cargo test --workspace --locked --offline --no-fail-fast` | PASS — **636 passed / 0 failed / 2 ignored** (same as the pre-split workspace) | +| Architecture boundaries | `cargo test -p marqdo-cli --test architecture_boundaries --locked` | PASS | +| Docs consistency | `cargo test -p marqdo-cli --test docs_consistency --locked` | PASS | +| Dependency direction | `python3 tools/ci/check_dependency_boundaries.py` | PASS — SDK back in the reviewed workspace allowlist with contract-only edges | +| SDK real consumption | `python3 tools/ci/check_plugin_sdk.py` | PASS — builds fixture with only the SDK; real CLI returns `Int 42`; tampered digest rejected | +| Engine differential | `python3 tools/ci/check_engine_boundary.py` | PASS | +| Tools unit tests | `python3 -m unittest discover -s tools/ci -p "test_*.py"` | PASS | + +The remote CI run for the final `master` commit is recorded by the pipeline on +that commit; this file is updated by the same integration when the run exists. +No split repository, mirror or submodule exists after the deletion. + +## Current architecture facts + +- `marqdo-plugin-abi` is still the pure public contract; loader/worker/manifest/ + artifact remain in `marqdo-host::plugin` (ADR-0071). +- `marqdo-plugin-sdk` is a CLI workspace member with normal/build dependencies + only on the contract + serde; the CLI product is the only assembly point. +- Plugin authors get header, spec, SDK, examples and loader from one public CLI + repository/release; they compile their plugin, not the CLI. +- The CLI runtime does not depend on the SDK; external plugin loading remains + available (C ABI header + `--plugin`/`--trust-native-plugin`/`--allow-plugin` + + worker transport). diff --git a/tests/README.md b/tests/README.md index da3c4f9..b25a288 100644 --- a/tests/README.md +++ b/tests/README.md @@ -33,6 +33,7 @@ tests/ │ ├── warnings/ 2 × warning-model/control fixtures + *.expected.json │ └── runtime/ 20 × runtime-error fixtures + *.expected.json ├── embedding/ Independent Engine consumer (own workspace + lock) +├── sdk-plugin/ Third-party plugin built only with the public Rust SDK └── README.md this file ``` @@ -52,6 +53,7 @@ Rust harnesses (all in `crates/cli/tests/`): | `negative.rs` | Current-syntax diagnostics are **hard errors** (never prose fallbacks): exact sorted `sem.*`/`symbol.*`/`call.*`/`frontmatter.*` code lists, the `sem.inferred_signature` warning model with inert-knowledge controls, and runtime error codes — each asserted in its own suite. | | `properties.rs` | Blueprint §14.2 prose invariance: inserting/removing pure narration paragraphs never changes the executable function IR (modulo source spans) and diagnostics stay error-free. | | `embedding/` + `tools/ci/check_engine_boundary.py` | Independent Cargo consumer builds without the native host, executes the real Markdown→frontend→IR→runtime path with bounded budgets and refusal cases, and its terminal Value Wire result matches a real CLI invocation on the same file (issue #13 / ADR-0071). | +| `sdk-plugin/` + `tools/ci/check_plugin_sdk.py` | A third-party plugin builds against only the public SDK, is loaded/invoked by the real CLI with explicit trust/grant, and a tampered artifact digest is rejected. | | `integration_cli.rs` | Real CLI contract: `init`, `check`, `run`, `call`, `inspect`, `fmt`, multi-module imports/cycles, `lock`/`sync --locked`, plugin inspection and explicitly trusted plugin invocation. | | `execution_events.rs` | Execution Events v1 black-box contract: pure JSONL, seq/terminal ordering, byte-exact base64 chunks, live delivery before exit, value redaction/selection, trace coexistence, truncation, output budget and broken-pipe failure. | diff --git a/tests/sdk-plugin/Cargo.lock b/tests/sdk-plugin/Cargo.lock new file mode 100644 index 0000000..0fcda55 --- /dev/null +++ b/tests/sdk-plugin/Cargo.lock @@ -0,0 +1,198 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "marqdo-plugin-abi" +version = "3.0.0-rc.4" +dependencies = [ + "marqdo-value", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "marqdo-plugin-sdk" +version = "3.0.0-rc.4" +dependencies = [ + "marqdo-plugin-abi", + "serde", + "serde_json", +] + +[[package]] +name = "marqdo-sdk-plugin-fixture" +version = "0.1.0" +dependencies = [ + "marqdo-plugin-sdk", +] + +[[package]] +name = "marqdo-span" +version = "3.0.0-rc.4" +dependencies = [ + "serde", +] + +[[package]] +name = "marqdo-value" +version = "3.0.0-rc.4" +dependencies = [ + "marqdo-span", + "num-bigint", + "num-traits", + "serde", + "serde_json", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", + "serde", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/sdk-plugin/Cargo.toml b/tests/sdk-plugin/Cargo.toml new file mode 100644 index 0000000..b16e614 --- /dev/null +++ b/tests/sdk-plugin/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "marqdo-sdk-plugin-fixture" +version = "0.1.0" +edition = "2021" +publish = false + +# Independent workspace: this fixture must build with only the public SDK +# artifacts, exactly as a third-party plugin would. +[workspace] + +[lib] +crate-type = ["cdylib"] +path = "src/lib.rs" + +[dependencies] +marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" } diff --git a/tests/sdk-plugin/call.mq.md b/tests/sdk-plugin/call.mq.md new file mode 100644 index 0000000..660f932 --- /dev/null +++ b/tests/sdk-plugin/call.mq.md @@ -0,0 +1,5 @@ +## @exec main + +`结果 = sdk.add(a=20, b=22)` + +`return 结果` diff --git a/tests/sdk-plugin/src/lib.rs b/tests/sdk-plugin/src/lib.rs new file mode 100644 index 0000000..7290f53 --- /dev/null +++ b/tests/sdk-plugin/src/lib.rs @@ -0,0 +1,33 @@ +//! Minimal third-party plugin built only against the public Rust SDK. +//! +//! It exercises the typed wire helpers (`decode_request`, `int_arg`, +//! `success`) and a `Value::Int` result. Real negotiation, loading and +//! invocation are performed by the frozen CLI in +//! `tools/ci/check_plugin_sdk.py`. + +use marqdo_plugin_sdk::wire; +use marqdo_plugin_sdk::{mq_plugin_entry, CallContext, PluginError, Value}; + +fn add(_ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { + let request = wire::decode_request(args)?; + let values = request.typed_args()?; + let a = wire::int_arg(&values, "a")?; + let b = wire::int_arg(&values, "b")?; + wire::success(Some(Value::Int((a + b).into()))) +} + +fn echo_text(_ctx: &mut CallContext, args: &[u8]) -> Result, PluginError> { + let request = wire::decode_request(args)?; + let values = request.typed_args()?; + let text = wire::text_arg(&values, "text")?; + wire::success(Some(Value::text(text))) +} + +mq_plugin_entry! { + name: "sdk.demo", + version: "0.1.0", + exports: { + "sdk.add" => "($a: Int, $b: Int) -> Int" => add, + "sdk.echo" => "($text: Text) -> Text" => echo_text, + } +} diff --git a/tools/ci/check_dependency_boundaries.py b/tools/ci/check_dependency_boundaries.py index 9df8948..7abda3c 100644 --- a/tools/ci/check_dependency_boundaries.py +++ b/tools/ci/check_dependency_boundaries.py @@ -50,6 +50,7 @@ WORKSPACE_CRATES = { "marqdo-sandbox": "native host support: OS isolation probe and strict launch", "marqdo-foreign": "native host support: controlled one-shot foreign kernels (F-A)", "marqdo-plugin-abi": "public contract: C ABI types, wire envelope and protocol errors", + "marqdo-plugin-sdk": "public contract consumer: third-party plugin development helpers", "marqdo-worker-ipc": "shared plumbing: one bounded worker frame transport", "marqdo-provider-worker": "shipped worker: provider helper process", "marqdo-package": "product support: project manifest, lock and dependency resolution", @@ -239,14 +240,22 @@ def check_workspace(metadata: dict) -> list[str]: f"dependency `{forbidden}`" ) - # ADR-0072: the SDK is an independent repository. The CLI workspace must - # not carry it again; a new member here would be an undocumented layer and - # would resurrect a second contract-consumer copy. - if "marqdo-plugin-sdk" in members: - problems.append( - "marqdo-plugin-sdk must not be a CLI workspace member; the SDK is the " - "independent repository pinned to a contract revision (ADR-0072)" - ) + sdk = "marqdo-plugin-sdk" + if sdk in graph: + closure = reachable(graph, sdk, BUILD_KINDS) + for forbidden in ( + "libloading", + "marqdo-worker-ipc", + "marqdo-host", + "marqdo-sandbox", + "marqdo-cli", + "marqdo-provider-worker", + ): + if forbidden in closure: + problems.append( + f"plugin SDK reaches execution-side dependency `{forbidden}`: " + f"{closure[forbidden]}" + ) # CLT Tool / package identity is a product concern; the CLI is the only # crate allowed to combine engine + native host + package. diff --git a/tools/ci/check_plugin_sdk.py b/tools/ci/check_plugin_sdk.py new file mode 100644 index 0000000..559c592 --- /dev/null +++ b/tools/ci/check_plugin_sdk.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Real third-party plugin SDK consumption gate (issue #13 §6.3, S04-S05). + +Builds the fixture in ``tests/sdk-plugin`` with only the public Rust SDK, creates +the host-specific ``plugin.yaml``, then lets a real built CLI load and invoke it +with explicit trust and an explicit plugin grant. A tampered digest must fail +closed. No mock host, no direct Rust call into plugin internals. + +Usage: + python3 tools/ci/check_plugin_sdk.py [--offline] +""" + +from __future__ import annotations + +import argparse +import hashlib +import platform +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +FIXTURE = REPO_ROOT / "tests" / "sdk-plugin" +CALL_DOC = FIXTURE / "call.mq.md" + + +class GateError(Exception): + pass + + +def cargo() -> str: + path = shutil.which("cargo") + if path is None: + raise GateError("cargo is not on PATH") + return path + + +def run(command: list[str], *, check: bool = True) -> subprocess.CompletedProcess: + result = subprocess.run( + command, cwd=REPO_ROOT, capture_output=True, text=True, check=False + ) + if check and result.returncode != 0: + raise GateError( + f"`{' '.join(command)}` failed with {result.returncode}:\n" + f"{result.stdout}\n{result.stderr}" + ) + return result + + +def host_triple() -> str: + result = run(["rustc", "-vV"]) + for line in result.stdout.splitlines(): + if line.startswith("host: "): + return line[len("host: ") :].strip() + raise GateError("rustc -vV did not report a host triple") + + +def artifact_name() -> str: + system = platform.system() + if system == "Darwin": + return "libmarqdo_sdk_plugin_fixture.dylib" + if system == "Windows": + return "marqdo_sdk_plugin_fixture.dll" + return "libmarqdo_sdk_plugin_fixture.so" + + +def write_manifest( + directory: Path, + digest: str, + triple: str, + artifact: str, + *, + tamper: bool = False, +) -> None: + effective = "0" * 64 if tamper else digest + manifest = f"""plugin: + name: sdk.demo + version: 0.1.0 + abi: "^1.0" + kind: native + exports: + - name: sdk.add + signature: "($a: Int, $b: Int) -> Int" + - name: sdk.echo + signature: "($text: Text) -> Text" + artifacts: + - target: {triple} + file: {artifact} + sha256: "{effective}" +""" + (directory / "plugin.yaml").write_text(manifest, encoding="utf-8") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--offline", action="store_true") + parser.add_argument( + "--sdk-revision", + default=None, + help="informational: exact CLI/SDK source revision under test", + ) + arguments = parser.parse_args() + offline = ["--offline"] if arguments.offline else [] + try: + run([cargo(), "build", "--locked", "-p", "marqdo-cli", *offline]) + run([cargo(), "build", "--locked", "--manifest-path", str(FIXTURE / "Cargo.toml"), *offline]) + name = artifact_name() + built = FIXTURE / "target" / "debug" / name + if not built.is_file(): + raise GateError(f"SDK fixture artifact not found: {built}") + triple = host_triple() + binary = REPO_ROOT / "target" / "debug" / "marqdo" + if not binary.is_file(): + raise GateError(f"CLI binary not found: {binary}") + + with tempfile.TemporaryDirectory(prefix="marqdo-sdk-plugin-") as raw: + directory = Path(raw) + artifact = "plugin" + Path(name).suffix + shutil.copyfile(built, directory / artifact) + digest = hashlib.sha256((directory / artifact).read_bytes()).hexdigest() + command = [ + str(binary), + "call", + str(CALL_DOC), + "main", + "--plugin", + str(directory), + "--trust-native-plugin", + "--allow-plugin", + "sdk.demo", + ] + + write_manifest(directory, digest, triple, artifact) + positive = run(command, check=False) + if positive.returncode != 0 or positive.stdout.strip() != "42": + raise GateError( + "real CLI could not invoke the SDK plugin: " + f"exit={positive.returncode} stdout={positive.stdout!r} " + f"stderr={positive.stderr!r}" + ) + print("PASS sdk-plugin-real-invocation (Int 42)") + + write_manifest(directory, digest, triple, artifact, tamper=True) + negative = run(command, check=False) + if negative.returncode == 0: + raise GateError("tampered plugin artifact digest was accepted") + combined = negative.stdout + negative.stderr + if "sha256" not in combined.lower() and "artifact" not in combined.lower(): + raise GateError( + "tampered artifact failed without an artifact/sha256 diagnostic: " + + combined + ) + print("PASS sdk-plugin-tampered-digest-rejected") + except GateError as error: + print(f"FAIL plugin-sdk: {error}", file=sys.stderr) + return 1 + print("PASS plugin-sdk") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/ci/test_dependency_boundaries.py b/tools/ci/test_dependency_boundaries.py index 3ec9bd2..565ec5d 100644 --- a/tools/ci/test_dependency_boundaries.py +++ b/tools/ci/test_dependency_boundaries.py @@ -82,6 +82,7 @@ def valid_workspace_edges() -> dict[str, list[str]]: "marqdo-span", ] edges["marqdo-plugin-abi"] = ["marqdo-value"] + edges["marqdo-plugin-sdk"] = ["marqdo-plugin-abi"] edges["marqdo-worker-ipc"] = [] edges["marqdo-sandbox"] = [] edges["marqdo-foreign"] = ["marqdo-worker-ipc"] @@ -184,15 +185,10 @@ class DependencyBoundaryTests(unittest.TestCase): "must not carry execution-side dependency `libloading`", ) - def test_sdk_reappearing_as_workspace_member_is_rejected(self) -> None: - edges = valid_workspace_edges() - edges["marqdo-plugin-sdk"] = ["marqdo-plugin-abi"] - workspace = metadata(edges, members=set(gate.WORKSPACE_CRATES) | {"marqdo-plugin-sdk"}) - consumer = metadata(valid_consumer_edges(), members={"marqdo-embedding-consumer"}) - problems = gate.evaluate(workspace, consumer) - self.assertTrue( - any("must not be a CLI workspace member" in problem for problem in problems), - problems, + def test_sdk_host_edge_is_rejected(self) -> None: + self.assert_rejected( + lambda edges: edges["marqdo-plugin-sdk"].append("marqdo-host"), + "plugin SDK reaches execution-side dependency `marqdo-host`", ) def test_undocumented_workspace_crate_is_rejected(self) -> None: