From 3ab4aaa861f3d1b428486bcd9ba8b648535773c6 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 19:39:11 +0800 Subject: [PATCH] refactor: move the plugin SDK to its independent repository (issue #15) Implements ADR-0072 and the SDK physical migration tracked by issue #15: - remove crates/marqdo-plugin-sdk, tests/sdk-plugin and the CLI-side check_plugin_sdk.py; the public cflmy/marqdo-plugin-sdk repository now owns the SDK workspace, lock, fixture, docs, AGENTS rules and CI definition. - SDK consumes marqdo-plugin-abi at the exact CLI contract rev 2585915e16906dac75f8571bed02e7f6f868c6bc; no path/submodule/copied contract. - CLI does not depend on the SDK and must not re-add it as a workspace member or copy; dependency/architecture gates enforce this. - docs: ADR-0072, CURRENT responsibility map/dependency graph, ADR-0071 amendment, indexes, README, spec/plugin-abi, CI and developer entries. - evidence: clean-clone SDK build/tests and real frozen 3.0.0-rc.4 CLI invocation (Int 42; tampered digest rejected). CLI workspace: 631 passed / 0 failed / 0 ignored; fmt/clippy/docs/architecture/ dependency gates green. Refs #15, #13 --- .github/workflows/ci.yml | 2 - .gitignore | 4 + .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 | 15 -- 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 | 26 ++ .../adr/0071-engine-host-contract-boundary.md | 12 +- docs/adr/0072-sdk-independent-repository.md | 106 ++++++++ docs/adr/README.md | 3 + docs/architecture/CURRENT.md | 7 +- docs/architecture/README.md | 3 +- 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 | 78 ++++++ log.txt | 0 out | 1 - 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 +- 35 files changed, 272 insertions(+), 1454 deletions(-) delete mode 100644 crates/marqdo-plugin-sdk/Cargo.toml delete mode 100644 crates/marqdo-plugin-sdk/src/bytes.rs delete mode 100644 crates/marqdo-plugin-sdk/src/call.rs delete mode 100644 crates/marqdo-plugin-sdk/src/entry.rs delete mode 100644 crates/marqdo-plugin-sdk/src/lib.rs delete mode 100644 crates/marqdo-plugin-sdk/src/tests.rs delete mode 100644 crates/marqdo-plugin-sdk/src/wire.rs create mode 100644 docs/adr/0072-sdk-independent-repository.md create mode 100644 docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md delete mode 100644 log.txt delete mode 100644 out delete mode 100644 tests/sdk-plugin/Cargo.lock delete mode 100644 tests/sdk-plugin/Cargo.toml delete mode 100644 tests/sdk-plugin/call.mq.md delete mode 100644 tests/sdk-plugin/src/lib.rs delete mode 100644 tools/ci/check_plugin_sdk.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 51fbe50..46c5990 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,8 +43,6 @@ 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/.gitignore b/.gitignore index 936ac57..cc5e3e8 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,7 @@ __pycache__/ /tests/embedding/target/ /tests/sdk-plugin/target/ /.tmp/ + +# Accidental curl/test capture files +/out +/log.txt diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index 18d6948..9860b0f 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -50,7 +50,6 @@ 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 2c739ec..2d113ea 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 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. 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 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. ## 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`, `python3 tools/ci/check_plugin_sdk.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`). 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 8c4b141..74d182e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -561,15 +561,6 @@ 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 6e49e37..eb42f4a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,6 @@ 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 c8dfbbe..d84673c 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 plugin SDK consumption gate, the Windows +engine-independence gates, 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 -crates/marqdo-plugin-sdk Rust plugin SDK and entry macro (contract-only) + (the Rust SDK lives in cflmy/marqdo-plugin-sdk) 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 c9c3002..2431680 100644 --- a/crates/cli/tests/architecture_boundaries.rs +++ b/crates/cli/tests/architecture_boundaries.rs @@ -687,18 +687,22 @@ fn plugin_contract_carries_no_native_execution() { "native host must own plugin `{module}`" ); } - let sdk = read(&root.join("crates/marqdo-plugin-sdk/Cargo.toml")); - for forbidden in [ - "marqdo-host", - "marqdo-cli", - "libloading", - "marqdo-worker-ipc", - ] { - assert!( - !sdk.contains(forbidden), - "the plugin SDK must not depend on `{forbidden}`" - ); - } + // 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" + ); } /// 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 deleted file mode 100644 index 2fb847b..0000000 --- a/crates/marqdo-plugin-sdk/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[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 deleted file mode 100644 index 90b3a4f..0000000 --- a/crates/marqdo-plugin-sdk/src/bytes.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! 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 deleted file mode 100644 index a484e91..0000000 --- a/crates/marqdo-plugin-sdk/src/call.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! 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 deleted file mode 100644 index 84743e5..0000000 --- a/crates/marqdo-plugin-sdk/src/entry.rs +++ /dev/null @@ -1,199 +0,0 @@ -//! 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 deleted file mode 100644 index 5833938..0000000 --- a/crates/marqdo-plugin-sdk/src/lib.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! 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 deleted file mode 100644 index 2483884..0000000 --- a/crates/marqdo-plugin-sdk/src/tests.rs +++ /dev/null @@ -1,245 +0,0 @@ -//! 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 deleted file mode 100644 index 9266abb..0000000 --- a/crates/marqdo-plugin-sdk/src/wire.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! 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 98d9a33..4b0c435 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -125,6 +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) + +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). + +- 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. + ## 0.10 Closed public Analysis boundary — issue #10 (RC.4 released) The candidate replaces the program-only Analysis projection in place under diff --git a/docs/adr/0071-engine-host-contract-boundary.md b/docs/adr/0071-engine-host-contract-boundary.md index c652e48..7d0b905 100644 --- a/docs/adr/0071-engine-host-contract-boundary.md +++ b/docs/adr/0071-engine-host-contract-boundary.md @@ -1,6 +1,10 @@ # 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 @@ -91,10 +95,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 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. +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. ## Verification diff --git a/docs/adr/0072-sdk-independent-repository.md b/docs/adr/0072-sdk-independent-repository.md new file mode 100644 index 0000000..d9369f5 --- /dev/null +++ b/docs/adr/0072-sdk-independent-repository.md @@ -0,0 +1,106 @@ +# ADR-0072 — Independent `marqdo-plugin-sdk` repository + +Status: **Accepted** (2026-11-26). + +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) +after the contract decoupling of issue #13. + +## Context + +Issue #13 / ADR-0071 separated the public plugin contract from its execution +side: + +- `marqdo-plugin-abi` (CLI repository) now contains only the C ABI v1 layout, + the wire envelope and protocol errors; +- `dlopen`, manifest/artifact file handling, worker management and invocation + dispatch live in `marqdo-host::plugin`; +- `marqdo-plugin-sdk` consumed only the contract and was verified by a real + fixture loaded through the CLI. + +The SDK is a leaf with a different consumer group (third-party plugin authors), +a different change cadence and an independent release need. Keeping it in the +CLI workspace made the architecture map imply that the CLI product owns SDK +publication and forced every SDK change through the CLI build. Issue #15 +required either fixing the distribution input or recording a blocking ticket. +The CLI repository is public, so a fixed Cargo git `rev` is a fetchable +contract input; there is no need for a submodule, a vendored contract copy or a +second wire implementation. + +This is a **deliberate, narrow repository split**, not a mechanical projection +of every crate: engine and native host remain in the CLI workspace (ADR-0071 +reopening conditions unchanged), and no empty candidate repository is created. + +## Decision + +### Topology + +| Item | Decision | +|---|---| +| SDK repository | Public `cflmy/marqdo-plugin-sdk` (`main`), own Cargo workspace and lock | +| Contract input | `marqdo-plugin-abi` from `https://git.cflmy.cn/cflmy/marqdo-cli.git` at exact `rev = 2585915e16906dac75f8571bed02e7f6f868c6bc` (the merge commit that landed ADR-0071) | +| CLI dependency on SDK | **None**. CLI normal/build/test lanes do not fetch or build the SDK | +| CLI workspace | `crates/marqdo-plugin-sdk` removed; the SDK is not a workspace member | +| Submodule/gitlink | **Not used** for this split; the SDK leaf must not create a CLI↔SDK identity cycle | +| Acceptance fixture | `tests/fixture` in the SDK repository only; real invocation uses a **frozen released CLI binary** via `tools/check_with_frozen_cli.py` | +| Contract authority | Unchanged: CLI owns the C header, Rust layout, Value Wire and error encodings; the SDK never defines a second contract | +| Publication | SDK releases are versioned independently against a contract generation; bumping the pinned CLI `rev` is a reviewed change | + +### Rules + +- The SDK repository must resolve and build from a clean clone without the CLI + checkout; only its fixed git dependency may reach the CLI repository. +- It must not depend on `libloading`, a native host, worker execution, sandbox + or CLI code. +- The SDK's fixture is a third-party plugin built with only the public SDK. It + is verified against a frozen CLI archive (same ABI 1.0 contract), not against a + locally rebuilt CLI. +- The CLI repository must not reintroduce the SDK as a workspace member, a + copied source tree or a compatibility path; `tools/ci/check_dependency_boundaries.py` + and `architecture_boundaries.rs` fail if it does. +- The CLI's public contract is authoritative; the SDK repository README and + AGENTS rules point back to `include/marqdo_plugin_abi_v1.h`, + `spec/plugin-abi.md` and the pinned commit. +- The existing security statement remains: a C ABI is not a sandbox, and native + loading requires explicit trust; the SDK grants no capability. + +## Verification (candidate) + +- SDK repository commit `b31187a` on `main`: + - clean-clone `cargo build --locked` and `cargo test --locked` pass; + - the fixture builds with only the SDK; + - `tools/check_with_frozen_cli.py --marqdo-bin ` + returns `Int 42` and rejects a tampered artifact digest. +- CLI candidate removes the SDK crate, fixture and CLI-side gate; workspace + tests, architecture boundaries, docs consistency and dependency gates pass; + the SDK no longer appears in the workspace or lock file. +- Full evidence: `docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md`. + +## Rejected alternatives + +- **Keep the SDK in the CLI workspace** while calling the contract "decoupled": + leaves two release cadences and ownership in one repo; issue #15 cannot close. +- **Git submodule/gitlink into the CLI repo**: CLI does not consume the SDK, so + a submodule would create an unnecessary recursive identity and checkout + failure mode. +- **Relative path dependency `../cli`**: not an independent build; forbidden by + issue #13 §6.2. +- **Copy `marqdo-plugin-abi`/Value Wire into the SDK repo**: would create a + second contract and wire encoder authority. +- **Publish the contract to a registry first**: no registry/release channel is + approved here; the public git `rev` is the available precise input. A future + published artifact can replace the git `rev` without changing authority. + +## Consequences and rollback + +- The architecture map now shows one CLI contract producer and one independent + SDK consumer; CLI CI no longer carries SDK-only checks, and SDK CI owns them. +- The SDK remains pinned to a CLI merge commit. Changing the contract or + advancing the pin is a deliberate cross-repository change with its own + evidence; a contract change must land in the CLI first, then the SDK pin is + bumped. +- Rollback is a complete known-good combination: keep the CLI commit and the SDK + pin that were verified together; do not restore a copied SDK or an old ABI. +- External SDK consumers can fetch the public CLI contract today. If a + registry-published contract or a different visibility policy is later chosen, + that is a new ADR, not an implicit change. diff --git a/docs/adr/README.md b/docs/adr/README.md index 504dfa8..436edd9 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -73,3 +73,6 @@ Files: `0001`–`0050`, plus: * [0071](0071-engine-host-contract-boundary.md) — Engine / Host Contract / 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`. diff --git a/docs/architecture/CURRENT.md b/docs/architecture/CURRENT.md index b4a3e79..78461a9 100644 --- a/docs/architecture/CURRENT.md +++ b/docs/architecture/CURRENT.md @@ -48,7 +48,6 @@ 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 | @@ -208,7 +207,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) -marqdo-plugin-sdk -> marqdo-plugin-abi (contract only) +[cflmy/marqdo-plugin-sdk] -> cflmy/marqdo-cli#marqdo-plugin-abi @ pinned rev marqdo-provider-worker -> marqdo-worker-ipc ``` @@ -326,7 +325,7 @@ 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` | Contract decoupled; physical move to an independent repository is a follow-up after the §6.3 external build and pinned-artifact mechanism | A clean-directory build against a fixed contract revision without the CLI checkout passes (S07/S08) | +| `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 | | 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 | @@ -358,6 +357,8 @@ 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. - [Issue #13 engine/host evidence](../evidence/2026-11-26-issue-13-engine-host-boundary.md) — executed candidate commands and results. - [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. diff --git a/docs/architecture/README.md b/docs/architecture/README.md index c606f37..694692f 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -83,7 +83,8 @@ 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, keep-in-workspace repository decision | +| 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 | | 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 e4744ea..14ac6a8 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -34,7 +34,6 @@ 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 d771621..7fbff30 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, SDK/header | +| High-performance native callable functions | Callable Plugin ABI v1 | `plugin.yaml`, host-targeted library, public SDK (`cflmy/marqdo-plugin-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 -`python3 tools/ci/check_plugin_sdk.py` with the Rust suits. Do not create an +the independent SDK repository's frozen-CLI check 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 1efecb5..66706b6 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 | +| 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`) | | 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 new file mode 100644 index 0000000..d8c2988 --- /dev/null +++ b/docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md @@ -0,0 +1,78 @@ +# Evidence — issue #15 independent `marqdo-plugin-sdk` repository + +Date: 2026-11-26 (Asia/Shanghai) +Tracking issue: +Decision: [ADR-0072](../adr/0072-sdk-independent-repository.md) +Parent: issue #13 / [ADR-0071](../adr/0071-engine-host-contract-boundary.md) + +## Topology and identity + +| Object | Exact identity | +|---|---| +| SDK repository | `cflmy/marqdo-plugin-sdk` (public), `main` at `b31187a` | +| CLI contract input | `marqdo-plugin-abi` from `https://git.cflmy.cn/cflmy/marqdo-cli.git` `rev = 2585915e16906dac75f8571bed02e7f6f868c6bc` (merge of PR #14) | +| CLI candidate | `architecture/sdk-independent-repository`; PR/CI SHA recorded by the PR | +| Frozen CLI acceptance binary | `marqdo` 3.0.0-rc.4 Linux x86_64 release archive, SHA-256 from the release `.sha256` asset | +| ABI | Plugin ABI 1.0 / Value Wire 1 / package + provider formats unchanged | + +The SDK repository is its own Cargo workspace and lock. The CLI does not depend +on it, and the SDK does not depend on the CLI checkout, the native host, a +loader/worker, a sandbox or the CLI product. + +## SDK repository verification (clean clone, independent of CLI checkout) + +Commands run in a fresh `git clone https://git.cflmy.cn/cflmy/marqdo-plugin-sdk.git` +outside this repository: + +| Gate | Command | Result | +|---|---|---| +| Locked build | `cargo build --locked` | PASS (contract fetched from the pinned public CLI git `rev`) | +| SDK tests | `cargo test --locked` | PASS (4 unit tests + 1 doc-test, 2 ignored doc examples) | +| Third-party fixture | `cargo build --locked --manifest-path tests/fixture/Cargo.toml` | PASS (built only from the SDK) | +| Frozen CLI invocation (S04/S07) | `python3 tools/check_with_frozen_cli.py --marqdo-bin frozen/marqdo` | PASS — real CLI returns `Int 42` | +| Tampered artifact (S05/S06) | same script, `sha256` replaced | PASS — rejected with artifact/sha256 diagnostic | + +The frozen binary was the released 3.0.0-rc.4 archive, not a locally rebuilt CLI; +the plugin ABI is unchanged across the #13 decoupling, which is exactly the +cross-repository compatibility being tested. + +SDK repository CI (`.woodpecker/main.yml`) repeats the workspace checks, the +fixture build and the frozen-CLI integration after downloading that released +archive. Enabling the Woodpecker project/webhook for the new repository is a +repository-administration step outside this change; the pipeline definition is +checked in and the same commands were executed manually above. + +## CLI repository verification (this change) + +| Gate | Command | Result | +|---|---|---| +| Workspace resolution | `cargo check --workspace --locked` | PASS; `marqdo-plugin-sdk` no longer appears in `Cargo.lock` | +| Formatting | `cargo fmt --all -- --check` | PASS | +| Clippy | `cargo clippy --workspace --all-targets --locked -- -D warnings` | PASS | +| Rust tests | `cargo test --workspace --locked --no-fail-fast` | PASS — 631 passed / 0 failed / 0 ignored (the removed SDK 4 unit + 1 doc test now run in the SDK repository; the two previously ignored SDK doc examples moved with them) | +| Architecture boundaries | `cargo test -p marqdo-cli --test architecture_boundaries --locked` | PASS — SDK absence/moved-repository assertion | +| Docs consistency | `cargo test -p marqdo-cli --test docs_consistency --locked` | PASS | +| Dependency direction | `python3 tools/ci/check_dependency_boundaries.py` | PASS — SDK no longer a workspace member; negative case added | +| Tools unit tests | `python3 -m unittest discover -s tools/ci -p "test_*.py"` | PASS | +| Engine differential | `python3 tools/ci/check_engine_boundary.py` | PASS (unchanged) | + +Removed from the CLI workspace/repository in the same integration: + +- `crates/marqdo-plugin-sdk/` (moved to the independent repository); +- `tests/sdk-plugin/` (fixture moved to `tests/fixture` in the SDK repository); +- `tools/ci/check_plugin_sdk.py` (its superset lives in the SDK repository and + uses a frozen CLI binary); +- workspace/lock entry, architecture/layer docs, CI lane entries and current + developer references. + +## Not verified / follow-ups + +- **Woodpecker activation** for the new public repository is administrative; the + pipeline definition is committed, but no remote pipeline run is claimed here. +- **Registry publication** of the contract crate is not introduced; the public + CLI git `rev` is the precise, fetchable input. A future published artifact + would be a new decision and would not change contract authority. +- Engine/Native Host remain in the CLI workspace under ADR-0071; this split does + not reopen that decision. +- No second ABI, wire encoder, loader or host copy exists in the SDK repository; + no compatibility/submodule path was added to the CLI repository. diff --git a/log.txt b/log.txt deleted file mode 100644 index e69de29..0000000 diff --git a/out b/out deleted file mode 100644 index 45dc425..0000000 --- a/out +++ /dev/null @@ -1 +0,0 @@ -{"id":186,"number":102,"author":"cflmy","parent":100,"event":"push","event_reason":null,"status":"pending","errors":null,"created":1795689775,"updated":1795689775,"started":0,"finished":0,"deploy_to":"","deploy_task":"","commit":"9b4f0a08228e9932bf3b0a8c5cf80e0d04626ccb","branch":"architecture/issue-13-engine-host-boundary","rerun_count":1,"ref":"refs/heads/architecture/issue-13-engine-host-boundary","refspec":"","author_avatar":"https://git.cflmy.cn/avatars/a03c2a29ffe40645c340184922645d9774759236871a8ba9a7fb1f6bd87f31ef","forge_url":"https://git.cflmy.cn/cflmy/marqdo-cli/commit/9b4f0a08228e9932bf3b0a8c5cf80e0d04626ccb","reviewed_by":"","reviewed":0,"workflows":[{"id":150,"pipeline_id":186,"pid":1,"name":"main","state":"pending","children":[{"id":513,"uuid":"01M8BQ708CS0DNFASR3FCFFBQ6","pipeline_id":186,"pid":2,"ppid":1,"name":"clone","state":"pending","exit_code":0,"type":"clone"},{"id":514,"uuid":"01M8BQ708CS0DNFASR3HYYVV9B","pipeline_id":186,"pid":3,"ppid":1,"name":"contract","state":"pending","exit_code":0,"type":"commands"},{"id":515,"uuid":"01M8BQ708CS0DNFASR3MCRV9KH","pipeline_id":186,"pid":4,"ppid":1,"name":"test","state":"pending","exit_code":0,"type":"commands"},{"id":516,"uuid":"01M8BQ708CS0DNFASR3QDE0WCS","pipeline_id":186,"pid":5,"ppid":1,"name":"minimum-rust","state":"pending","exit_code":0,"type":"commands"},{"id":517,"uuid":"01M8BQ708CS0DNFASR3R5CWAKR","pipeline_id":186,"pid":6,"ppid":1,"name":"build","state":"pending","exit_code":0,"type":"commands","depends_on":["test","minimum-rust","contract"]}]}],"changed_files":["crates/marqdo-host-contract/Cargo.toml","crates/marqdo-host-contract/src/context.rs","crates/marqdo-host-contract/src/host.rs","crates/marqdo-host-contract/src/lib.rs","crates/marqdo-host-contract/src/observe.rs","crates/marqdo-host-contract/src/resource.rs","crates/marqdo-host/src/plugin/artifact.rs","crates/marqdo-host/src/plugin/loader.rs","crates/marqdo-host/src/plugin/manifest.rs","crates/marqdo-host/src/plugin/mod.rs","crates/marqdo-host/src/plugin/worker.rs","crates/marqdo-host/tests/loader_unix.rs","docs/adr/0071-engine-host-contract-boundary.md","docs/evidence/2026-11-26-issue-13-engine-host-boundary.md","tests/embedding/Cargo.lock","tests/embedding/Cargo.toml","tests/embedding/README.md","tests/embedding/program.mq.md","tests/embedding/src/main.rs","tests/sdk-plugin/Cargo.lock","tests/sdk-plugin/Cargo.toml","tests/sdk-plugin/call.mq.md","tests/sdk-plugin/src/lib.rs","tools/ci/check_dependency_boundaries.py","tools/ci/check_engine_boundary.py","tools/ci/check_plugin_sdk.py","tools/ci/test_dependency_boundaries.py","crates/marqdo-host/src/context.rs","crates/marqdo-plugin-abi/src/artifact.rs","crates/marqdo-plugin-abi/src/loader.rs","crates/marqdo-plugin-abi/src/manifest.rs","crates/marqdo-plugin-abi/src/worker.rs","crates/marqdo-plugin-abi/tests/loader_unix.rs",".github/workflows/ci.yml",".gitignore",".woodpecker/main.yml","AGENTS.md","Cargo.lock","Cargo.toml","README.md","crates/cli/Cargo.toml","crates/cli/src/commands.rs","crates/cli/src/commands/run.rs","crates/cli/src/commands/tool.rs","crates/cli/src/extension_descriptors.rs","crates/cli/src/extension_selection.rs","crates/cli/src/main.rs","crates/cli/src/observation.rs","crates/cli/src/provider_manifest.rs","crates/cli/tests/architecture_boundaries.rs","crates/cli/tests/callable_resolution.rs","crates/cli/tests/conformance_semantics.rs","crates/cli/tests/extension_selection.rs","crates/cli/tests/integration_cli.rs","crates/cli/tests/observation.rs","crates/cli/tests/plugin_worker.rs","crates/cli/tests/provider_cli.rs","crates/marqdo-host/Cargo.toml","crates/marqdo-host/src/host.rs","crates/marqdo-host/src/kernels.rs","crates/marqdo-host/src/lib.rs","crates/marqdo-host/src/observe.rs","crates/marqdo-host/src/plugin_worker.rs","crates/marqdo-host/src/process.rs","crates/marqdo-host/src/provider_c.rs","crates/marqdo-host/src/provider_worker.rs","crates/marqdo-host/src/resource.rs","crates/marqdo-host/tests/c_provider.rs","crates/marqdo-host/tests/capability_broker.rs","crates/marqdo-host/tests/observation.rs","crates/marqdo-host/tests/plugin_exports.rs","crates/marqdo-host/tests/resource_streams.rs","crates/marqdo-host/tests/worker_provider.rs","crates/marqdo-plugin-abi/Cargo.toml","crates/marqdo-plugin-abi/src/abi.rs","crates/marqdo-plugin-abi/src/lib.rs","crates/marqdo-provider-worker/Cargo.toml","crates/marqdo-provider-worker/tests/worker_binding.rs","crates/marqdo-runtime/Cargo.toml","crates/marqdo-runtime/src/builtins_impl.rs","crates/marqdo-runtime/src/interpreter.rs","crates/marqdo-runtime/src/lib.rs","crates/marqdo-runtime/tests/interpreter.rs","crates/marqdo-runtime/tests/observation.rs","docs/DEVELOPMENT_BLUEPRINT.md","docs/STATUS.md","docs/adr/README.md","docs/architecture/CURRENT.md","docs/architecture/README.md","docs/ci.md","docs/developers/README.md","examples/plugin-demo/README.md","spec/plugin-abi.md","spec/security.md","tests/README.md"],"version":"3.20.1","title":"","message":"refactor: extract neutral host contract and decouple plugin ABI (issue #13)\n\nImplements the core M0-M3 boundary work from issue #13 / ADR-0071 without\nchanging language semantics or any public protocol:\n\n- add marqdo-host-contract owning Host/HostOp/ExecutionContext/ResourceRead\n and the runtime observation facts; the engine depends on it only.\n- marqdo-runtime no longer links marqdo-host; the native host implements the\n contract and has no reverse edge to runtime/frontend/IR.\n- reduce marqdo-plugin-abi to the public C ABI/wire/error contract; move\n manifest/artifact/loader/worker execution into marqdo-host::plugin so the\n SDK carries no loader/worker/host dependency.\n- add a real independent consumer (tests/embedding, own workspace+lock) that\n runs Markdown -\u003e frontend -\u003e IR -\u003e runtime with bounded budgets and explicit\n effect refusal, plus differential CLI comparison.\n- add an SDK-only third-party plugin fixture and real CLI invocation gate.\n- replace the frozen-crate architecture test with a reviewed responsibility\n graph enforced from Cargo metadata, with negative unit cases.\n- consolidate current docs/entry: ADR-0071, CURRENT responsibility map,\n developers/architecture indexes, historical banners, STATUS and evidence.\n- record keep-in-workspace for Engine/Native Host; no empty candidate repo.\n\nEvidence: docs/evidence/2026-11-26-issue-13-engine-host-boundary.md\nRefs #13\n","timestamp":1795689423,"sender":"cflmy","author_email":"1+cflmy@noreply.localhost"} \ No newline at end of file diff --git a/tests/README.md b/tests/README.md index b25a288..da3c4f9 100644 --- a/tests/README.md +++ b/tests/README.md @@ -33,7 +33,6 @@ 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 ``` @@ -53,7 +52,6 @@ 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 deleted file mode 100644 index 0fcda55..0000000 --- a/tests/sdk-plugin/Cargo.lock +++ /dev/null @@ -1,198 +0,0 @@ -# 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 deleted file mode 100644 index b16e614..0000000 --- a/tests/sdk-plugin/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[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 deleted file mode 100644 index 660f932..0000000 --- a/tests/sdk-plugin/call.mq.md +++ /dev/null @@ -1,5 +0,0 @@ -## @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 deleted file mode 100644 index 7290f53..0000000 --- a/tests/sdk-plugin/src/lib.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! 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 7abda3c..9df8948 100644 --- a/tools/ci/check_dependency_boundaries.py +++ b/tools/ci/check_dependency_boundaries.py @@ -50,7 +50,6 @@ 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", @@ -240,22 +239,14 @@ def check_workspace(metadata: dict) -> list[str]: f"dependency `{forbidden}`" ) - 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]}" - ) + # 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)" + ) # 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 deleted file mode 100644 index 559c592..0000000 --- a/tools/ci/check_plugin_sdk.py +++ /dev/null @@ -1,164 +0,0 @@ -#!/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 565ec5d..3ec9bd2 100644 --- a/tools/ci/test_dependency_boundaries.py +++ b/tools/ci/test_dependency_boundaries.py @@ -82,7 +82,6 @@ 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"] @@ -185,10 +184,15 @@ class DependencyBoundaryTests(unittest.TestCase): "must not carry execution-side dependency `libloading`", ) - 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_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_undocumented_workspace_crate_is_rejected(self) -> None: