conformance fixtures: pure lib, plugin, kernel, provider, tool

This commit is contained in:
Marqdo Extension Fixtures committed 2026-11-21 23:41:32 +08:00
commit 40bf1f932e
31 files changed
+2361

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
# Build outputs (rebuilt by build.sh on each machine; never committed)
plugin/build/
provider/build/
kernel/mocklang.sha256
tests/__pycache__/
evidence/results.json
+61
View File
@@ -0,0 +1,61 @@
# Conformance contract
This repository targets the exact versions below. It makes no "latest version
works" claim. Unknown/newer protocol versions fail closed.
| Contract | Version used here | Required by |
|---|---|---|
| Marqdo Core CLI | `0.1.0` (frozen binary SHA recorded in `evidence/`) | all |
| Language semantics | RFC-LANG-0002 / ADR-0052 (one Markdown→program mapping) | `.mq.md` fixtures |
| Markdown profile | `marqdo.md.v1` | all documents |
| Plugin ABI | C ABI v1 (`MQ_ABI_MAJOR=1`, host target triple recorded in `plugin/build/plugin.yaml`) | `plugin/` |
| Plugin package manifest | `plugin.yaml` ABI v1 | `plugin/` |
| Value Wire | `wire_version: 1`, type-tagged JSON | plugin and foreign payloads |
| Foreign kernel descriptor | `kernel.json` v1 (`wire_version: 1`) | `kernel/` |
| Resource provider manifest | `marqdo.provider` schema v2, `transport: worker`, `abi: c-abi-1` | `provider/` |
| Resource provider worker protocol | ADR-0035 framed JSON (host ↔ helper) + C ABI v1 (helper ↔ library) | `provider/` |
| Analysis | Analysis v2 (`marqdo check --emit`) | `tool/` |
| Trace | Trace v2 (`marqdo run --trace-file`) | `tool/` |
| CLI Tool Protocol | v1 (`marqdo.cli-tool`, schema_version 1) | `tool/` |
## Platform matrix
| Lane | Status |
|---|---|
| Linux x86_64 (glibc) | **supported** — the mandatory conformance lane |
| macOS arm64/x86_64 | **unverified** by this repository unless `tests/run_all.py` is run there with a native build |
| Windows x86_64 | **unsupported** for plugin/provider C ABI in this fixture; the pure `.mq.md`, kernel and tool cases are portable but not claimed until run |
`plugin/build_all.sh` and `provider/build_all.sh` build for the *host* target
and write that target triple + artifact SHA-256 into the generated manifest;
the committed manifests contain zero digests and are templates only.
## Hash and identity rules
* Artifact SHA-256 is **integrity**, not publisher identity or a signature.
* `marqdo.lock` pins the pure-library Git commit by full 40-character SHA; the
consumer never resolves a branch or "latest".
* The plugin/provider manifests are matched against the static descriptor and
the loaded artifact; a changed byte fails before the entry function runs.
* Analysis/Trace evidence is consumed as public JSON only; no private Rust IR
is linked or copied.
## Grants and failure behaviour
| Extension | Explicit grant | Without grant | Without manifest |
|---|---|---|---|
| `.mq.md` package | none beyond project mode | n/a | unresolved import (static error) |
| Plugin | `--allow-plugin demo.ext` (+ `--plugin`) | `permission.denied` | `symbol.unknown` |
| Foreign kernel | `--allow-foreign` (+ `--kernel`) | `permission.denied` | `kernel.unavailable` |
| Provider | `--allow-provider demo.sensor` (+ `--provider`) | `permission.denied` | `resource.unsupported` |
| Tool | none (tool runs as its own process) | n/a | command is unknown |
`pure`/`strict` modes reject extension flags and third-party execution; this
repository never claims `strict` L2 or an OS sandbox for worker transports.
## Environment assumptions
Linux x86_64, Python 3 (stdlib only), a C compiler (`cc`), Git. No network is
required: the consumer test creates its pinned Git repository locally with
`git init` + `git commit` and a full SHA. No Node/Python runtime is required
for the kernel case: `mocklang` is a POSIX shell script.
+44
View File
@@ -0,0 +1,44 @@
# marqdo-extension-conformance
Independent, physically separate conformance fixtures for
[RFC-EXT-0001](../marqdo-cli/docs/architecture/RFC-EXT-0001.md): a third-party
repository that provides all five extension kinds **without modifying or
recompiling `marqdo-cli`**.
Everything here is built and executed by a *frozen* `marqdo` binary whose
absolute path is supplied as `$MARQDO_BIN`. No script in this repository runs
Cargo, links a Rust crate, reads `marqdo-cli`'s test fixtures, or writes into
the CLI workspace.
| Directory | Extension kind | Entry point |
|---|---|---|
| `pure-lib/` | `.mq.md` package (pinned Git) | `consumer/` project locks it by full SHA |
| `plugin/` | Callable ABI plugin (worker transport) | `plugin/plugin.yaml`, C ABI v1 |
| `kernel/` | Foreign kernel (`mocklang`) | `kernel/kernel.json`, one-shot process |
| `provider/` | Resource provider v2 (`demo.sensor`) | `provider/provider.json`, worker helper + C ABI |
| `tool/` | CLI Tool | `tool/tool.json`, `inspect-ext` command |
## Quick start
```bash
cargo build --release -p marqdo-cli # in ../marqdo-cli (once)
export MARQDO_BIN=/abs/path/to/target/release/marqdo
# Ship the provider helper sibling exactly as the release archive does:
cp /abs/path/to/target/release/marqdo-provider-worker "$(dirname "$MARQDO_BIN")"/
./scripts/build_all.sh
python3 tests/run_all.py # writes evidence/results.json
```
`tests/verify_frozen_cli.py` hashes `$MARQDO_BIN` before and after the suite and
fails if the binary changed. The committed `evidence/results.json` is generated,
not hand-edited; `evidence/manifest.json` is produced by the CLI repository's
`tools/ci/verify_extension_contracts.py`.
## Contract
See [`CONTRACT.md`](CONTRACT.md) for the exact language/ABI/wire/schema versions
and supported platform matrix. `plugin/include/marqdo_plugin_abi_v1.h` is a
verbatim copy of the public ABI header published by the CLI repository; the
provider ABI declarations are re-declared in `provider/src/sensor.c` from the
public C ABI specification because no separate provider header is published yet.
+8
View File
@@ -0,0 +1,8 @@
---
import:
m: "@math"
---
## @exec main
`return m.双倍面积(r=3)`
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Write kernel/build/kernel.json with the absolute host entrypoint digest.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
out="$here/build"
mkdir -p "$out"
chmod +x "$here/mocklang"
if command -v sha256sum >/dev/null 2>&1; then
hash="$(sha256sum "$here/mocklang" | cut -d' ' -f1)"
else
hash="$(shasum -a 256 "$here/mocklang" | cut -d' ' -f1)"
fi
cat > "$out/kernel.json" <<JSON
{
"provider_id": "mocklang-provider",
"languages": ["mocklang"],
"wire_version": 1,
"entrypoint": "$here/mocklang",
"permissions_requested": [],
"digest": "$hash"
}
JSON
echo "built $out/kernel.json (digest $hash)"
+13
View File
@@ -0,0 +1,13 @@
## @exec main
`结果 = foreign.call(ref("#代码"), {})`
`打印(结果.result)`
`return 结果.result`
### @knowledge 代码
```mocklang
a language tag marqdo-cli has never heard of; selected only by --kernel
```
+8
View File
@@ -0,0 +1,8 @@
{
"provider_id": "mocklang-provider",
"languages": ["mocklang"],
"wire_version": 1,
"entrypoint": "./mocklang",
"permissions_requested": [],
"digest": "0000000000000000000000000000000000000000000000000000000000000000"
}
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Minimal third-party foreign kernel: the language label "mocklang" is unknown
# to marqdo-cli. The host writes exactly one request envelope to stdin; this
# provider consumes it and emits exactly one type-tagged Value Wire value.
# Args: <source-file>
cat >/dev/null
printf '%s' '{"type":"map","entries":{"language":{"type":"text","value":"mocklang"},"result":{"type":"int","decimal":"42"}}}'
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Build the conformance plugin for the host target and generate a complete
# plugin.yaml (target triple + real artifact SHA-256). The tracked plugin.yaml
# is a zero-digest template and is never rewritten.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
out="$here/build"
mkdir -p "$out"
host="$(rustc -vV | sed -n 's/^host: //p')"
case "$host" in
*apple-darwin*) ext="dylib"; flags=(-dynamiclib -fPIC) ;;
*windows*) ext="dll"; flags=(-shared) ;;
*) ext="so"; flags=(-shared -fPIC) ;;
esac
artifact="plugin.$ext"
cc -std=c11 -O2 "${flags[@]}" -I "$here/include" -o "$out/$artifact" "$here/src/plugin.c"
if command -v sha256sum >/dev/null 2>&1; then
hash="$(sha256sum "$out/$artifact" | cut -d' ' -f1)"
else
hash="$(shasum -a 256 "$out/$artifact" | cut -d' ' -f1)"
fi
cat > "$out/plugin.yaml" <<YAML
plugin:
name: demo.ext
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
- name: solver.add
signature: "(\$a: Int, \$b: Int) -> Int"
- name: solver.neg
signature: "(\$a: Int) -> Int"
- name: quant.scale
signature: "(\$a: Int) -> Int"
requires:
- math.compute
artifacts:
- target: $host
file: $artifact
sha256: "$hash"
YAML
echo "built $out/$artifact for $host (sha256 $hash)"
+15
View File
@@ -0,0 +1,15 @@
## @exec main
`和 = solver.add(20, b=22)`
`相反数 = solver.neg(a=7)`
`缩放 = quant.scale(a=5)`
`打印(和)`
`打印(相反数)`
`打印(缩放)`
`return 和`
+472
View File
@@ -0,0 +1,472 @@
/*
* Marqdo plugin C ABI, generation v1.
* =====================================================================
*
* This header is the canonical, frozen description of the Marqdo native
* plugin ABI v1. It is an independent ABI generation: it is *not* the old
* `marqdo_abi.h` v2 interface and is neither source- nor binary-compatible
* with it. Only an explicit, separately tested adapter may ever bridge the
* two.
*
* This file defines stable-layout C types only:
*
* - fixed-width integers (`int32_t`, `uint32_t`) and `size_t`,
* - byte buffers represented as length + pointer (`MqBytes` /
* `MqOwnedBytes`),
* - opaque, host-owned handles (`MqCallContext`),
* - `extern "C"` function pointers.
*
* The following must NEVER cross this boundary:
*
* - Rust `String` / `Vec` / `Result` / trait objects / panics,
* - C++ exceptions, Go runtime objects or garbage-collected pointers,
* - raw pointers to host-internal structures (other than the opaque
* `MqCallContext *` minted for one invocation),
* - real filesystem handles, sockets, keys or OS resources; capabilities
* are requested symbolically through `MqHostApi::request_capability`.
*
* A C ABI IS NOT A SANDBOX
* ------------------------
* Native plugins are loaded into the host process. They are not isolated:
* a plugin can read host memory, call arbitrary syscalls, crash the process
* or corrupt the host. In-process native loading therefore requires an
* explicit user trust decision. Untrusted third-party plugins must run in an
* isolated worker process (same logical plugin API, length-prefixed IPC
* transport) or a Wasm component. Do not present this ABI as a security
* boundary.
*
* VERSIONS
* --------
* Three independent versions exist and must never be conflated:
*
* 1. Marqdo language / syntax / semantics version,
* 2. plugin ABI major.minor (this header, `MQ_ABI_MAJOR`/`MQ_ABI_MINOR`),
* 3. plugin package SemVer (declared in `plugin.yaml`).
*
* This header is ABI major 1, minor 0.
*
* TARGET AND WORD SIZE
* --------------------
* The layout below uses `size_t`, so it depends on the target triple and the
* pointer width. A plugin artifact is only loadable by a host built for the
* same target triple and the same pointer width (32-bit and 64-bit objects
* are never interchangeable). All struct fields use native endianness;
* host and plugin must share the target byte order. The JSON wire payloads
* are UTF-8 and endian-neutral.
*
* LAYOUT EXPECTATIONS (little/big-endian, size_t == 8 bytes)
* ---------------------------------------------------------
* sizeof(MqBytes) == 16, alignof == 8
* sizeof(MqOwnedBytes) == 16, alignof == 8
* sizeof(MqPluginApi) == 32, alignof == 8
* sizeof(MqHostApi) == 56, alignof == 8
* sizeof(MqPluginInvoke) == 8
* The same expectations are asserted in `crates/marqdo-plugin-abi`.
*
* BUFFER OWNERSHIP AND LIFETIMES
* ------------------------------
* There are three distinct kinds of byte buffer:
*
* (a) Host-owned input buffers (`args_wire`, capability `request_wire`,
* `export_name`, `signature_wire`, `plugin_metadata_wire` as watched by
* the host). The producer of the pointer keeps it valid only for the
* duration of the call in which it is passed. The consumer MUST NOT
* retain the pointer, MUST NOT free it and MUST copy any data it needs
* to keep. In particular the host copies plugin metadata, export names
* and signatures during the entry/registration call.
*
* (b) Host-allocated output buffers. The host owns `alloc`/`free`. A plugin
* that produces `MqOwnedBytes` output (`result_wire`, `error_wire`,
* capability `reply_wire`) MUST allocate the memory with
* `host->alloc(host->host_data, size)` and write the payload there. The
* consuming side (host for invoke results/errors, plugin for capability
* replies) copies what it needs and then releases the buffer with
* `host->free(host->host_data, data)`. The producer MUST NOT free the
* buffer itself and MUST NOT use `malloc`/`new`/GC memory for it.
*
* (c) Plugin-owned static metadata. During `mq_plugin_entry_v1` the plugin
* passes `plugin_metadata_wire` pointing at storage it owns (typically a
* static string). It only has to remain valid for the duration of the
* entry call; the host copies it.
*
* Zero-length semantics: a buffer with `len == 0` must have `data == NULL`
* (hosts and plugins must treat `{NULL, 0}` as the empty buffer). A buffer
* with `len > 0` must have a non-NULL `data`. Violations are protocol errors
* (`MQ_ERR_INVALID_ARGUMENT` / `MQ_ERR_BAD_WIRE`), never silent.
*
* SIZE LIMITS (enforced by the host; plugins should fail fast)
* -----------------------------------------------------------
* MQ_MAX_EXPORT_NAME_BYTES 256
* MQ_MAX_SIGNATURE_WIRE_BYTES 4096
* MQ_MAX_METADATA_WIRE_BYTES 65536
* MQ_MAX_REQUEST_WIRE_BYTES 8384512 (8 MiB - 4096)
* MQ_MAX_RESULT_WIRE_BYTES 8384512 (8 MiB - 4096)
* MQ_MAX_ERROR_WIRE_BYTES 1048576 (1 MiB)
* MQ_MAX_CAPABILITY_REPLY_BYTES 8384512 (8 MiB - 4096)
* JSON depth is additionally limited to 64 levels. Requests/results that
* exceed these limits are rejected with a structured error; they must not
* be truncated and reparsed.
*
* ERROR FIELD BEHAVIOUR
* ---------------------
* `mq_plugin_entry_v1` returns `MQ_OK` (0) on success, a non-zero
* `MQ_ERR_*` code on failure. On a non-zero return the host MUST NOT read
* `plugin_metadata_wire`, `plugin_api.abi_*` or any registered callback.
*
* `MqPluginInvoke` returns `MQ_OK` (0) on success and a non-zero code on
* failure:
* - on success, `*result_wire` holds exactly one UTF-8 JSON response
* envelope (see `spec/value-wire.md` / wire_version 1) and
* `*error_wire` MUST be `{NULL, 0}`;
* - on failure, `*error_wire` holds a UTF-8 JSON error envelope
* (`{ "wire_version": 1, "kind": "response", "error": {...} }`) and
* `*result_wire` MUST be `{NULL, 0}`. The host treats a missing error
* envelope as an unstructured plugin failure and still fails the call.
* Both output pointers MUST be non-NULL as provided by the host; writing
* through a NULL output pointer is a caller/plugin contract violation.
*
* OOM / NULL ALLOCATION: `host->alloc` returns NULL on failure (and for
* `size == 0`). A plugin that cannot allocate must return
* `MQ_ERR_OUT_OF_MEMORY` and must not write partial output buffers.
*
* THREAD MODEL
* ------------
* v1 is deliberately single-threaded and synchronous:
* - `mq_plugin_entry_v1` is called exactly once, by the loading thread;
* - every `MqPluginInvoke` and every host callback for a given loaded
* plugin instance runs on that same thread;
* - at most one invocation is in flight per instance; the host serializes
* calls. A plugin must not start its own threads that call back into
* `MqHostApi`, and must not invoke the host from a signal handler;
* - there is no async/parallel callback contract in v1. `MqCallContext`
* is valid only for the duration of the invocation it was minted for,
* must not be cached, and must not be used after the call returns.
*
* UNLOADING / SHUTDOWN
* --------------------
* v1 does not support hot-unload or reload of a loaded native library.
* A plugin lives for the lifetime of the process (or of the trusted loading
* scope); there is no `shutdown` callback in v1. Hosts must not unload a
* library while a call is in flight, and must keep all registered function
* pointers reachable until shutdown. Plugins must tolerate never being
* unloaded.
*
* VERSION NEGOTIATION
* -------------------
* The host fills `MqPluginApi::struct_size` with sizeof(MqPluginApi) before
* the entry call and zeroes the remaining fields; the plugin fills in
* `abi_major`, `abi_minor` and `plugin_metadata_wire`. The host then:
* - rejects the load if `plugin->abi_major != MQ_ABI_MAJOR` (major is
* never negotiated);
* - accepts a plugin minor greater than its own, but clamps to the host's
* supported minor and only uses features defined at that minor.
* The plugin mirrors the check against the host table:
* - reject if `host == NULL`, `plugin == NULL`,
* `host->struct_size < sizeof(MqHostApi)` (the exact size of the v1.0
* table it was built against) or `host->abi_major != MQ_ABI_MAJOR`.
* `struct_size` is the extension mechanism: a consumer must only read a
* field when `struct_size >= offsetof(field) + sizeof(field)`; a producer
* sets `struct_size = sizeof(its struct)` and may append new fields only in
* a later ABI minor while never reordering or resizing earlier fields.
* Fields appended in a later minor are ABSENT (not usable) when the
* negotiated minor is lower.
*
* EXCEPTIONS, PANICS, UNDEFINED BEHAVIOUR
* ---------------------------------------
* No panic, exception, longjmp or unwinding of any kind may cross the ABI
* boundary. Rust plugins should call `extern "C"` entry points from
* panic-aborting builds or catch panics inside the SDK; C++ plugins must
* catch all exceptions inside their invocation function. The host treats a
* process crash as a host process crash: this ABI cannot contain it.
*
* WIRE FORMAT
* -----------
* All payloads are UTF-8 JSON, `wire_version == 1`. See the canonical
* `spec/value-wire.md` (type-tagged values: every value is an object with a
* `type` tag; 64-bit-and-beyond integers use decimal strings; NaN/Infinity
* use explicit tags). Names:
* - request : {"wire_version":1,"kind":"request","function":...,
* "args":{...},"context":{...}}
* - response : {"wire_version":1,"kind":"response","value":{...}}
* - error : {"wire_version":1,"kind":"response","error":
* {"kind":"...","code":"...","message":"...",...}}
* `export_name` and capability `name` are UTF-8 byte strings (not JSON).
* `signature_wire` is the JSON object {"signature":"<signature string>"}.
* `plugin_metadata_wire` is the JSON object
* {"name":"<plugin name>","version":"<semver>"} (extra fields ignored).
*/
#ifndef MARQDO_PLUGIN_ABI_V1_H
#define MARQDO_PLUGIN_ABI_V1_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ------------------------------------------------------------------ */
/* Version and result codes */
/* ------------------------------------------------------------------ */
/** Plugin ABI major version. Major mismatches always fail the load. */
#define MQ_ABI_MAJOR 1u
/** Plugin ABI minor version implemented by this header. */
#define MQ_ABI_MINOR 0u
/** Human-readable ABI version of this header. */
#define MQ_ABI_VERSION_STRING "1.0"
/** Required exported symbol name. */
#define MQ_PLUGIN_ENTRY_SYMBOL "mq_plugin_entry_v1"
/** Success. */
#define MQ_OK 0
/** Malformed argument (NULL pointer, bad pointer/length pair, ...). */
#define MQ_ERR_INVALID_ARGUMENT 1
/** ABI major mismatch or incompatible struct_size. */
#define MQ_ERR_ABI_MISMATCH 2
/** A required export could not be registered. */
#define MQ_ERR_REGISTRATION 3
/** Operation/type/capability not supported by this version. */
#define MQ_ERR_UNSUPPORTED 4
/** Host allocation failed. */
#define MQ_ERR_OUT_OF_MEMORY 5
/** Payload is not valid wire_version 1 JSON. */
#define MQ_ERR_BAD_WIRE 6
/** Unexpected internal plugin failure (including caught panics). */
#define MQ_ERR_INTERNAL 7
/** Capability request failed or was denied by the host. */
#define MQ_ERR_CAPABILITY 8
/* ------------------------------------------------------------------ */
/* Size limits */
/* ------------------------------------------------------------------ */
#define MQ_MAX_EXPORT_NAME_BYTES 256u
#define MQ_MAX_SIGNATURE_WIRE_BYTES 4096u
#define MQ_MAX_METADATA_WIRE_BYTES 65536u
#define MQ_MAX_REQUEST_WIRE_BYTES ((8u * 1024u * 1024u) - 4096u)
#define MQ_MAX_RESULT_WIRE_BYTES ((8u * 1024u * 1024u) - 4096u)
#define MQ_MAX_ERROR_WIRE_BYTES (1024u * 1024u)
#define MQ_MAX_CAPABILITY_REPLY_BYTES ((8u * 1024u * 1024u) - 4096u)
/* ------------------------------------------------------------------ */
/* Stable-layout buffer types */
/* ------------------------------------------------------------------ */
/**
* Borrowed, immutable byte view.
*
* Ownership stays with the producer; the pointer is valid only for the
* duration of the call that received it. `{NULL, 0}` is the empty buffer.
* A non-NULL `data` with `len == 0` is tolerated by neither side.
*/
typedef struct {
const uint8_t *data;
size_t len;
} MqBytes;
/**
* Mutable byte buffer ownership transfer.
*
* The producer allocates with `MqHostApi::alloc` and passes ownership to the
* consumer, which copies the bytes and then calls `MqHostApi::free` on
* `data`. `{NULL, 0}` is the empty buffer. A buffer left non-empty when the
* call returns is owned by the documented consumer; it is never freed by
* the producer.
*/
typedef struct {
uint8_t *data;
size_t len;
} MqOwnedBytes;
/**
* Opaque, host-owned invocation context.
*
* The plugin only ever receives a pointer to this type and must pass the
* same pointer back to `request_capability`. Its layout is private to the
* host and may change between ABI minors without notice. It is valid only
* during the invocation it was minted for and must not be cached, copied or
* inspected. Never dereference this pointer from a plugin.
*/
typedef struct MqCallContext MqCallContext;
/* ------------------------------------------------------------------ */
/* Function pointer types */
/* ------------------------------------------------------------------ */
/**
* Plugin invocation callback, registered once per export.
*
* Contract: see the ERROR FIELD BEHAVIOUR section above. The callback runs
* on the host invocation thread, with at most one call in flight per plugin
* instance. It must be reentrant-safe with respect to its own state because
* repeated invocations may occur sequentially. It must not panic/throw.
*
* @param ctx Opaque host context for this call (may be NULL only
* if the host could not mint one; then the plugin should
* fail with MQ_ERR_INVALID_ARGUMENT).
* @param args_wire Borrowed UTF-8 JSON request envelope.
* @param result_wire Host-provided out-parameter; on success must be
* filled with a host-allocated UTF-8 JSON response
* envelope. Must not be NULL.
* @param error_wire Host-provided out-parameter; on failure must be filled
* with a host-allocated UTF-8 JSON error envelope. Must
* not be NULL.
* @return MQ_OK on success, a non-zero MQ_ERR_* code otherwise.
*/
typedef int32_t (*MqPluginInvoke)(
MqCallContext *ctx,
MqBytes args_wire,
MqOwnedBytes *result_wire,
MqOwnedBytes *error_wire
);
/* ------------------------------------------------------------------ */
/* Host API table */
/* ------------------------------------------------------------------ */
/**
* Host-provided function table, valid for the whole life of the plugin
* instance. All function pointers are non-NULL in ABI v1.0.
*
* `host_data` is an opaque host-owned pointer that must be passed back to
* every function that takes it. Plugins must not interpret it.
*/
typedef struct {
/**
* sizeof(MqHostApi) as seen by the host. Consumers must check this
* against their own required size before reading any field (see VERSION
* NEGOTIATION). Producers never shrink the table; fields are only
* appended and never reordered.
*/
uint32_t struct_size;
/** Host-supported ABI major (must be MQ_ABI_MAJOR). */
uint32_t abi_major;
/** Host-supported ABI minor (features above this are unavailable). */
uint32_t abi_minor;
/** Opaque host state; pass back to every callback that accepts it. */
void *host_data;
/**
* Host allocator. Returns NULL on failure and for `size == 0`.
* The returned memory is at least `size` bytes and suitably aligned for
* byte buffers. The matching `free` must be used; never free with
* malloc/new/free() from the plugin runtime.
*/
void *(*alloc)(void *host_data, size_t size);
/**
* Host deallocator; must be called exactly once for a pointer returned by
* `alloc` (including capability replies allocated by the host). Passing
* NULL is a no-op.
*/
void (*free)(void *host_data, void *ptr);
/**
* Register one plugin export during `mq_plugin_entry_v1`.
*
* `export_name` is a UTF-8 dotted name, already namespaced by the
* manifest validation (e.g. "solver.add"). `signature_wire` is UTF-8
* JSON: {"signature":"(...)"}. Name and signature are copied by the
* host during this call. Returns MQ_OK or a non-zero MQ_ERR_* code; on
* failure the export must be considered not registered.
*
* Export names must not shadow Marqdo built-ins and must match the
* manifest exports exactly.
*/
int32_t (*register_function)(
void *host_data,
MqBytes export_name,
MqBytes signature_wire,
MqPluginInvoke invoke
);
/**
* Request a whitelisted capability from the host for the current call.
*
* `name` is a UTF-8 capability name (e.g. "math.compute", "fs.read",
* "clock"). `request_wire` is a UTF-8 JSON capability request whose shape
* is defined per capability. On success the host allocates
* `reply_wire` (with `alloc`) and the plugin must copy and then free it
* with `free`. On failure `reply_wire` is `{NULL, 0}` and the call
* returns a non-zero code.
*
* Capabilities are granted structurally by the host's authorization
* layer before the plugin is loaded; this function only consumes a grant
* and can never escalate privileges. `ctx` must be the context of the
* current invocation only.
*/
int32_t (*request_capability)(
MqCallContext *ctx,
MqBytes name,
MqBytes request_wire,
MqOwnedBytes *reply_wire
);
} MqHostApi;
/* ------------------------------------------------------------------ */
/* Plugin API table (host-filled, plugin-filled) */
/* ------------------------------------------------------------------ */
/**
* Plugin-side version/metadata table.
*
* The host initializes `struct_size` to sizeof(MqPluginApi) and zeroes the
* rest before calling the entry point. The plugin must set `abi_major`,
* `abi_minor` and `plugin_metadata_wire` and must not change
* `struct_size` (it may only be larger in a future ABI minor; consumers
* check it).
*/
typedef struct {
/** sizeof(MqPluginApi) as initialized by the host. */
uint32_t struct_size;
/** Plugin ABI major; must equal MQ_ABI_MAJOR for the load to proceed. */
uint32_t abi_major;
/** Plugin ABI minor; the host clamps and negotiates down as needed. */
uint32_t abi_minor;
/**
* Plugin metadata JSON, plugin-owned static storage, valid only for the
* duration of the entry call. Format:
* {"name":"<plugin name>","version":"<semver>"}
* The host copies it during the call. Must be a non-empty, valid UTF-8
* JSON object.
*/
MqBytes plugin_metadata_wire;
} MqPluginApi;
/**
* Required exported entry point. Exactly one per plugin artifact.
*
* @param host Host API table, host-owned, valid for the plugin lifetime.
* Must be non-NULL.
* @param plugin Plugin API table, host-provided. The plugin must fill it in
* and may not retain it. Must be non-NULL.
* @return MQ_OK on success, a non-zero MQ_ERR_* code on failure.
*
* The host calls this exactly once on the loading thread. The plugin
* registers every export through `host->register_function` during this call
* and must return MQ_OK only after all exports are registered successfully.
*/
typedef int32_t (*MqPluginEntryV1)(const MqHostApi *host, MqPluginApi *plugin);
#ifdef __cplusplus
} /* extern "C" */
#endif
/*
* Compile-time layout checks for the canonical 64-bit target. On other word
* sizes the expected sizes are smaller (every pointer/size_t shrinks by 4
* bytes); the Rust side asserts the corresponding architecture-specific
* values.
*/
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
#if defined(__LP64__) || defined(_LP64)
_Static_assert(sizeof(MqBytes) == 16, "MqBytes layout must stay 16 bytes on 64-bit");
_Static_assert(sizeof(MqOwnedBytes) == 16, "MqOwnedBytes layout must stay 16 bytes on 64-bit");
_Static_assert(sizeof(MqPluginApi) == 32, "MqPluginApi layout must stay 32 bytes on 64-bit");
_Static_assert(sizeof(MqHostApi) == 56, "MqHostApi layout must stay 56 bytes on 64-bit");
#endif
#endif
#endif /* MARQDO_PLUGIN_ABI_V1_H */
+3
View File
@@ -0,0 +1,3 @@
## @exec main
`return solver.add(a=1)`
+3
View File
@@ -0,0 +1,3 @@
## @exec main
`return solver.subtract(a=1, b=2)`
+20
View File
@@ -0,0 +1,20 @@
# Template only. build.sh writes build/plugin.yaml with the host target triple
# and the real artifact SHA-256; the zero digest here is never loadable.
plugin:
name: demo.ext
version: 0.1.0
abi: "^1.0"
kind: worker
exports:
- name: solver.add
signature: "($a: Int, $b: Int) -> Int"
- name: solver.neg
signature: "($a: Int) -> Int"
- name: quant.scale
signature: "($a: Int) -> Int"
requires:
- math.compute
artifacts:
- target: x86_64-unknown-linux-gnu
file: plugin.so
sha256: "0000000000000000000000000000000000000000000000000000000000000000"
+229
View File
@@ -0,0 +1,229 @@
/*
* Conformance plugin for Marqdo plugin ABI v1 (worker transport).
*
* Independent third-party source: it only depends on the published
* `marqdo_plugin_abi_v1.h` header (copied verbatim into ../include). It is
* built for the host target by build.sh, which also writes the target triple
* and artifact SHA-256 into the generated plugin manifest. The committed
* plugin.yaml is a template with zero digests.
*
* Exports:
* solver.add(Int, Int) -> Int
* solver.neg(Int) -> Int
* quant.scale(Int) -> Int
*/
#include "marqdo_plugin_abi_v1.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char METADATA[] = "{\"name\":\"demo.ext\",\"version\":\"0.1.0\"}";
static const MqHostApi *g_host = NULL;
static const char *find_key(const char *json, const char *key) {
size_t key_len = strlen(key);
const char *cursor = json;
while ((cursor = strchr(cursor, '"')) != NULL) {
const char *name_start = cursor + 1;
const char *name_end = strchr(name_start, '"');
const char *after;
if (name_end == NULL) {
return NULL;
}
if ((size_t)(name_end - name_start) != key_len ||
memcmp(name_start, key, key_len) != 0) {
cursor = name_end + 1;
continue;
}
after = name_end + 1;
while (*after == ' ' || *after == '\t' || *after == '\n' || *after == '\r') {
after++;
}
if (*after != ':') {
return NULL;
}
after++;
while (*after == ' ' || *after == '\t' || *after == '\n' || *after == '\r') {
after++;
}
return after;
}
return NULL;
}
static const char *find_object_value(const char *json, const char *name) {
const char *value = find_key(json, name);
return (value != NULL && *value == '{') ? value : NULL;
}
static int read_int_argument(const char *json, const char *name, long long *out) {
const char *args = find_object_value(json, "args");
const char *argument;
const char *decimal;
char buffer[32];
size_t length;
char *end = NULL;
if (args == NULL) {
return -1;
}
argument = find_object_value(args, name);
if (argument == NULL) {
return -1;
}
decimal = find_key(argument, "decimal");
if (decimal == NULL || *decimal != '"') {
return -1;
}
length = (size_t)(strchr(decimal + 1, '"') - (decimal + 1));
if (length == 0 || length + 1 > sizeof(buffer)) {
return -1;
}
memcpy(buffer, decimal + 1, length);
buffer[length] = '\0';
*out = strtoll(buffer, &end, 10);
return (end != NULL && *end == '\0') ? 0 : -1;
}
static int32_t emit(const char *json, size_t len, MqOwnedBytes *out) {
uint8_t *buffer;
if (g_host == NULL || out == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
buffer = (uint8_t *)g_host->alloc(g_host->host_data, len);
if (buffer == NULL) {
return MQ_ERR_OUT_OF_MEMORY;
}
memcpy(buffer, json, len);
out->data = buffer;
out->len = len;
return MQ_OK;
}
static int32_t fail(const char *code, const char *message, MqOwnedBytes *out, int32_t status) {
char json[512];
int written = snprintf(
json, sizeof(json),
"{\"wire_version\":1,\"kind\":\"response\",\"error\":"
"{\"kind\":\"invoke\",\"code\":\"%s\",\"message\":\"%s\"}}",
code, message);
if (written < 0 || (size_t)written >= sizeof(json)) {
return MQ_ERR_INTERNAL;
}
if (emit(json, (size_t)written, out) != MQ_OK) {
return MQ_ERR_OUT_OF_MEMORY;
}
return status;
}
static int32_t emit_int(long long value, MqOwnedBytes *out) {
char json[160];
int written = snprintf(
json, sizeof(json),
"{\"wire_version\":1,\"kind\":\"response\",\"value\":"
"{\"type\":\"int\",\"decimal\":\"%lld\"}}",
value);
if (written < 0 || (size_t)written >= sizeof(json)) {
return MQ_ERR_INTERNAL;
}
return emit(json, (size_t)written, out);
}
static int32_t invoke_binary(
MqBytes args_wire,
MqOwnedBytes *result_wire,
MqOwnedBytes *error_wire,
const char *first,
const char *second,
int operation
) {
char *json;
long long a = 0;
long long b = 0;
if (args_wire.data == NULL || args_wire.len == 0) {
return fail("bad_arguments", "request wire is empty", error_wire, MQ_ERR_INVALID_ARGUMENT);
}
json = (char *)malloc(args_wire.len + 1);
if (json == NULL) {
return fail("out_of_memory", "plugin could not copy request", error_wire, MQ_ERR_OUT_OF_MEMORY);
}
memcpy(json, args_wire.data, args_wire.len);
json[args_wire.len] = '\0';
if (read_int_argument(json, first, &a) != 0 ||
(second != NULL && read_int_argument(json, second, &b) != 0)) {
free(json);
return fail("bad_arguments", "invalid Int arguments", error_wire, MQ_ERR_INVALID_ARGUMENT);
}
free(json);
switch (operation) {
case 0: return emit_int(a + b, result_wire);
case 1: return emit_int(-a, result_wire);
default: return emit_int(a * 3, result_wire);
}
}
static int32_t solver_add(MqCallContext *ctx, MqBytes args, MqOwnedBytes *result, MqOwnedBytes *error) {
(void)ctx;
*result = (MqOwnedBytes){NULL, 0};
*error = (MqOwnedBytes){NULL, 0};
return invoke_binary(args, result, error, "a", "b", 0);
}
static int32_t solver_neg(MqCallContext *ctx, MqBytes args, MqOwnedBytes *result, MqOwnedBytes *error) {
(void)ctx;
*result = (MqOwnedBytes){NULL, 0};
*error = (MqOwnedBytes){NULL, 0};
return invoke_binary(args, result, error, "a", NULL, 1);
}
static int32_t quant_scale(MqCallContext *ctx, MqBytes args, MqOwnedBytes *result, MqOwnedBytes *error) {
(void)ctx;
*result = (MqOwnedBytes){NULL, 0};
*error = (MqOwnedBytes){NULL, 0};
return invoke_binary(args, result, error, "a", NULL, 2);
}
static int32_t register_export(const char *name, const char *signature, MqPluginInvoke invoke) {
MqBytes name_bytes;
MqBytes signature_bytes;
char wire[256];
int written = snprintf(wire, sizeof(wire), "{\"signature\":\"%s\"}", signature);
if (written < 0 || (size_t)written >= sizeof(wire)) {
return MQ_ERR_INTERNAL;
}
name_bytes.data = (const uint8_t *)name;
name_bytes.len = strlen(name);
signature_bytes.data = (const uint8_t *)wire;
signature_bytes.len = (size_t)written;
return g_host->register_function(g_host->host_data, name_bytes, signature_bytes, invoke);
}
int32_t mq_plugin_entry_v1(const MqHostApi *host, MqPluginApi *plugin) {
int32_t code;
if (host == NULL || plugin == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
if (host->struct_size < sizeof(MqHostApi) || host->abi_major != MQ_ABI_MAJOR) {
return MQ_ERR_ABI_MISMATCH;
}
if (host->alloc == NULL || host->free == NULL || host->register_function == NULL ||
host->request_capability == NULL) {
return MQ_ERR_ABI_MISMATCH;
}
g_host = host;
plugin->struct_size = (uint32_t)sizeof(MqPluginApi);
plugin->abi_major = MQ_ABI_MAJOR;
plugin->abi_minor = MQ_ABI_MINOR;
plugin->plugin_metadata_wire.data = (const uint8_t *)METADATA;
plugin->plugin_metadata_wire.len = sizeof(METADATA) - 1;
code = register_export("solver.add", "($a: Int, $b: Int) -> Int", solver_add);
if (code != MQ_OK) {
return code;
}
code = register_export("solver.neg", "($a: Int) -> Int", solver_neg);
if (code != MQ_OK) {
return code;
}
return register_export("quant.scale", "($a: Int) -> Int", quant_scale);
}
+318
View File
@@ -0,0 +1,318 @@
/*
* Marqdo plugin ABI v1 example plugin in C.
*
* Exports `solver.add` through `mq_plugin_entry_v1`, using the wire_version 1
* JSON envelope. It deliberately has no external dependencies: the tiny JSON
* scanning below is a demo aid, not a general-purpose JSON parser.
*
* Build:
* cc -std=c11 -O2 -shared -fPIC -I include examples/plugin-demo/solver.c \
* -o examples/plugin-demo/solver.so
*
* Test-only compile switches (used by the host-side conformance tests):
* -DMQ_SOLVER_REPORT_ABI_MAJOR=2 report a wrong ABI major on purpose
*/
#include "marqdo_plugin_abi_v1.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef MQ_SOLVER_REPORT_ABI_MAJOR
#define MQ_SOLVER_REPORT_ABI_MAJOR MQ_ABI_MAJOR
#endif
static const char PLUGIN_METADATA[] =
"{\"name\":\"demo.solver\",\"version\":\"0.1.0\"}";
static const char SIGNATURE_ADD[] = "{\"signature\":\"($a: Int, $b: Int) -> Int\"}";
/* Single-threaded ABI: the host table is captured once at entry. */
static const MqHostApi *g_host = NULL;
/* Return the pointer just past `"key"` + optional whitespace + ':' inside
* `json`. Returns NULL when the key is absent. This is a demo scanner. */
static const char *find_key(const char *json, const char *key) {
size_t key_len = strlen(key);
const char *cursor = json;
while ((cursor = strchr(cursor, '"')) != NULL) {
const char *name_start = cursor + 1;
const char *name_end = strchr(name_start, '"');
if (name_end == NULL) {
return NULL;
}
if ((size_t)(name_end - name_start) == key_len &&
memcmp(name_start, key, key_len) == 0) {
const char *after = name_end + 1;
while (*after == ' ' || *after == '\t' || *after == '\n' ||
*after == '\r') {
after++;
}
if (*after != ':') {
return NULL;
}
after++;
while (*after == ' ' || *after == '\t' || *after == '\n' ||
*after == '\r') {
after++;
}
return after;
}
cursor = name_end + 1;
}
return NULL;
}
/* Find the object that is the value of key `name` and return a pointer to its
* opening '{'. */
static const char *find_object_value(const char *json, const char *name) {
const char *value = find_key(json, name);
if (value == NULL || *value != '{') {
return NULL;
}
return value;
}
/* Extract a quoted JSON string value for `key`, copying at most `out_len - 1`
* bytes into `out` (NUL terminated). Rejects escapes for simplicity. */
static int read_string_value(const char *object, const char *key, char *out,
size_t out_len) {
const char *value = find_key(object, key);
if (value == NULL || *value != '"') {
return -1;
}
const char *start = value + 1;
const char *end = strchr(start, '"');
if (end == NULL) {
return -1;
}
size_t len = (size_t)(end - start);
if (len + 1 > out_len || memchr(start, '\\', len) != NULL) {
return -1;
}
memcpy(out, start, len);
out[len] = '\0';
return 0;
}
/* Extract the integer argument `name` from the request's `args` object. */
static int read_int_argument(const char *json, const char *name,
long long *out_value) {
const char *args = find_object_value(json, "args");
if (args == NULL) {
return -1;
}
const char *argument = find_object_value(args, name);
if (argument == NULL) {
return -1;
}
char decimal[32];
if (read_string_value(argument, "decimal", decimal, sizeof(decimal)) != 0) {
return -1;
}
char *end = NULL;
long long value = strtoll(decimal, &end, 10);
if (end == NULL || *end != '\0' || end == decimal) {
return -1;
}
*out_value = value;
return 0;
}
/* Allocate an output buffer through the host allocator and copy `len` bytes.
* The host frees it after copying; the plugin never frees output buffers. */
static int32_t emit(const char *json, size_t len, MqOwnedBytes *out) {
uint8_t *buffer;
if (g_host == NULL || out == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
buffer = (uint8_t *)g_host->alloc(g_host->host_data, len);
if (buffer == NULL) {
return MQ_ERR_OUT_OF_MEMORY;
}
memcpy(buffer, json, len);
out->data = buffer;
out->len = len;
return MQ_OK;
}
static int32_t emit_error(const char *code, const char *message,
MqOwnedBytes *out, int32_t failure_code) {
char json[512];
int written = snprintf(
json, sizeof(json),
"{\"wire_version\":1,\"kind\":\"response\",\"error\":"
"{\"kind\":\"invoke\",\"code\":\"%s\",\"message\":\"%s\"}}",
code, message);
if (written < 0 || (size_t)written >= sizeof(json)) {
return MQ_ERR_INTERNAL;
}
if (emit(json, (size_t)written, out) != MQ_OK) {
return MQ_ERR_OUT_OF_MEMORY;
}
/* Non-zero: the invocation failed even though an error envelope was
* written. The host reads the envelope for the structured error. */
return failure_code;
}
/* Implementation of the `solver.add` export. */
static int32_t solver_add(MqCallContext *ctx, MqBytes args_wire,
MqOwnedBytes *result_wire, MqOwnedBytes *error_wire) {
char *json;
long long a = 0;
long long b = 0;
long long sum;
char response[160];
int written;
(void)ctx;
if (result_wire == NULL || error_wire == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
*result_wire = (MqOwnedBytes){NULL, 0};
*error_wire = (MqOwnedBytes){NULL, 0};
if (args_wire.data == NULL || args_wire.len == 0) {
return emit_error("bad_arguments", "request wire is empty", error_wire,
MQ_ERR_INVALID_ARGUMENT);
}
if (args_wire.len > MQ_MAX_REQUEST_WIRE_BYTES) {
return emit_error("request_too_large", "request wire is too large",
error_wire, MQ_ERR_INVALID_ARGUMENT);
}
json = (char *)malloc(args_wire.len + 1);
if (json == NULL) {
return emit_error("out_of_memory", "plugin could not copy request",
error_wire, MQ_ERR_OUT_OF_MEMORY);
}
memcpy(json, args_wire.data, args_wire.len);
json[args_wire.len] = '\0';
if (read_int_argument(json, "a", &a) != 0 ||
read_int_argument(json, "b", &b) != 0) {
free(json);
return emit_error("bad_arguments",
"solver.add requires Int arguments `a` and `b`",
error_wire, MQ_ERR_INVALID_ARGUMENT);
}
free(json);
#ifdef MQ_SOLVER_CRASH
/* Test-only crash injection for isolated-worker crash tests. */
abort();
#endif
if (__builtin_add_overflow(a, b, &sum)) {
return emit_error("integer_overflow", "solver.add overflowed i64",
error_wire, MQ_ERR_INTERNAL);
}
written = snprintf(
response, sizeof(response),
"{\"wire_version\":1,\"kind\":\"response\",\"value\":"
"{\"type\":\"int\",\"decimal\":\"%lld\"}}",
sum);
if (written < 0 || (size_t)written >= sizeof(response)) {
return MQ_ERR_INTERNAL;
}
return emit(response, (size_t)written, result_wire);
}
#ifdef MQ_SOLVER_MULTI_EXPORT
/* Test-only second export: `solver.neg`, used to prove complete-name routing
* (ADR-0010). It is not part of the default demo manifest. */
static int32_t solver_neg(MqCallContext *ctx, MqBytes args_wire,
MqOwnedBytes *result_wire, MqOwnedBytes *error_wire) {
char *json;
long long a = 0;
char response[160];
int written;
(void)ctx;
if (result_wire == NULL || error_wire == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
*result_wire = (MqOwnedBytes){NULL, 0};
*error_wire = (MqOwnedBytes){NULL, 0};
if (args_wire.data == NULL || args_wire.len == 0) {
return emit_error("bad_arguments", "request wire is empty", error_wire,
MQ_ERR_INVALID_ARGUMENT);
}
json = (char *)malloc(args_wire.len + 1);
if (json == NULL) {
return emit_error("out_of_memory", "plugin could not copy request",
error_wire, MQ_ERR_OUT_OF_MEMORY);
}
memcpy(json, args_wire.data, args_wire.len);
json[args_wire.len] = '\0';
if (read_int_argument(json, "a", &a) != 0) {
free(json);
return emit_error("bad_arguments", "solver.neg requires Int `a`",
error_wire, MQ_ERR_INVALID_ARGUMENT);
}
free(json);
written = snprintf(
response, sizeof(response),
"{\"wire_version\":1,\"kind\":\"response\",\"value\":"
"{\"type\":\"int\",\"decimal\":\"%lld\"}}",
-a);
if (written < 0 || (size_t)written >= sizeof(response)) {
return MQ_ERR_INTERNAL;
}
return emit(response, (size_t)written, result_wire);
}
#endif
/* Required ABI v1 entry point. */
int32_t mq_plugin_entry_v1(const MqHostApi *host, MqPluginApi *plugin) {
MqBytes export_name;
MqBytes signature_wire;
int32_t code;
if (host == NULL || plugin == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
if (host->struct_size < sizeof(MqHostApi)) {
return MQ_ERR_ABI_MISMATCH;
}
if (host->abi_major != MQ_ABI_MAJOR) {
return MQ_ERR_ABI_MISMATCH;
}
if (host->alloc == NULL || host->free == NULL ||
host->register_function == NULL || host->request_capability == NULL) {
return MQ_ERR_ABI_MISMATCH;
}
g_host = host;
/* The host pre-fills struct_size; keep it and report our ABI version. */
plugin->struct_size = (uint32_t)sizeof(MqPluginApi);
plugin->abi_major = MQ_SOLVER_REPORT_ABI_MAJOR;
plugin->abi_minor = MQ_ABI_MINOR;
plugin->plugin_metadata_wire.data = (const uint8_t *)PLUGIN_METADATA;
plugin->plugin_metadata_wire.len = sizeof(PLUGIN_METADATA) - 1;
export_name.data = (const uint8_t *)"solver.add";
export_name.len = sizeof("solver.add") - 1;
signature_wire.data = (const uint8_t *)SIGNATURE_ADD;
signature_wire.len = sizeof(SIGNATURE_ADD) - 1;
code = host->register_function(host->host_data, export_name, signature_wire,
solver_add);
if (code != MQ_OK) {
return code;
}
#ifdef MQ_SOLVER_MULTI_EXPORT
export_name.data = (const uint8_t *)"solver.neg";
export_name.len = sizeof("solver.neg") - 1;
signature_wire.data = (const uint8_t *)"{\"signature\":\"($a: Int) -> Int\"}";
signature_wire.len = sizeof("{\"signature\":\"($a: Int) -> Int\"}") - 1;
code = host->register_function(host->host_data, export_name, signature_wire,
solver_neg);
if (code != MQ_OK) {
return code;
}
#endif
return MQ_OK;
}
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Build the C sensor provider and write provider/build/provider.json (schema v2)
# with the host target triple and the real artifact SHA-256.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
out="$here/build"
mkdir -p "$out"
host="$(rustc -vV | sed -n 's/^host: //p')"
case "$host" in
*windows*) echo "unsupported: Windows C ABI provider is not implemented in this fixture" >&2; exit 3 ;;
*apple-darwin*) ext="dylib"; flags=(-dynamiclib -fPIC) ;;
*) ext="so"; flags=(-shared -fPIC) ;;
esac
artifact="libsensor.$ext"
cc -std=c11 -O2 "${flags[@]}" -o "$out/$artifact" "$here/src/sensor.c"
if command -v sha256sum >/dev/null 2>&1; then
hash="$(sha256sum "$out/$artifact" | cut -d' ' -f1)"
else
hash="$(shasum -a 256 "$out/$artifact" | cut -d' ' -f1)"
fi
cat > "$out/provider.json" <<JSON
{
"schema": "marqdo.provider",
"schema_version": 2,
"name": "demo.sensor",
"version": "0.1.0",
"abi": "c-abi-1",
"transport": "worker",
"kinds": ["demo.sensor"],
"artifacts": [
{
"target": "$host",
"path": "lib/$artifact",
"sha256": "$hash"
}
],
"permissions_requested": []
}
JSON
mkdir -p "$out/lib"
mv "$out/$artifact" "$out/lib/$artifact"
echo "built $out/lib/$artifact for $host (sha256 $hash)"
+35
View File
@@ -0,0 +1,35 @@
# @knowledge 设备测试
## @exec main
打开独立仓库提供的资源;此标题仅决定文档语义,不涉及 Provider 注册。
`流 = resource.open("demo.sensor", "unit-1", ["read"])`
`内存 = memory.new(1, 1)`
`读取 = resource.read(流, 内存, 0, 5)`
`关闭 = resource.close(流)`
`if not 读取.ok`
`return 读取`
`else`
`if not 关闭.ok`
`return 关闭`
`else`
`if true`
`return 读取.value.count`
`end`
`end`
`end`
+17
View File
@@ -0,0 +1,17 @@
{
"schema": "marqdo.provider",
"schema_version": 2,
"name": "demo.sensor",
"version": "0.1.0",
"abi": "c-abi-1",
"transport": "worker",
"kinds": ["demo.sensor"],
"artifacts": [
{
"target": "x86_64-unknown-linux-gnu",
"path": "lib/libsensor.so",
"sha256": "0000000000000000000000000000000000000000000000000000000000000000"
}
],
"permissions_requested": []
}
+111
View File
@@ -0,0 +1,111 @@
/*
* Conformance resource provider (C ABI v1) for the unknown kind `demo.sensor`.
*
* The host's released `marqdo-provider-worker` helper loads this library and
* serves the framed-JSON resource protocol; the CLI never links this code.
* The provider ABI is re-declared here from the public C ABI specification
* (no standalone header is published yet).
*
* Behaviour used by the fixture:
* open("demo.sensor", "unit-1", ["read"]) -> token
* first read(max_bytes>=5) -> "hello", eof=true
* write(bytes) -> accepted, discarded
* close(token) -> closes exactly once
*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define ABI_VERSION 1
#define MQ_OK 0
#define MQ_ERR 1
static char g_last_error[256];
static int closed = 0;
uint32_t marqdo_resource_provider_abi_version(void) { return ABI_VERSION; }
static int fail(const char *message) {
snprintf(g_last_error, sizeof(g_last_error), "%s", message);
return MQ_ERR;
}
int32_t marqdo_resource_open(
const char *kind,
const char *descriptor,
const char *rights,
uint64_t *token
) {
(void)descriptor;
if (kind == NULL || strcmp(kind, "demo.sensor") != 0) {
return fail("unsupported kind");
}
if (rights == NULL || strstr(rights, "read") == NULL) {
return fail("read right is required");
}
if (token == NULL) {
return fail("token pointer is NULL");
}
*token = 1;
closed = 0;
snprintf(g_last_error, sizeof(g_last_error), "%s", "ok");
return MQ_OK;
}
int32_t marqdo_resource_read(
uint64_t token,
uint8_t *buffer,
uint32_t capacity,
uint32_t *read,
int32_t *eof
) {
static const char payload[] = "hello";
if (token != 1 || buffer == NULL || read == NULL || eof == NULL) {
return fail("invalid read arguments");
}
if (closed) {
return fail("resource is closed");
}
if (capacity < sizeof(payload) - 1) {
return fail("buffer is too small");
}
memcpy(buffer, payload, sizeof(payload) - 1);
*read = (uint32_t)(sizeof(payload) - 1);
*eof = 1;
return MQ_OK;
}
int32_t marqdo_resource_write(
uint64_t token,
const uint8_t *bytes,
uint32_t length,
uint32_t *written
) {
if (token != 1 || written == NULL || (bytes == NULL && length != 0)) {
return fail("invalid write arguments");
}
if (closed) {
return fail("resource is closed");
}
*written = length;
return MQ_OK;
}
int32_t marqdo_resource_close(uint64_t token) {
if (token != 1) {
return fail("unknown token");
}
if (closed) {
return fail("resource is already closed");
}
closed = 1;
return MQ_OK;
}
int32_t marqdo_resource_last_error(char *buffer, uint32_t capacity) {
if (buffer == NULL || capacity == 0) {
return MQ_ERR;
}
snprintf(buffer, capacity, "%s", g_last_error);
return MQ_OK;
}
+5
View File
@@ -0,0 +1,5 @@
## @exec main
`流 = resource.open("demo.sensor", "unit-1", ["read"])`
`return resource.close(流)`
+15
View File
@@ -0,0 +1,15 @@
# @knowledge 示例数学库
## @exec 加倍
`params(x: Int)`
`return x * 2`
## @exec 双倍面积
`params(r: Int)`
调用另一个模块的纯函数,再调用本模块的 `加倍`;不需要任何 Rust/Host 改动。
`return 加倍(x=geometry.面积(r=r))`
+3
View File
@@ -0,0 +1,3 @@
project:
name: example-math
version: 0.1.0
+12
View File
@@ -0,0 +1,12 @@
---
import:
helper: "./helper.mq.md"
---
# @knowledge 几何
## @exec 面积
`params(r: Int)`
`return helper.平方(x=r)`
+7
View File
@@ -0,0 +1,7 @@
# @knowledge 基础
## @exec 平方
`params(x: Int)`
`return x * x`
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Build every native fixture for the host target and generate complete
# manifests. Requires: cc, git, rustc (for the host triple), python3.
set -euo pipefail
here="$(cd "$(dirname "$0")/.." && pwd)"
"$here/plugin/build.sh"
"$here/provider/build.sh"
"$here/kernel/build.sh"
echo "all native fixtures built"
+644
View File
@@ -0,0 +1,644 @@
#!/usr/bin/env python3
"""Black-box conformance suite for a frozen Marqdo CLI.
Run from this repository after `scripts/build_all.sh`:
MARQDO_BIN=/abs/path/to/marqdo python3 tests/run_all.py
The suite never runs Cargo, never imports a Rust crate, and never writes into
the CLI workspace. It refuses to report success if the frozen binary hash
changes during the run (see tests/verify_frozen_cli.py).
Results are written to evidence/results.json in the shape consumed by
`marqdo-cli/tools/ci/verify_extension_contracts.py`.
"""
from __future__ import annotations
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
RESULTS = EVIDENCE / "results.json"
CATEGORIES = [
"callable_registry",
"plugin_worker",
"foreign_kernel",
"resource_provider_cli",
"package_pinned_git",
"tool_analysis_consumer",
"negative_security",
]
@dataclass
class Case:
category: str
name: str
status: str = "SKIPPED"
detail: str = ""
commands: list[str] = field(default_factory=list)
error_codes: list[str] = field(default_factory=list)
class Runner:
def __init__(self, cli: Path) -> None:
self.cli = cli
self.cases: list[Case] = []
self.cli_hash = sha256_file(cli)
self.tool_sha = git_sha(ROOT)
self.env = dict(os.environ)
self.env["MARQDO_BIN"] = str(cli)
# -- helpers ---------------------------------------------------------
def case(self, category: str, name: str) -> Case:
item = Case(category=category, name=name)
self.cases.append(item)
return item
def run(
self,
args: list[str],
cwd: Path | None = None,
env: dict[str, str] | None = None,
timeout: int = 60,
) -> subprocess.CompletedProcess:
merged = dict(self.env)
if env:
merged.update(env)
completed = subprocess.run(
[str(self.cli), *args],
cwd=str(cwd or ROOT),
env=merged,
capture_output=True,
text=True,
timeout=timeout,
)
return completed
def finish(
self,
case: Case,
completed: subprocess.CompletedProcess,
expect_exit: int,
*,
stdout: str | None = None,
stderr_contains: str | None = None,
stderr_not_contains: str | None = None,
) -> bool:
case.commands.append(" ".join(str(part) for part in completed.args))
ok = completed.returncode == expect_exit
if ok and stdout is not None:
ok = completed.stdout == stdout
if ok and stderr_contains is not None:
ok = stderr_contains in completed.stderr
if ok and stderr_not_contains is not None:
ok = stderr_not_contains not in completed.stderr
if ok:
case.status = "PASS"
case.detail = f"exit {completed.returncode}"
else:
case.status = "FAIL"
case.detail = (
f"exit {completed.returncode} (wanted {expect_exit}); "
f"stdout={completed.stdout[:300]!r}; stderr={completed.stderr[:500]!r}"
)
for line in completed.stderr.splitlines():
if line.startswith("error[") and "]" in line:
case.error_codes.append(line.split("[", 1)[1].split("]", 1)[0])
return ok
def skip(self, case: Case, reason: str) -> None:
case.status = "SKIPPED"
case.detail = reason
# -- fixture builds --------------------------------------------------
def build(self) -> None:
completed = subprocess.run(
[str(ROOT / "scripts" / "build_all.sh")],
cwd=str(ROOT),
env=self.env,
capture_output=True,
text=True,
)
if completed.returncode != 0:
raise SystemExit(
"fixture build failed:\n" + completed.stdout + completed.stderr
)
# -- categories ------------------------------------------------------
def check_plugin(self) -> None:
plugin = ROOT / "plugin"
build = plugin / "build"
demo = plugin / "demo.mq.md"
case = self.case("plugin_worker", "plugin check is static and succeeds")
check = self.run(["check", str(demo), "--plugin", str(build)])
self.finish(case, check, 0)
case = self.case("plugin_worker", "worker plugin executes three exports")
run = self.run(
[
"run",
str(demo),
"--plugin",
str(build),
"--allow-plugin",
"demo.ext",
]
)
self.finish(case, run, 0, stdout="42\n-7\n15\n")
case = self.case("callable_registry", "missing plugin export is symbol.unknown")
missing = self.run(
[
"run",
str(plugin / "negative-missing-export.mq.md"),
"--plugin",
str(build),
"--allow-plugin",
"demo.ext",
]
)
self.finish(case, missing, 1, stderr_contains="symbol.unknown")
case = self.case("callable_registry", "bad plugin args fail statically")
bad = self.run(
[
"check",
str(plugin / "negative-bad-args.mq.md"),
"--plugin",
str(build),
]
)
self.finish(case, bad, 1, stderr_contains="call.arity")
case = self.case("negative_security", "plugin without grant is permission.denied")
no_grant = self.run(
[
"run",
str(demo),
"--plugin",
str(build),
]
)
self.finish(case, no_grant, 1, stderr_contains="permission.denied")
case = self.case(
"negative_security", "tampered plugin artifact fails before main"
)
tampered = Path(tempfile.mkdtemp(prefix="ext-plugin-tamper-"))
try:
for entry in build.iterdir():
if entry.is_file():
shutil.copy(entry, tampered / entry.name)
manifest = self.read_yaml_artifact(tampered / "plugin.yaml")
artifact = tampered / manifest
artifact.write_bytes(artifact.read_bytes() + b"\0")
tamper_run = self.run(
[
"run",
str(demo),
"--plugin",
str(tampered),
"--allow-plugin",
"demo.ext",
]
)
self.finish(
case,
tamper_run,
1,
stderr_contains="ext.artifact_integrity",
stderr_not_contains="42",
)
finally:
shutil.rmtree(tampered, ignore_errors=True)
case = self.case(
"negative_security", "check does not require the plugin artifact to exist"
)
missing_artifact = Path(tempfile.mkdtemp(prefix="ext-plugin-missing-"))
try:
shutil.copytree(build, missing_artifact, dirs_exist_ok=True)
artifact_name = self.read_yaml_artifact(missing_artifact / "plugin.yaml")
(missing_artifact / artifact_name).unlink()
static_check = self.run(
[
"check",
str(demo),
"--plugin",
str(missing_artifact),
]
)
self.finish(case, static_check, 0)
finally:
shutil.rmtree(missing_artifact, ignore_errors=True)
def check_kernel(self) -> None:
kernel = ROOT / "kernel" / "build" / "kernel.json"
demo = ROOT / "kernel" / "demo.mq.md"
case = self.case("foreign_kernel", "unknown language mocklang executes")
result = self.run(
[
"run",
str(demo),
"--kernel",
str(kernel),
"--allow-foreign",
]
)
self.finish(case, result, 0, stdout="42\n")
case = self.case("negative_security", "foreign kernel without grant is denied")
denied = self.run(["run", str(demo), "--kernel", str(kernel)])
self.finish(case, denied, 1, stderr_contains="permission.denied")
def check_provider(self) -> None:
provider_dir = ROOT / "provider"
build = provider_dir / "build"
demo = provider_dir / "demo.mq.md"
help_text = self.run(["run", "--help"])
supports = "--provider" in help_text.stdout
case = self.case(
"resource_provider_cli", "provider v2 reads five bytes through the CLI"
)
if not supports:
self.skip(
case,
"frozen CLI has no --provider/--allow-provider (RFC-EXT-0001 PR-03 not built yet)",
)
return
helper = self.cli.with_name("marqdo-provider-worker")
if not helper.is_file():
self.skip(
case,
f"provider helper is not shipped next to the frozen CLI: {helper}",
)
return
result = self.run(
[
"run",
str(demo),
"--provider",
str(build),
"--allow-provider",
"demo.sensor",
]
)
self.finish(case, result, 0, stdout="5\n")
case = self.case("negative_security", "provider without grant is denied")
denied = self.run(["run", str(demo), "--provider", str(build)])
self.finish(case, denied, 1, stderr_contains="permission.denied")
case = self.case(
"negative_security", "provider v1 schema is rejected without migration"
)
temp = Path(tempfile.mkdtemp(prefix="ext-provider-v1-"))
try:
shutil.copytree(build, temp, dirs_exist_ok=True)
manifest = json.loads((temp / "provider.json").read_text())
manifest["schema_version"] = 1
(temp / "provider.json").write_text(json.dumps(manifest))
v1 = self.run(
[
"run",
str(demo),
"--provider",
str(temp),
"--allow-provider",
"demo.sensor",
]
)
self.finish(
case,
v1,
2,
stderr_contains="ext.unsupported_provider_schema",
)
finally:
shutil.rmtree(temp, ignore_errors=True)
case = self.case(
"negative_security", "provider artifact digest tamper is rejected"
)
temp = Path(tempfile.mkdtemp(prefix="ext-provider-tamper-"))
try:
shutil.copytree(build, temp, dirs_exist_ok=True)
manifest = json.loads((temp / "provider.json").read_text())
manifest["artifacts"][0]["sha256"] = "0" * 64
(temp / "provider.json").write_text(json.dumps(manifest))
tampered = self.run(
[
"run",
str(demo),
"--provider",
str(temp),
"--allow-provider",
"demo.sensor",
]
)
self.finish(
case,
tampered,
1,
stderr_contains="ext.artifact_integrity",
)
finally:
shutil.rmtree(temp, ignore_errors=True)
case = self.case(
"negative_security", "pure and strict modes reject provider flags"
)
pure = self.run(
[
"run",
str(demo),
"--mode",
"pure",
"--provider",
str(build),
"--allow-provider",
"demo.sensor",
]
)
strict = self.run(
[
"run",
str(demo),
"--mode",
"strict",
"--provider",
str(build),
"--allow-provider",
"demo.sensor",
]
)
ok_pure = self.finish(case, pure, 2)
if ok_pure:
strict_case = self.case(
"negative_security", "strict mode rejects provider flags"
)
self.finish(strict_case, strict, 2)
def check_tool(self) -> None:
case = self.case(
"tool_analysis_consumer", "independent tool consumes Analysis v2"
)
home = Path(tempfile.mkdtemp(prefix="ext-tool-home-"))
try:
env = {
"HOME": str(home),
"XDG_CONFIG_HOME": str(home / ".config"),
"XDG_DATA_HOME": str(home / ".local" / "share"),
}
install = self.run(
["tool", "install", str(ROOT / "tool" / "tool.json")], env=env
)
if not self.finish(case, install, 0):
return
case = self.case(
"tool_analysis_consumer", "registered tool command dispatches"
)
invoke = self.run(
["inspect-ext", str(ROOT / "tool" / "demo.mq.md")], env=env
)
ok = self.finish(case, invoke, 0)
if ok:
payload = json.loads(invoke.stdout)
functions = payload.get("functions", [])
ok = any(item.get("local_name") == "main" for item in functions)
if not ok:
case.status = "FAIL"
case.detail = f"tool saw no main function: {invoke.stdout[:500]}"
case = self.case(
"negative_security", "tool install rejects unknown entrypoint traversal"
)
bad = Path(tempfile.mkdtemp(prefix="ext-tool-bad-"))
try:
shutil.copytree(ROOT / "tool", bad, dirs_exist_ok=True)
bad_manifest = json.loads((bad / "tool.json").read_text())
bad_manifest["entrypoint"] = "../../escape.py"
(bad / "tool.json").write_text(json.dumps(bad_manifest))
rejected = self.run(["tool", "install", str(bad)], env=env)
self.finish(case, rejected, 2)
finally:
shutil.rmtree(bad, ignore_errors=True)
remove = self.run(["tool", "remove", "inspect-ext"], env=env)
self.finish(
self.case("tool_analysis_consumer", "tool remove unregisters"),
remove,
0,
)
finally:
shutil.rmtree(home, ignore_errors=True)
def check_package(self) -> None:
case = self.case(
"package_pinned_git", "pinned Git .mq.md library runs from a separate repo"
)
workspace = Path(tempfile.mkdtemp(prefix="ext-package-"))
try:
source = workspace / "math-src"
shutil.copytree(ROOT / "pure-lib", source)
git_commit(source, "math library snapshot")
rev = git_sha(source)
consumer = workspace / "consumer"
consumer.mkdir()
shutil.copy(ROOT / "consumer" / "index.mq.md", consumer / "index.mq.md")
(consumer / "marqdo.yaml").write_text(
"project:\n"
" name: ext-consumer\n"
" version: 0.1.0\n"
"dependencies:\n"
" math:\n"
f" git: \"file://{source}\"\n"
f" rev: \"{rev}\"\n"
)
lock = self.run(["lock"], cwd=consumer)
if not self.finish(case, lock, 0):
return
sync = self.run(["sync"], cwd=consumer)
if not self.finish(case, sync, 0):
return
case = self.case(
"package_pinned_git", "consumer runs the pinned dependency"
)
check = self.run(["check", "index.mq.md"], cwd=consumer)
ok = self.finish(case, check, 0)
run = self.run(["run", "index.mq.md", "--json"], cwd=consumer)
ok = ok and self.finish(
case,
run,
0,
stdout=json.dumps(
{
"command": "run",
"success": True,
"value": {"type": "int", "decimal": "18"},
"stdout": "",
"stderr": "",
"diagnostics": [],
"trace": [],
},
separators=(",", ":"),
),
)
if not ok:
return
# Offline/reproducibility: move the project, delete the source Git
# repository, and run again from the verified cache only.
moved = workspace / "moved-consumer"
shutil.move(str(consumer), moved)
shutil.rmtree(source)
case = self.case(
"package_pinned_git",
"verified cache still runs after moving the checkout and deleting the source",
)
offline = self.run(["run", "index.mq.md"], cwd=moved)
self.finish(case, offline, 0)
finally:
shutil.rmtree(workspace, ignore_errors=True)
# -- utilities -------------------------------------------------------
@staticmethod
def read_yaml_artifact(manifest: Path) -> str:
for line in manifest.read_text().splitlines():
stripped = line.strip()
if stripped.startswith("file:"):
return stripped.split("file:", 1)[1].strip().strip('"')
raise SystemExit(f"manifest has no artifact file: {manifest}")
def report(self) -> int:
final_hash = sha256_file(self.cli)
if final_hash != self.cli_hash:
case = self.case("negative_security", "frozen CLI binary did not change")
case.status = "FAIL"
case.detail = f"sha256 changed {self.cli_hash} -> {final_hash}"
else:
case = self.case("negative_security", "frozen CLI binary did not change")
case.status = "PASS"
case.detail = f"sha256 {self.cli_hash}"
results: dict[str, str] = {}
for category in CATEGORIES:
cases = [item for item in self.cases if item.category == category]
if not cases:
results[category] = "UNSUPPORTED"
elif any(item.status == "FAIL" for item in cases):
results[category] = "FAIL"
elif all(item.status == "SKIPPED" for item in cases):
results[category] = "UNSUPPORTED"
elif any(item.status == "SKIPPED" for item in cases):
results[category] = "PASS" if all(
item.status in {"PASS", "SKIPPED"} for item in cases
) else "FAIL"
else:
results[category] = "PASS"
payload = {
"schema": "marqdo.ext-fixture-results",
"schema_version": 1,
"tool_sha": self.tool_sha,
"cli_binary_sha256": final_hash,
"os": os_name(),
"arch": platform.machine(),
"results": results,
"cases": [
{
"category": item.category,
"name": item.name,
"status": item.status,
"detail": item.detail,
"commands": item.commands,
"error_codes": item.error_codes,
}
for item in self.cases
],
}
EVIDENCE.mkdir(exist_ok=True)
RESULTS.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
failures = [item for item in self.cases if item.status == "FAIL"]
for item in self.cases:
marker = {"PASS": "PASS", "FAIL": "FAIL", "SKIPPED": "SKIP"}[item.status]
print(f"[{marker}] {item.category}: {item.name}")
if item.status != "PASS":
print(f" {item.detail}")
print(json.dumps(results, indent=2))
return 1 if failures else 0
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def git_sha(directory: Path) -> str:
output = subprocess.run(
["git", "-C", str(directory), "rev-parse", "HEAD"],
check=True,
capture_output=True,
text=True,
)
return output.stdout.strip()
def git_commit(directory: Path, message: str) -> None:
def git(*args: str) -> None:
subprocess.run(
["git", "-C", str(directory), *args], check=True, capture_output=True
)
if not (directory / ".git").is_dir():
git("init", "-q", "-b", "main")
git("config", "user.name", "Marqdo Extension Fixtures")
git("config", "user.email", "fixtures@example.invalid")
git("add", "-A")
git("commit", "-q", "-m", message)
def os_name() -> str:
name = platform.system().lower()
if name.startswith("linux"):
return "linux"
if name == "darwin":
return "macos"
if name.startswith("windows"):
return "windows"
return name
def main() -> int:
raw = os.environ.get("MARQDO_BIN")
if not raw:
print("error: set MARQDO_BIN to the absolute frozen CLI path", file=sys.stderr)
return 2
cli = Path(raw).resolve()
if not cli.is_file():
print(f"error: MARQDO_BIN is not a file: {cli}", file=sys.stderr)
return 2
runner = Runner(cli)
print(f"frozen CLI: {cli} sha256 {runner.cli_hash}")
runner.build()
runner.check_plugin()
runner.check_kernel()
runner.check_provider()
runner.check_tool()
runner.check_package()
return runner.report()
if __name__ == "__main__":
raise SystemExit(main())
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Verify that the frozen CLI binary is an absolute file and never changed.
Usage:
python3 tests/verify_frozen_cli.py --hash # print sha256
python3 tests/verify_frozen_cli.py --expect <sha256>
MARQDO_BIN=... python3 tests/verify_frozen_cli.py --hash
The suite never accepts a PATH lookup, `cargo run` or a relative binary: that
would let the "frozen binary" assumption silently drift.
"""
import hashlib
import os
import sys
from pathlib import Path
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def main(argv: list[str]) -> int:
raw = os.environ.get("MARQDO_BIN")
if not raw:
print("error: MARQDO_BIN must be set to the absolute frozen CLI path", file=sys.stderr)
return 2
cli = Path(raw)
if not cli.is_absolute():
print(f"error: MARQDO_BIN must be absolute, got {raw}", file=sys.stderr)
return 2
if not cli.is_file():
print(f"error: MARQDO_BIN is not a regular file: {cli}", file=sys.stderr)
return 2
actual = sha256(cli)
if "--hash" in argv:
print(actual)
return 0
if "--expect" in argv:
expected = argv[argv.index("--expect") + 1]
if expected != actual:
print(
f"error: frozen CLI changed: expected {expected}, actual {actual}",
file=sys.stderr,
)
return 1
print(f"frozen CLI unchanged: {actual}")
return 0
print(f"{cli} {actual}")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
+5
View File
@@ -0,0 +1,5 @@
## @exec main
`打印("tool analysis consumer")`
`return 7`
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Independent Marqdo CLI Tool (Tool Protocol v1).
Consumes only public contracts: `$MARQDO_BIN check <doc> --emit <analysis>`
(Analysis v2) and optionally `$MARQDO_BIN run <doc> --trace-file <trace>`
(Trace v2). It links no Rust crate and reads no CLI source tree.
Usage:
marqdo inspect-ext <document.mq.md> [--trace]
Prints one deterministic JSON object:
{"schema":"ext.inspect.v1","document":...,"functions":[...],
"function_digest":"sha256:...", "trace": {...}|null}
"""
import hashlib
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path
SCHEMA = "ext.inspect.v1"
def fail(message, code=2):
print(json.dumps({"schema": SCHEMA, "error": message}, ensure_ascii=False))
return code
def main(argv):
args = [arg for arg in argv[1:] if not arg.startswith("--")]
want_trace = "--trace" in argv[1:]
if len(args) != 1:
return fail("usage: marqdo inspect-ext <document.mq.md> [--trace]")
bin_path = os.environ.get("MARQDO_BIN")
if not bin_path:
return fail("MARQDO_BIN is not set; install through `marqdo tool install`")
document = Path(args[0]).resolve()
if not document.is_file():
return fail(f"document does not exist: {document}")
with tempfile.TemporaryDirectory(prefix="ext-inspect-") as tmp:
analysis_path = Path(tmp) / "analysis.json"
check = subprocess.run(
[bin_path, "check", str(document), "--emit", str(analysis_path), "--json"],
capture_output=True,
text=True,
)
if check.returncode != 0 or not analysis_path.is_file():
return fail(
"check failed: " + (check.stderr.strip() or check.stdout.strip()),
code=1,
)
analysis = json.loads(analysis_path.read_text(encoding="utf-8"))
functions = []
for module in analysis.get("modules", []):
for function in module.get("functions", []):
functions.append(
{
"id": function["id"],
"module": module["id"],
"local_name": function.get("local_name"),
"heading_span": function.get("heading_span"),
"signature": function.get("signature", {}).get("kind"),
}
)
functions.sort(key=lambda item: item["id"])
digest = hashlib.sha256()
for function in functions:
digest.update(function["id"].encode())
digest.update(b"\0")
heading = function.get("heading_span") or {}
digest.update(f"{heading.get('start', 0)}:{heading.get('end', 0)}".encode())
digest.update(b"\0")
payload = {
"schema": SCHEMA,
"document": document.name,
"analysis_schema_version": analysis.get("schema_version"),
"analysis_digest": hashlib.sha256(
json.dumps(analysis, sort_keys=True, separators=(",", ":")).encode()
).hexdigest(),
"functions": functions,
"function_digest": "sha256:" + digest.hexdigest(),
"trace": None,
}
if want_trace:
trace_path = Path(tmp) / "trace.json"
run = subprocess.run(
[
bin_path,
"run",
str(document),
"--trace-file",
str(trace_path),
"--json",
],
capture_output=True,
text=True,
)
if trace_path.is_file():
trace = json.loads(trace_path.read_text(encoding="utf-8"))
payload["trace"] = {
"schema": trace.get("schema"),
"schema_version": trace.get("schema_version"),
"events": len(trace.get("events", [])),
}
elif run.returncode != 0:
payload["trace"] = {"error": run.stderr.strip()[:500]}
print(json.dumps(payload, ensure_ascii=False, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
+13
View File
@@ -0,0 +1,13 @@
{
"schema": "marqdo.cli-tool",
"schema_version": 1,
"name": "inspect-ext",
"version": "0.1.0",
"command": "inspect-ext",
"entrypoint": "inspect_ext.py",
"compatibility": {
"marqdo": ">=0.1,<1",
"analysis": [2],
"trace": [2]
}
}