Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8b82d4143 | ||
|
|
f836f05998 | ||
|
|
98d256f5a2 | ||
|
|
89acb709c6 | ||
|
|
3ab4aaa861 | ||
|
|
c769eafc60 | ||
|
|
2acaaefe77 | ||
|
|
88ce91a9e1 | ||
|
|
0e1efc713e | ||
|
|
ab6b6b1a23 | ||
|
|
3a68260cf2 | ||
|
|
422b9de6d7 | ||
|
|
1b9d9c4c26 | ||
|
|
b9c72e1d2a |
No files matched your search
@@ -19,6 +19,8 @@ jobs:
|
||||
components: rustfmt, clippy
|
||||
- name: Rust cache
|
||||
uses: Swatinem/rust-cache@v2
|
||||
- name: Verify the pinned stdlib Bundle
|
||||
run: python3 tools/stdlib/bundle.py
|
||||
- name: Formatting
|
||||
run: cargo fmt --all -- --check
|
||||
- name: Clippy
|
||||
@@ -43,9 +45,14 @@ 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
|
||||
- name: Whole stdlib product tests (explicit pinned Bundle)
|
||||
env:
|
||||
MARQDO_TEST_STDLIB_BUNDLE: ${{ github.workspace }}/stdlib
|
||||
MARQDO_TEST_BUNDLE_PIN: ${{ github.workspace }}/tools/stdlib/bundle-pin.json
|
||||
run: cargo test -p marqdo-cli --test stdlib_product
|
||||
- name: Validate public JSON schemas
|
||||
run: |
|
||||
@@ -97,6 +104,16 @@ jobs:
|
||||
--trust-native-plugin \
|
||||
--allow-plugin demo.solver
|
||||
|
||||
independent-build:
|
||||
name: independent CLI/worker build (no stdlib source)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: Build from a copy without stdlib and run a language-only program
|
||||
run: python3 tools/ci/independent_build.py
|
||||
|
||||
schema:
|
||||
name: schema instance validation + consumers
|
||||
runs-on: ubuntu-latest
|
||||
@@ -225,7 +242,8 @@ jobs:
|
||||
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
version="$(cargo metadata --no-deps --format-version 1 --offline \
|
||||
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
|
||||
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version"
|
||||
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version" \
|
||||
--stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json
|
||||
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
|
||||
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$GITHUB_SHA" dist/frozen-extension-evidence.json
|
||||
- uses: actions/upload-artifact@v4
|
||||
@@ -243,7 +261,7 @@ jobs:
|
||||
|
||||
release-evidence:
|
||||
name: release evidence manifest
|
||||
needs: [test, schema, cross-platform, frozen-extensions]
|
||||
needs: [test, schema, cross-platform, frozen-extensions, independent-build]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -256,6 +274,7 @@ jobs:
|
||||
LINUX_RESULT: ${{ needs.test.result }}
|
||||
SCHEMA_RESULT: ${{ needs.schema.result }}
|
||||
EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }}
|
||||
INDEPENDENT_RESULT: ${{ needs.independent-build.result }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
state() {
|
||||
@@ -266,7 +285,7 @@ jobs:
|
||||
esac
|
||||
}
|
||||
linux="$(state "$LINUX_RESULT")"
|
||||
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ]; then
|
||||
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ] || [ "$(state "$INDEPENDENT_RESULT")" != "PASS" ]; then
|
||||
linux="FAIL"
|
||||
fi
|
||||
python3 tools/ci/release_evidence.py --profile rc --target-sha "$TARGET_SHA" \
|
||||
|
||||
@@ -42,3 +42,7 @@ __pycache__/
|
||||
/tests/embedding/target/
|
||||
/tests/sdk-plugin/target/
|
||||
/.tmp/
|
||||
|
||||
# Accidental curl/test capture files
|
||||
/out
|
||||
/log.txt
|
||||
+13
-2
@@ -40,6 +40,7 @@ steps:
|
||||
- apt-get install -y --no-install-recommends curl ca-certificates python3 python3-jsonschema build-essential gcc-mingw-w64-x86-64
|
||||
- curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
|
||||
- apt-get install -y --no-install-recommends nodejs
|
||||
- python3 tools/stdlib/bundle.py
|
||||
- cargo fmt --all -- --check
|
||||
- cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Provider CLI tests resolve a real provider worker next to the CLI
|
||||
@@ -50,13 +51,21 @@ 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
|
||||
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/stdlib" MARQDO_TEST_BUNDLE_PIN="$PWD/tools/stdlib/bundle-pin.json" cargo test -p marqdo-cli --test stdlib_product
|
||||
# Windows compile gate: runtime lanes are native on GitHub; this catches
|
||||
# cfg/compile regressions on the Linux CI without a Windows runner.
|
||||
- rustup target add x86_64-pc-windows-gnu
|
||||
- cargo check --workspace --all-targets --target x86_64-pc-windows-gnu
|
||||
|
||||
independent-build:
|
||||
image: rust:1.100-bookworm
|
||||
commands:
|
||||
- apt-get update
|
||||
- apt-get install -y --no-install-recommends ca-certificates git python3
|
||||
- python3 tools/ci/independent_build.py
|
||||
|
||||
minimum-rust:
|
||||
image: rust:1.89-bookworm
|
||||
commands:
|
||||
@@ -74,13 +83,15 @@ steps:
|
||||
# only supported transport and resolution is a sibling-of-CLI lookup.
|
||||
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
- test -x target/release/marqdo-provider-worker
|
||||
- python3 tools/stdlib/bundle.py
|
||||
# Build the deterministic archive from this exact commit and cold-install
|
||||
# smoke-test it; the package script refuses a dirty tree or wrong SHA.
|
||||
- |
|
||||
set -eu
|
||||
version="$(cargo metadata --no-deps --format-version 1 --offline \
|
||||
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
|
||||
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version"
|
||||
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version" \
|
||||
--stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json
|
||||
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
|
||||
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$CI_COMMIT_SHA" dist/frozen-extension-evidence.json
|
||||
cat dist/frozen-extension-evidence.json
|
||||
@@ -10,6 +10,7 @@ steps:
|
||||
commands:
|
||||
- apt-get update
|
||||
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates git openssl build-essential
|
||||
- python3 tools/stdlib/bundle.py
|
||||
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
- |
|
||||
set -eu
|
||||
@@ -22,7 +23,8 @@ steps:
|
||||
(cd "$perf_dir/beta" && cargo build --release --locked -p marqdo-cli)
|
||||
|
||||
version="$(target/release/marqdo --version | cut -d ' ' -f 2)"
|
||||
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" --out-dir "$perf_dir"
|
||||
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" \
|
||||
--stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json --out-dir "$perf_dir"
|
||||
archive="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu.tar.gz"
|
||||
(cd "$perf_dir" && sha256sum -c "$(basename "$archive.sha256")")
|
||||
tar -xzf "$archive" -C "$perf_dir"
|
||||
@@ -37,7 +39,8 @@ steps:
|
||||
(cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \
|
||||
--warmups 5 --samples 20 --platform-id woodpecker-agent-1 \
|
||||
--cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null)
|
||||
python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" --warmups 5 --samples 20 \
|
||||
python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" \
|
||||
--stdlib-dir "$candidate/stdlib" --warmups 5 --samples 20 \
|
||||
--platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \
|
||||
--baseline "$perf_dir/beta.json" --out perf.json > /dev/null
|
||||
python3 - <<'PY'
|
||||
|
||||
@@ -34,8 +34,8 @@ correctness and release evidence before expanding the surface.
|
||||
9. Side effects go through `CapabilityHost`; do not invent host bypasses for tests, plugins, math or foreign kernels. `check` and `inspect` cannot execute untrusted project code.
|
||||
10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates.
|
||||
11. RFC-LANG-0002 is implemented by the frontend, `marqdo-expression`, IR lowering, runtime and the bundled stdlib. Keep `spec/`, implementation, fixtures, stdlib digest and docs in lockstep; there is no legacy mapper or per-file syntax switch to fall back to. Do not make a release claim beyond the evidence recorded in `docs/STATUS.md`.
|
||||
12. The language engine depends on the neutral `marqdo-host-contract` only; it must never link `marqdo-host`, the sandbox, foreign kernels, the plugin loader/worker, package or CLI in normal/build dependencies. `marqdo-host-contract` depends on `Value`/`Span` only. The native host implements the contract and must not depend back on the runtime/frontend/IR. The plugin ABI crate is a contract (no `dlopen`/worker/manifest execution); the standalone public SDK repository `cflmy/marqdo-plugin-sdk` consumes one pinned CLI contract revision and the CLI must not depend on it (ADR-0072). CLI is the one assembly point. This is enforced by `tools/ci/check_dependency_boundaries.py`, `tools/ci/check_engine_boundary.py` and `crates/cli/tests/architecture_boundaries.rs`; see ADR-0071/ADR-0072.
|
||||
13. Do not create empty candidate repositories (for example `marqdo-engine`/`marqdo-host`/`marqdo-cli-*`) to "solve" architecture. A repository split requires a separate accepted ADR with ownership/release evidence; "keep in workspace" is a valid recorded decision. The only split approved so far is the independent public SDK (ADR-0072); the SDK is pinned to a CLI contract `rev` and must not return as a workspace member or copied source. Do not add a second Host trait, Value encoding, wire/RPC engine protocol or compatibility re-export path.
|
||||
12. The language engine depends on the neutral `marqdo-host-contract` only; it must never link `marqdo-host`, the sandbox, foreign kernels, the plugin loader/worker, package or CLI in normal/build dependencies. `marqdo-host-contract` depends on `Value`/`Span` only. The native host implements the contract and must not depend back on the runtime/frontend/IR. The plugin ABI crate is a contract (no `dlopen`/worker/manifest execution); the SDK consumes the contract only. CLI is the one assembly point. This is enforced by `tools/ci/check_dependency_boundaries.py`, `tools/ci/check_engine_boundary.py`, `tools/ci/check_plugin_sdk.py` and `crates/cli/tests/architecture_boundaries.rs`; see ADR-0071.
|
||||
13. Do not create empty candidate repositories (for example `marqdo-engine`/`marqdo-host`/`marqdo-cli-*`) to "solve" architecture. A repository split requires the issue #13 §9.2 evidence and a separate accepted ADR; "keep in workspace" is a valid recorded decision. The plugin SDK stays in this CLI workspace as a contract-only crate (ADR-0073); do not re-create an independent SDK repository, mirror or submodule for the pre-stable line. Do not add a second Host trait, Value encoding, wire/RPC engine protocol or compatibility re-export path.
|
||||
|
||||
## Pre-stable protocol changes
|
||||
|
||||
@@ -54,7 +54,7 @@ closing a protocol replacement issue.
|
||||
2. Update the normative spec **in place** first; there is never a second active syntax spec.
|
||||
3. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST, execution IR and diagnostics.
|
||||
4. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, expression parser, runtime and host separated.
|
||||
5. Run formatting, clippy, unit tests, golden tests, the architecture/dependency gates and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`, `python3 tools/ci/check_dependency_boundaries.py`, `python3 tools/ci/check_engine_boundary.py`).
|
||||
5. Run formatting, clippy, unit tests, golden tests, the architecture/dependency gates and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`, `python3 tools/ci/check_dependency_boundaries.py`, `python3 tools/ci/check_engine_boundary.py`, `python3 tools/ci/check_plugin_sdk.py`).
|
||||
6. Write the tradeoff and state of completion in the PR. Never say a feature is finished because a design example looks executable. Update `spec/` and `docs/STATUS.md` when behavior or status changes; the docs describe what the code does and flag divergences explicitly.
|
||||
|
||||
## Unresolved design topics
|
||||
|
||||
Generated
+9
@@ -561,6 +561,15 @@ dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-plugin-sdk"
|
||||
version = "3.0.0-rc.4"
|
||||
dependencies = [
|
||||
"marqdo-plugin-abi",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-provider-worker"
|
||||
version = "3.0.0-rc.4"
|
||||
|
||||
@@ -11,6 +11,7 @@ members = [
|
||||
"crates/marqdo-plugin-abi",
|
||||
"crates/marqdo-provider-worker",
|
||||
"crates/marqdo-worker-ipc",
|
||||
"crates/marqdo-plugin-sdk",
|
||||
"crates/marqdo-host",
|
||||
"crates/marqdo-host-contract",
|
||||
"crates/marqdo-runtime",
|
||||
|
||||
@@ -50,7 +50,7 @@ CI: the source of truth is the Gitea remote
|
||||
[git.cflmy.cn/cflmy/marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) with
|
||||
Woodpecker at [ci.cflmy.cn](https://ci.cflmy.cn); [`.woodpecker/main.yml`](.woodpecker/main.yml)
|
||||
runs fmt, clippy, workspace tests with `--locked`, the dependency-direction and
|
||||
engine-independence gates, the Windows
|
||||
engine-independence gates, the plugin SDK consumption gate, the Windows
|
||||
cross-target compile gate and a release build of both binaries. The strict OS-isolation lane
|
||||
requires the disposable VM described in [docs/ci.md](docs/ci.md); a GitHub
|
||||
mirror is not used as the authoritative lane for this beta.
|
||||
@@ -64,6 +64,21 @@ cargo build -p marqdo-cli
|
||||
# binary: target/debug/marqdo (or $CARGO_TARGET_DIR/debug/marqdo)
|
||||
```
|
||||
|
||||
The CLI and Provider Worker compile without the stdlib sources. A release is
|
||||
assembled from one explicit, verified Bundle (ADR-0070); the debug CLI still
|
||||
discovers the checkout's `stdlib/` for the development loop, and
|
||||
`MARQDO_STDLIB_DIR` is the explicit runtime override:
|
||||
|
||||
```bash
|
||||
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
python3 tools/stdlib/bundle.py --print-path
|
||||
python3 tools/release/package.py --source-sha "$(git rev-parse HEAD)" \
|
||||
--version <version> --stdlib-dir stdlib \
|
||||
--bundle-pin tools/stdlib/bundle-pin.json
|
||||
```
|
||||
|
||||
See [`docs/releasing.md`](docs/releasing.md) for the full procedure.
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
@@ -297,7 +312,7 @@ crates/marqdo-foreign Python/Node one-shot kernel supervisor
|
||||
crates/marqdo-sandbox mode parsing + platform isolation detection
|
||||
crates/marqdo-host-contract neutral Host trait, HostOp, context and runtime facts
|
||||
crates/marqdo-plugin-abi public C ABI v1 contract: layout, wire envelope, errors
|
||||
(the Rust SDK lives in cflmy/marqdo-plugin-sdk)
|
||||
crates/marqdo-plugin-sdk Rust plugin SDK and entry macro (contract-only)
|
||||
crates/marqdo-host Native Host: capability, resources, OS, plugin loader/worker
|
||||
crates/marqdo-runtime tree-walk interpreter (depends only on the neutral contract)
|
||||
crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery
|
||||
|
||||
+61
-44
@@ -51,14 +51,24 @@ impl StdlibBundle {
|
||||
/// machine path: the release archive must ship a verified `stdlib/` next to
|
||||
/// the binary (RFC-EXT-0003 H-08, ADR).
|
||||
pub fn discover() -> Result<Option<Self>, String> {
|
||||
if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) {
|
||||
return Self::load(PathBuf::from(dir)).map(Some);
|
||||
let override_dir = std::env::var_os(STDLIB_DIR_ENV).map(PathBuf::from);
|
||||
let exe_dir = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|exe| exe.parent().map(Path::to_path_buf));
|
||||
Self::discover_with(override_dir, exe_dir)
|
||||
}
|
||||
|
||||
/// Discovery with the explicit override and the executable directory passed
|
||||
/// in. The override is authoritative: a bad `MARQDO_STDLIB_DIR` fails even
|
||||
/// when a valid sibling Bundle exists (no silent fallback).
|
||||
fn discover_with(
|
||||
override_dir: Option<PathBuf>,
|
||||
exe_dir: Option<PathBuf>,
|
||||
) -> Result<Option<Self>, String> {
|
||||
if let Some(dir) = override_dir {
|
||||
return Self::load(dir).map(Some);
|
||||
}
|
||||
Self::discover_from_exe_dir(
|
||||
std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|exe| exe.parent().map(Path::to_path_buf)),
|
||||
)
|
||||
Self::discover_from_exe_dir(exe_dir)
|
||||
}
|
||||
|
||||
/// Discover from the directory that holds the executable, without the explicit
|
||||
@@ -454,21 +464,41 @@ pub fn aliases_digest(aliases: &[PublicAlias]) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn dev_bundle() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("..")
|
||||
.join("..")
|
||||
.join("stdlib")
|
||||
/// A small synthetic Bundle so loader unit tests never depend on the
|
||||
/// product tree (ADR-0070 test-lane separation).
|
||||
fn write_synthetic_bundle(root: &Path) {
|
||||
for (relative, body) in [
|
||||
("io.mq.md", "## @knowledge test\n"),
|
||||
("io/console.mq.md", "## @knowledge console\n"),
|
||||
] {
|
||||
let path = root.join(relative);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, body).unwrap();
|
||||
}
|
||||
let digest = tree_digest(root).unwrap();
|
||||
let manifest = serde_json::json!({
|
||||
"name": "test-stdlib",
|
||||
"version": "0.0.0-test",
|
||||
"digest": digest,
|
||||
});
|
||||
std::fs::write(
|
||||
root.join("stdlib.json"),
|
||||
serde_json::to_vec(&manifest).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dev_bundle_verifies_and_resolves() {
|
||||
let bundle = StdlibBundle::load(dev_bundle()).unwrap();
|
||||
assert!(bundle.digest.starts_with("sha256:"));
|
||||
fn synthetic_bundle_verifies_and_resolves() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_synthetic_bundle(dir.path());
|
||||
let bundle = StdlibBundle::load(dir.path()).unwrap();
|
||||
assert_eq!(bundle.version(), "0.0.0-test");
|
||||
let io = bundle.resolve("io").unwrap();
|
||||
assert_eq!(io.relative_path, "io.mq.md");
|
||||
assert!(io.package.instance_id.starts_with("std:marqdo-stdlib@"));
|
||||
assert!(io.package.instance_id.starts_with("std:test-stdlib@"));
|
||||
assert!(bundle.resolve("../escape").is_err());
|
||||
assert!(bundle.resolve("/absolute").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -476,44 +506,31 @@ mod tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bundle = dir.path().join("stdlib");
|
||||
std::fs::create_dir_all(&bundle).unwrap();
|
||||
for entry in std::fs::read_dir(dev_bundle()).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let target = bundle.join(entry.file_name());
|
||||
if entry.path().is_dir() {
|
||||
copy_dir(&entry.path(), &target);
|
||||
} else {
|
||||
std::fs::copy(entry.path(), target).unwrap();
|
||||
}
|
||||
}
|
||||
write_synthetic_bundle(&bundle);
|
||||
let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf()))
|
||||
.unwrap()
|
||||
.expect("sibling stdlib");
|
||||
assert_eq!(found.root, bundle.canonicalize().unwrap());
|
||||
assert_eq!(found.root(), bundle.canonicalize().unwrap());
|
||||
}
|
||||
|
||||
fn copy_dir(source: &std::path::Path, target: &std::path::Path) {
|
||||
std::fs::create_dir_all(target).unwrap();
|
||||
for entry in std::fs::read_dir(source).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let destination = target.join(entry.file_name());
|
||||
if entry.path().is_dir() {
|
||||
copy_dir(&entry.path(), &destination);
|
||||
} else {
|
||||
std::fs::copy(entry.path(), destination).unwrap();
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn bad_override_fails_closed_even_with_a_valid_sibling() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let sibling = dir.path().join("stdlib");
|
||||
std::fs::create_dir_all(&sibling).unwrap();
|
||||
write_synthetic_bundle(&sibling);
|
||||
let error = StdlibBundle::discover_with(
|
||||
Some(dir.path().join("missing")),
|
||||
Some(dir.path().to_path_buf()),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.contains("cannot open stdlib directory"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digest_tamper_is_rejected() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let source = dev_bundle();
|
||||
for entry in std::fs::read_dir(&source).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
if entry.path().is_file() {
|
||||
std::fs::copy(entry.path(), dir.path().join(entry.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
write_synthetic_bundle(dir.path());
|
||||
std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap();
|
||||
let error = StdlibBundle::load(dir.path()).unwrap_err();
|
||||
assert!(error.contains("digest mismatch"), "{error}");
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
//! checks, not an OS-sandbox proof; `tools/ci/check_dependency_boundaries.py`
|
||||
//! adds the Cargo-metadata graph gate.
|
||||
|
||||
#[path = "support/stdlib.rs"]
|
||||
pub mod stdlib_support;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -138,7 +141,14 @@ fn engine_depends_on_the_neutral_host_contract_only() {
|
||||
|
||||
#[test]
|
||||
fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
|
||||
let root = repo_root().join("stdlib");
|
||||
let root = stdlib_support::bundle_dir();
|
||||
// Phase A (ADR-0070): the pinned Bundle is still the checkout tree. Phase B
|
||||
// replaces this assertion when the ecosystem Bundle becomes the input.
|
||||
assert_eq!(
|
||||
root,
|
||||
repo_root().join("stdlib").canonicalize().unwrap(),
|
||||
"the Phase A stdlib pin must resolve to the in-repo stdlib tree"
|
||||
);
|
||||
let manifest: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
|
||||
assert_eq!(manifest["name"], "marqdo-stdlib");
|
||||
@@ -153,7 +163,7 @@ fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
|
||||
|
||||
#[test]
|
||||
fn stdlib_imports_resolve_inside_the_bundle() {
|
||||
let root = repo_root().join("stdlib");
|
||||
let root = stdlib_support::bundle_dir();
|
||||
for entry in walk_markdown(&root) {
|
||||
let is_test = entry.starts_with(root.join("tests"));
|
||||
let text = read(&entry);
|
||||
@@ -488,7 +498,7 @@ const _: fn(marqdo_value::Value) = |value| match value {
|
||||
/// hard-coded runtime names. Recompute the canonical metadata digest.
|
||||
#[test]
|
||||
fn official_stdlib_public_aliases_are_verified_metadata() {
|
||||
let root = repo_root().join("stdlib");
|
||||
let root = stdlib_support::bundle_dir();
|
||||
let manifest: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
|
||||
let aliases = manifest["public_aliases"]
|
||||
@@ -687,22 +697,18 @@ fn plugin_contract_carries_no_native_execution() {
|
||||
"native host must own plugin `{module}`"
|
||||
);
|
||||
}
|
||||
// ADR-0072: the SDK is an independent repository pinned to a contract
|
||||
// revision. It must not be reintroduced as a second in-workspace copy.
|
||||
assert!(
|
||||
!root.join("crates/marqdo-plugin-sdk").exists(),
|
||||
"the plugin SDK moved to cflmy/marqdo-plugin-sdk (ADR-0072)"
|
||||
);
|
||||
let manifest = read(&root.join("Cargo.toml"));
|
||||
assert!(
|
||||
!manifest.contains("marqdo-plugin-sdk"),
|
||||
"the plugin SDK must not return as a CLI workspace member"
|
||||
);
|
||||
let current = read(&root.join("docs/architecture/CURRENT.md"));
|
||||
assert!(
|
||||
current.contains("cflmy/marqdo-plugin-sdk") && current.contains("ADR-0072"),
|
||||
"CURRENT.md must name the independent SDK repository decision"
|
||||
);
|
||||
let sdk = read(&root.join("crates/marqdo-plugin-sdk/Cargo.toml"));
|
||||
for forbidden in [
|
||||
"marqdo-host",
|
||||
"marqdo-cli",
|
||||
"libloading",
|
||||
"marqdo-worker-ipc",
|
||||
] {
|
||||
assert!(
|
||||
!sdk.contains(forbidden),
|
||||
"the plugin SDK must not depend on `{forbidden}`"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// E01/E04: the independent embedding consumer is a real package outside the
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
//! expectation; the checked-in goldens were reviewed individually.
|
||||
|
||||
use std::fs;
|
||||
#[path = "support/stdlib.rs"]
|
||||
pub mod stdlib_support;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use marqdo_host::{Capabilities, StdHost};
|
||||
@@ -292,7 +295,7 @@ fn normalise_relative(path: &Path) -> String {
|
||||
/// unique registry, run the single binding pass and install its table. There is
|
||||
/// no `print_override` and no runtime name guessing.
|
||||
fn bind_calls_with_stdlib_aliases(program: &mut Program) {
|
||||
let root = repo_root().join("stdlib");
|
||||
let root = stdlib_support::bundle_dir();
|
||||
let mut loaded = std::collections::BTreeSet::new();
|
||||
let mut official = Vec::new();
|
||||
if root.join("stdlib.json").is_file() {
|
||||
@@ -429,7 +432,7 @@ fn install_entry_stdlib_imports(
|
||||
module_id: &ModuleId,
|
||||
analysis: &marqdo_frontend::AnalysisResult,
|
||||
) {
|
||||
let root = repo_root().join("stdlib");
|
||||
let root = stdlib_support::bundle_dir();
|
||||
let Some(imports) = analysis
|
||||
.document
|
||||
.frontmatter()
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
#[path = "support/observation.rs"]
|
||||
pub mod observation;
|
||||
|
||||
#[path = "support/stdlib.rs"]
|
||||
pub mod stdlib_support;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
@@ -109,7 +112,8 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
|
||||
|
||||
#[test]
|
||||
fn p2_stdlib_table_also_runs_in_pure_mode() {
|
||||
let path = repo_root().join("stdlib").join("tests").join("table.mq.md");
|
||||
let bundle = stdlib_support::bundle_dir();
|
||||
let path = bundle.join("tests").join("table.mq.md");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args([
|
||||
"run",
|
||||
@@ -119,8 +123,8 @@ fn p2_stdlib_table_also_runs_in_pure_mode() {
|
||||
"--output",
|
||||
"json",
|
||||
])
|
||||
.current_dir(repo_root().join("stdlib"))
|
||||
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
|
||||
.current_dir(&bundle)
|
||||
.env("MARQDO_STDLIB_DIR", &bundle)
|
||||
.output()
|
||||
.expect("run table self-test");
|
||||
assert_eq!(
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
//! runtime name special case and no hard-coded per-function scan.
|
||||
#![cfg(unix)]
|
||||
|
||||
#[path = "support/stdlib.rs"]
|
||||
pub mod stdlib_support;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
@@ -35,15 +38,6 @@ impl Drop for TempDir {
|
||||
}
|
||||
}
|
||||
|
||||
fn repo() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
|
||||
command.args(args).current_dir(dir);
|
||||
@@ -62,7 +56,7 @@ fn stdout(output: &Output) -> String {
|
||||
}
|
||||
|
||||
fn copy_stdlib(target: &Path) {
|
||||
let source = repo().join("stdlib");
|
||||
let source = stdlib_support::bundle_dir();
|
||||
std::fs::create_dir_all(target).unwrap();
|
||||
for entry in std::fs::read_dir(&source).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
//! Bundled stdlib (`std:`) and frozen-CLI closure tests (CM-A10).
|
||||
|
||||
#[path = "support/stdlib.rs"]
|
||||
pub mod stdlib_support;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
fn repo_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
fn binary() -> &'static str {
|
||||
env!("CARGO_BIN_EXE_marqdo")
|
||||
}
|
||||
|
||||
fn stdlib_dir() -> PathBuf {
|
||||
repo_root().join("stdlib")
|
||||
stdlib_support::bundle_dir()
|
||||
}
|
||||
|
||||
fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output {
|
||||
|
||||
@@ -3,24 +3,18 @@
|
||||
#[path = "support/observation.rs"]
|
||||
pub mod observation;
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
#[path = "support/stdlib.rs"]
|
||||
pub mod stdlib_support;
|
||||
|
||||
fn repo_root() -> std::path::PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.to_path_buf()
|
||||
}
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn stdlib_http_parses_chunked_responses_and_builds_requests() {
|
||||
let bundle = stdlib_support::bundle_dir();
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args(["run", "tests/http.mq.md", "--output", "json"])
|
||||
.current_dir(repo_root().join("stdlib"))
|
||||
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
|
||||
.current_dir(&bundle)
|
||||
.env("MARQDO_STDLIB_DIR", &bundle)
|
||||
.output()
|
||||
.expect("run http self-test");
|
||||
assert_eq!(
|
||||
|
||||
@@ -8,20 +8,14 @@
|
||||
#[path = "support/observation.rs"]
|
||||
pub mod observation;
|
||||
|
||||
#[path = "support/stdlib.rs"]
|
||||
pub mod stdlib_support;
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
fn repo_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
static FS_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
|
||||
@@ -33,7 +27,7 @@ fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
|
||||
}
|
||||
|
||||
fn stdlib_dir() -> PathBuf {
|
||||
repo_root().join("stdlib")
|
||||
stdlib_support::bundle_dir()
|
||||
}
|
||||
|
||||
struct TestFile {
|
||||
|
||||
@@ -3,23 +3,17 @@
|
||||
#[path = "support/observation.rs"]
|
||||
pub mod observation;
|
||||
|
||||
use std::path::Path;
|
||||
#[path = "support/stdlib.rs"]
|
||||
pub mod stdlib_support;
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn repo_root() -> std::path::PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.unwrap()
|
||||
.parent()
|
||||
.unwrap()
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
fn run_table_self_test() -> serde_json::Value {
|
||||
let bundle = stdlib_support::bundle_dir();
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args(["run", "tests/table.mq.md", "--output", "json"])
|
||||
.current_dir(repo_root().join("stdlib"))
|
||||
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
|
||||
.current_dir(&bundle)
|
||||
.env("MARQDO_STDLIB_DIR", &bundle)
|
||||
.output()
|
||||
.expect("run table self-test");
|
||||
assert_eq!(
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
//! Pinned stdlib Bundle resolver shared by test harnesses (ADR-0070).
|
||||
//!
|
||||
//! Product tests consume one explicit Bundle whose identity is pinned in
|
||||
//! `tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest and
|
||||
//! alias digest). `MARQDO_TEST_STDLIB_BUNDLE` may change the location, but the
|
||||
//! Bundle must still match the pin; `MARQDO_TEST_BUNDLE_PIN` may change the pin
|
||||
//! file. A bad explicit input fails even when the default location is valid —
|
||||
//! there is no silent fallback.
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub const BUNDLE_ENV: &str = "MARQDO_TEST_STDLIB_BUNDLE";
|
||||
pub const PIN_ENV: &str = "MARQDO_TEST_BUNDLE_PIN";
|
||||
|
||||
/// The checkout root (this test support module lives in `crates/cli/tests`).
|
||||
pub fn repo_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
.expect("crates directory")
|
||||
.parent()
|
||||
.expect("repository root")
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
/// Pin file path, overridable for a candidate Bundle.
|
||||
pub fn pin_path() -> PathBuf {
|
||||
std::env::var_os(PIN_ENV)
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
repo_root()
|
||||
.join("tools")
|
||||
.join("stdlib")
|
||||
.join("bundle-pin.json")
|
||||
})
|
||||
}
|
||||
|
||||
/// One pinned Bundle identity (`tools/stdlib/bundle-pin.json`).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BundlePin {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub source_commit: String,
|
||||
pub source_path: PathBuf,
|
||||
pub tree_digest: String,
|
||||
pub aliases_digest: String,
|
||||
}
|
||||
|
||||
impl BundlePin {
|
||||
pub fn load(path: &Path) -> Self {
|
||||
let text = std::fs::read_to_string(path)
|
||||
.unwrap_or_else(|error| panic!("cannot read Bundle pin {}: {error}", path.display()));
|
||||
let value: serde_json::Value = serde_json::from_str(&text)
|
||||
.unwrap_or_else(|error| panic!("invalid Bundle pin {}: {error}", path.display()));
|
||||
assert_eq!(
|
||||
value.get("schema").and_then(serde_json::Value::as_str),
|
||||
Some("marqdo.stdlib-bundle-pin"),
|
||||
"{} must use the marqdo.stdlib-bundle-pin schema",
|
||||
path.display()
|
||||
);
|
||||
assert_eq!(
|
||||
value
|
||||
.get("schema_version")
|
||||
.and_then(serde_json::Value::as_u64),
|
||||
Some(1),
|
||||
"{} must use pin schema_version 1",
|
||||
path.display()
|
||||
);
|
||||
let source = value
|
||||
.get("source")
|
||||
.unwrap_or_else(|| panic!("Bundle pin {} has no source object", path.display()));
|
||||
let source_path = source
|
||||
.get("path")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_else(|| panic!("Bundle pin {} has no source.path", path.display()));
|
||||
validate_relative(source_path)
|
||||
.unwrap_or_else(|error| panic!("Bundle pin {} source.path: {error}", path.display()));
|
||||
Self {
|
||||
name: required_str(&value, "name", path),
|
||||
version: required_str(&value, "version", path),
|
||||
source_commit: required_str(source, "commit", path),
|
||||
source_path: PathBuf::from(source_path),
|
||||
tree_digest: required_str(&value, "tree_digest", path),
|
||||
aliases_digest: required_str(&value, "aliases_digest", path),
|
||||
}
|
||||
}
|
||||
|
||||
/// The committed pin for the current checkout.
|
||||
pub fn committed() -> Self {
|
||||
Self::load(&pin_path())
|
||||
}
|
||||
}
|
||||
|
||||
fn required_str(value: &serde_json::Value, field: &str, path: &Path) -> String {
|
||||
value
|
||||
.get(field)
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|text| !text.is_empty())
|
||||
.unwrap_or_else(|| panic!("Bundle pin {} has no `{field}`", path.display()))
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// One verified Bundle on disk.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Bundle {
|
||||
root: PathBuf,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub tree_digest: String,
|
||||
pub aliases_digest: String,
|
||||
}
|
||||
|
||||
impl Bundle {
|
||||
/// Resolve the Bundle for a product test: explicit override or pinned path,
|
||||
/// verified against the pin.
|
||||
pub fn pinned() -> Self {
|
||||
let pin = BundlePin::committed();
|
||||
let explicit = std::env::var_os(BUNDLE_ENV).map(PathBuf::from);
|
||||
let root = explicit
|
||||
.clone()
|
||||
.unwrap_or_else(|| repo_root().join(&pin.source_path));
|
||||
let bundle = Self::verify(&root).unwrap_or_else(|error| match &explicit {
|
||||
Some(_) => panic!(
|
||||
"{BUNDLE_ENV} does not name a valid stdlib Bundle at {}: {error}",
|
||||
root.display()
|
||||
),
|
||||
None => panic!(
|
||||
"pinned stdlib Bundle at {} is invalid: {error}",
|
||||
root.display()
|
||||
),
|
||||
});
|
||||
let mismatches = [
|
||||
("name", &pin.name, &bundle.name),
|
||||
("version", &pin.version, &bundle.version),
|
||||
("tree_digest", &pin.tree_digest, &bundle.tree_digest),
|
||||
(
|
||||
"aliases_digest",
|
||||
&pin.aliases_digest,
|
||||
&bundle.aliases_digest,
|
||||
),
|
||||
];
|
||||
for (field, expected, actual) in mismatches {
|
||||
assert_eq!(
|
||||
expected,
|
||||
actual,
|
||||
"stdlib Bundle at {} does not match the pin field `{field}`",
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
for required in ["stdlib.json", "io.mq.md", "io/console.mq.md"] {
|
||||
assert!(
|
||||
bundle.root.join(required).is_file(),
|
||||
"stdlib Bundle at {} is missing required file {required}",
|
||||
bundle.root.display()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
pin.source_commit.len(),
|
||||
40,
|
||||
"the pin must record a full source commit, got {:?}",
|
||||
pin.source_commit
|
||||
);
|
||||
bundle
|
||||
}
|
||||
|
||||
/// Verify one unpacked Bundle root.
|
||||
pub fn verify(root: &Path) -> Result<Self, String> {
|
||||
if !root.is_dir() {
|
||||
return Err(format!("not a directory: {}", root.display()));
|
||||
}
|
||||
let manifest_path = root.join("stdlib.json");
|
||||
if !manifest_path.is_file() {
|
||||
return Err(format!("missing manifest: {}", manifest_path.display()));
|
||||
}
|
||||
let text = std::fs::read_to_string(&manifest_path)
|
||||
.map_err(|error| format!("cannot read {}: {error}", manifest_path.display()))?;
|
||||
let manifest: serde_json::Value = serde_json::from_str(&text)
|
||||
.map_err(|error| format!("invalid {}: {error}", manifest_path.display()))?;
|
||||
let name = manifest
|
||||
.get("name")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.ok_or_else(|| format!("{} has no name", manifest_path.display()))?
|
||||
.to_string();
|
||||
let version = manifest
|
||||
.get("version")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.ok_or_else(|| format!("{} has no version", manifest_path.display()))?
|
||||
.to_string();
|
||||
let declared = manifest
|
||||
.get("digest")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.ok_or_else(|| format!("{} has no digest", manifest_path.display()))?
|
||||
.to_string();
|
||||
let actual = tree_digest(root)?;
|
||||
if declared != actual {
|
||||
return Err(format!(
|
||||
"tree digest mismatch: stdlib.json declares {declared}, the files are {actual}"
|
||||
));
|
||||
}
|
||||
let aliases = manifest
|
||||
.get("public_aliases")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let declared_aliases = manifest
|
||||
.get("aliases_digest")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(ToString::to_string);
|
||||
let actual_aliases = aliases_digest(&aliases);
|
||||
match (declared_aliases, aliases.is_empty()) {
|
||||
(Some(declared_aliases), _) => {
|
||||
if declared_aliases != actual_aliases {
|
||||
return Err(format!(
|
||||
"alias digest mismatch: stdlib.json declares {declared_aliases}, \
|
||||
the alias table is {actual_aliases}"
|
||||
));
|
||||
}
|
||||
}
|
||||
(None, false) => {
|
||||
return Err(format!(
|
||||
"{} declares public_aliases without aliases_digest",
|
||||
manifest_path.display()
|
||||
));
|
||||
}
|
||||
(None, true) => {}
|
||||
}
|
||||
Ok(Self {
|
||||
root: root
|
||||
.canonicalize()
|
||||
.map_err(|error| format!("cannot canonicalize {}: {error}", root.display()))?,
|
||||
name,
|
||||
version,
|
||||
tree_digest: actual,
|
||||
aliases_digest: actual_aliases,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve and verify the pinned Bundle once per test process.
|
||||
pub fn bundle() -> &'static Bundle {
|
||||
static BUNDLE: std::sync::OnceLock<Bundle> = std::sync::OnceLock::new();
|
||||
BUNDLE.get_or_init(Bundle::pinned)
|
||||
}
|
||||
|
||||
/// Bundle root for fixtures and `MARQDO_STDLIB_DIR`.
|
||||
pub fn bundle_dir() -> PathBuf {
|
||||
bundle().root().to_path_buf()
|
||||
}
|
||||
|
||||
/// Content digest over all `.mq.md` files: sorted relative path, NUL, bytes, NUL.
|
||||
pub fn tree_digest(root: &Path) -> Result<String, String> {
|
||||
let mut files = Vec::new();
|
||||
collect_markdown(root, root, &mut files)?;
|
||||
files.sort();
|
||||
let mut hasher = Sha256::new();
|
||||
for (relative, path) in files {
|
||||
let bytes = std::fs::read(&path)
|
||||
.map_err(|error| format!("cannot read {}: {error}", path.display()))?;
|
||||
hasher.update(relative.as_bytes());
|
||||
hasher.update([0]);
|
||||
hasher.update(&bytes);
|
||||
hasher.update([0]);
|
||||
}
|
||||
Ok(format!("sha256:{}", hex(&hasher.finalize())))
|
||||
}
|
||||
|
||||
/// Canonical digest over the official public-alias table.
|
||||
pub fn aliases_digest(aliases: &[serde_json::Value]) -> String {
|
||||
let mut entries: Vec<&serde_json::Value> = aliases.iter().collect();
|
||||
entries.sort_by_key(|alias| {
|
||||
(
|
||||
alias["target_module"].as_str().unwrap_or("").to_string(),
|
||||
alias["target_function"].as_str().unwrap_or("").to_string(),
|
||||
)
|
||||
});
|
||||
let mut hasher = Sha256::new();
|
||||
for alias in entries {
|
||||
if let Some(module) = alias["target_module"].as_str() {
|
||||
hasher.update(module.as_bytes());
|
||||
}
|
||||
hasher.update([0]);
|
||||
if let Some(function) = alias["target_function"].as_str() {
|
||||
hasher.update(function.as_bytes());
|
||||
}
|
||||
hasher.update([0]);
|
||||
let mut names: Vec<&str> = alias["public_names"]
|
||||
.as_array()
|
||||
.map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
|
||||
.unwrap_or_default();
|
||||
names.sort();
|
||||
for name in names {
|
||||
hasher.update(name.as_bytes());
|
||||
hasher.update([0]);
|
||||
}
|
||||
}
|
||||
format!("sha256:{}", hex(&hasher.finalize()))
|
||||
}
|
||||
|
||||
fn collect_markdown(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
out: &mut Vec<(String, PathBuf)>,
|
||||
) -> Result<(), String> {
|
||||
let entries = std::fs::read_dir(dir)
|
||||
.map_err(|error| format!("cannot read {}: {error}", dir.display()))?;
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|error| format!("cannot read {}: {error}", dir.display()))?;
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect_markdown(root, &path, out)?;
|
||||
} else if path
|
||||
.file_name()
|
||||
.is_some_and(|name| name.to_string_lossy().ends_with(".mq.md"))
|
||||
{
|
||||
let relative = path
|
||||
.strip_prefix(root)
|
||||
.map_err(|_| "stdlib file escaped its root".to_string())?
|
||||
.components()
|
||||
.map(|component| component.as_os_str().to_string_lossy().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/");
|
||||
out.push((relative, path));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_relative(path: &str) -> Result<(), String> {
|
||||
let mut normalised = PathBuf::new();
|
||||
for component in Path::new(path).components() {
|
||||
match component {
|
||||
Component::Normal(part) => normalised.push(part),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
|
||||
return Err("must be a relative path inside the repository".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
if normalised.as_os_str().is_empty() {
|
||||
return Err("must not be empty".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
out.push_str(&format!("{byte:02x}"));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "marqdo-plugin-sdk"
|
||||
description = "Rust SDK for writing Marqdo plugins against ABI v1"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[dependencies]
|
||||
marqdo-plugin-abi = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Safe wrappers around the raw `MqBytes` / `MqOwnedBytes` ABI buffers.
|
||||
//!
|
||||
//! Ownership rules (see the canonical header):
|
||||
//! - [`BytesRef`] is a borrowed, validated view of host input; it is only
|
||||
//! valid for the call that produced it.
|
||||
//! - [`HostBuffer`] is plugin output allocated with the host allocator and
|
||||
//! handed back to the host, which frees it after copying.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::marker::PhantomData;
|
||||
use std::ptr;
|
||||
|
||||
use marqdo_plugin_abi::abi::{MqBytes, MqHostApi, MqOwnedBytes};
|
||||
|
||||
use crate::PluginError;
|
||||
|
||||
/// Validated borrowed view of an ABI byte buffer (`MqBytes`).
|
||||
pub struct BytesRef<'a> {
|
||||
raw: MqBytes,
|
||||
_marker: PhantomData<&'a [u8]>,
|
||||
}
|
||||
|
||||
impl<'a> BytesRef<'a> {
|
||||
/// Validate a raw borrowed buffer.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// If `raw.len > 0`, `raw.data` must point to `raw.len` initialized bytes
|
||||
/// that stay alive for `'a`. Within the ABI, `'a` must not outlive the
|
||||
/// call that produced the buffer.
|
||||
pub unsafe fn from_raw(raw: MqBytes) -> Result<Self, PluginError> {
|
||||
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<Self, PluginError> {
|
||||
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) };
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Per-invocation context passed to plugin handlers.
|
||||
//!
|
||||
//! The context is valid only for the duration of one invocation. It exists to
|
||||
//! carry host capabilities into the plugin: capability requests are answered
|
||||
//! by the host's authorization layer and can never be escalated by plugin
|
||||
//! code. Do not cache this value, its raw pointer or any capability token.
|
||||
|
||||
use marqdo_plugin_abi::abi::{
|
||||
MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MAX_CAPABILITY_REPLY_BYTES,
|
||||
};
|
||||
use marqdo_plugin_abi::PluginError;
|
||||
|
||||
use crate::bytes;
|
||||
|
||||
/// Context for one plugin invocation.
|
||||
pub struct CallContext {
|
||||
raw: *mut MqCallContext,
|
||||
host: &'static MqHostApi,
|
||||
}
|
||||
|
||||
impl CallContext {
|
||||
/// Wrap the host-provided context pointer.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `raw` must be the context pointer provided by the host for the current
|
||||
/// invocation, and `host` must be the validated host API table.
|
||||
pub(crate) unsafe fn new(raw: *mut MqCallContext, host: &'static MqHostApi) -> Self {
|
||||
Self { raw, host }
|
||||
}
|
||||
|
||||
/// The host API table of this plugin instance.
|
||||
pub fn host(&self) -> &'static MqHostApi {
|
||||
self.host
|
||||
}
|
||||
|
||||
/// Request an already-authorized host capability for this call.
|
||||
///
|
||||
/// `request` is a UTF-8 JSON capability request; the reply is opaque bytes
|
||||
/// owned by the host. The SDK copies the reply and releases the host buffer.
|
||||
pub fn capability_request(
|
||||
&mut self,
|
||||
name: &str,
|
||||
request: &[u8],
|
||||
) -> Result<Vec<u8>, 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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! Entry-point plumbing used by [`mq_plugin_entry!`](crate::mq_plugin_entry).
|
||||
//!
|
||||
//! These functions are the "runtime" of the SDK macro. They are public so the
|
||||
//! macro can reference them through `$crate` from a plugin crate, but they are
|
||||
//! not intended for direct use.
|
||||
|
||||
use std::panic::{catch_unwind, AssertUnwindSafe};
|
||||
use std::sync::atomic::{AtomicPtr, Ordering};
|
||||
|
||||
use marqdo_plugin_abi::abi::{
|
||||
check_host_api, result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi,
|
||||
MqPluginInvoke, ABI_MAJOR, ABI_MINOR, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
|
||||
MAX_RESULT_WIRE_BYTES,
|
||||
};
|
||||
use marqdo_plugin_abi::{PluginError, WireResponse};
|
||||
|
||||
use crate::bytes::{release_host_buffer, HostBuffer};
|
||||
use crate::call::CallContext;
|
||||
use crate::HandlerFn;
|
||||
|
||||
/// Host API table captured by the entry point for the plugin lifetime.
|
||||
static CURRENT_HOST: AtomicPtr<MqHostApi> = 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::<MqPluginApi>() 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) };
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Rust SDK for writing Marqdo native plugins against plugin ABI v1.
|
||||
//!
|
||||
//! The SDK is the plugin-developer side of `include/marqdo_plugin_abi_v1.h`.
|
||||
//! It hides the raw C layout behind safe wrappers and provides the
|
||||
//! [`mq_plugin_entry!`] macro that exports the required
|
||||
//! `mq_plugin_entry_v1` symbol:
|
||||
//!
|
||||
//! ```
|
||||
//! use marqdo_plugin_sdk::{mq_plugin_entry, CallContext, PluginError, Value};
|
||||
//!
|
||||
//! fn add(_ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, 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<Vec<u8>, 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;
|
||||
@@ -0,0 +1,245 @@
|
||||
//! End-to-end SDK tests: run the macro-generated entry point against a tiny
|
||||
//! in-process host table and invoke the registered export.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::ptr;
|
||||
|
||||
use marqdo_plugin_abi::abi::{
|
||||
result, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, MqPluginApi, MqPluginInvoke,
|
||||
ABI_MAJOR, ABI_MINOR,
|
||||
};
|
||||
|
||||
use crate::wire;
|
||||
use crate::{CallContext, PluginError, Value, WireRequest, WireResponse};
|
||||
|
||||
/// ABI v1 is single-threaded: the generated plugin stores the host table in a
|
||||
/// process-global. Serialize tests that call the entry point so they do not
|
||||
/// race (the SDK's own contract, not a test-only limitation).
|
||||
static ABI_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn abi_test_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
ABI_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestHostState {
|
||||
registrations: Vec<(String, String, MqPluginInvoke)>,
|
||||
}
|
||||
|
||||
unsafe extern "C" fn test_alloc(_host_data: *mut c_void, size: usize) -> *mut c_void {
|
||||
const HEADER: usize = 16;
|
||||
if size == 0 {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
let Ok(layout) = std::alloc::Layout::from_size_align(size + HEADER, 16) else {
|
||||
return ptr::null_mut();
|
||||
};
|
||||
// SAFETY: non-zero layout.
|
||||
let base = unsafe { std::alloc::alloc(layout) };
|
||||
if base.is_null() {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
// SAFETY: allocation has room for the header.
|
||||
unsafe { (base as *mut usize).write(size) };
|
||||
// SAFETY: offset within the allocation.
|
||||
unsafe { base.add(HEADER) as *mut c_void }
|
||||
}
|
||||
|
||||
unsafe extern "C" fn test_free(_host_data: *mut c_void, pointer: *mut c_void) {
|
||||
const HEADER: usize = 16;
|
||||
if pointer.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: only pointers from test_alloc are freed.
|
||||
unsafe {
|
||||
let base = (pointer as *mut u8).sub(HEADER);
|
||||
let size = (base as *const usize).read();
|
||||
std::alloc::dealloc(
|
||||
base,
|
||||
std::alloc::Layout::from_size_align_unchecked(size + HEADER, 16),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn test_register(
|
||||
host_data: *mut c_void,
|
||||
export_name: MqBytes,
|
||||
signature_wire: MqBytes,
|
||||
invoke: MqPluginInvoke,
|
||||
) -> i32 {
|
||||
if host_data.is_null() {
|
||||
return result::INVALID_ARGUMENT;
|
||||
}
|
||||
// SAFETY: host_data points at TestHostState for the test.
|
||||
let state = unsafe { &mut *(host_data as *mut TestHostState) };
|
||||
// SAFETY: buffers are valid for this callback.
|
||||
let name = match unsafe { export_name.as_slice() } {
|
||||
Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(),
|
||||
Err(_) => return result::INVALID_ARGUMENT,
|
||||
};
|
||||
// SAFETY: buffers are valid for this callback.
|
||||
let signature = match unsafe { signature_wire.as_slice() } {
|
||||
Ok(bytes) => String::from_utf8_lossy(bytes).into_owned(),
|
||||
Err(_) => return result::INVALID_ARGUMENT,
|
||||
};
|
||||
state.registrations.push((name, signature, invoke));
|
||||
result::OK
|
||||
}
|
||||
|
||||
unsafe extern "C" fn test_capability(
|
||||
_ctx: *mut MqCallContext,
|
||||
_name: MqBytes,
|
||||
_request: MqBytes,
|
||||
reply: *mut MqOwnedBytes,
|
||||
) -> i32 {
|
||||
if !reply.is_null() {
|
||||
// SAFETY: output pointer is non-NULL.
|
||||
unsafe { *reply = MqOwnedBytes::EMPTY };
|
||||
}
|
||||
result::UNSUPPORTED
|
||||
}
|
||||
|
||||
fn add(_ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, 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<TestHostState>,
|
||||
api: MqHostApi,
|
||||
}
|
||||
|
||||
fn test_host() -> TestHost {
|
||||
let mut state = Box::new(TestHostState::default());
|
||||
let api = MqHostApi {
|
||||
struct_size: std::mem::size_of::<MqHostApi>() 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);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Wire envelope helpers for plugin handlers.
|
||||
//!
|
||||
//! The canonical envelope is defined by `marqdo-plugin-abi` and documented in
|
||||
//! `spec/value-wire.md`: UTF-8 JSON, `wire_version == 1`, type-tagged values.
|
||||
//! Handlers normally do:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! fn add(ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, 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, PluginError> {
|
||||
WireRequest::from_json_bytes(bytes)
|
||||
}
|
||||
|
||||
/// Look up a typed argument by name.
|
||||
pub fn value_arg<'a>(
|
||||
values: &'a BTreeMap<String, Value>,
|
||||
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<String, Value>, name: &str) -> Result<i64, PluginError> {
|
||||
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<String, Value>,
|
||||
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<String, Value>, name: &str) -> Result<bool, PluginError> {
|
||||
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<Value>) -> Result<Vec<u8>, 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<Json>) -> Result<Vec<u8>, 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<Vec<u8>, 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<Option<Value>, PluginError> {
|
||||
WireResponse::from_json_bytes(bytes)?.typed_value()
|
||||
}
|
||||
+79
-31
@@ -75,6 +75,46 @@ The `spec/` tree contains only current contracts; retired specifications are in
|
||||
Git history and tagged archives. The earlier release records below describe
|
||||
their tagged binaries and are not current protocol claims.
|
||||
|
||||
## 0.11 Explicit stdlib Bundle input — issue #11 Phase A (unreleased)
|
||||
|
||||
Phase A lands the build-input boundary only: the stdlib production sources and
|
||||
the debug source fallback are still in this repository, and Phase B (the
|
||||
ecosystem-assembled Bundle, source removal and `std:` replacement) is **not**
|
||||
claimed. Executed candidate:
|
||||
`ab6b6b1a23ec064fbc7de943c52befca18142a56`; bundle source commit
|
||||
`2cbde54602c07f62a62f341400bc9cb4764a93f8`.
|
||||
|
||||
* `tools/stdlib/bundle-pin.json` pins `marqdo-stdlib@0.1.0` with tree digest
|
||||
`sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713`
|
||||
and alias digest
|
||||
`sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb`;
|
||||
`tools/stdlib/bundle.py` is the single resolver/verifier.
|
||||
* `tools/pack-stdlib.py` and `tools/release/package.py` require
|
||||
`--stdlib-dir` and accept `--bundle-pin`. A missing directory, missing
|
||||
manifest, tree/alias digest mismatch, pin mismatch or symlink fails before
|
||||
an archive is written; `RELEASE_INFO.json.stdlib.source` records the pinned
|
||||
kind/repository/commit/path.
|
||||
* Product, performance and release lanes resolve that Bundle
|
||||
(`crates/cli/tests/support/stdlib.rs`, `tools/perf/runner.py`). An explicit
|
||||
`MARQDO_TEST_STDLIB_BUNDLE`/`--stdlib-dir` changes the location but must match
|
||||
the pin; a bad override fails even when the default is valid. Loader unit
|
||||
tests build small synthetic Bundles.
|
||||
* `tools/ci/independent_build.py` exports a clean copy without `stdlib/`,
|
||||
builds `marqdo-cli` + `marqdo-provider-worker` with `--locked`, runs the
|
||||
language-only `tests/independent/language-only.mq.md`, and requires a
|
||||
stdlib-dependent run to fail closed with no sibling `stdlib/`. GitHub and
|
||||
Woodpecker run the lane.
|
||||
* Archive smoke and cold-install keep the missing-Bundle failure and now also
|
||||
require the language-only `factorial` call to succeed after the shipped
|
||||
`stdlib/` is moved aside. Two packaging runs from the same input and
|
||||
toolchain are byte-identical.
|
||||
|
||||
Evidence:
|
||||
[`evidence/2026-11-26-issue-11-phase-a.md`](evidence/2026-11-26-issue-11-phase-a.md).
|
||||
Runtime discovery is unchanged: `MARQDO_STDLIB_DIR` (invalid values still fail
|
||||
hard), then `stdlib/` next to the executable, then the debug-only source
|
||||
fallback. Phase B is gated on ecosystem issue #2 and the extension replacement
|
||||
evidence named by issue #11.
|
||||
## 0.12 Engine / Host Contract boundary — issue #13 (unreleased candidate)
|
||||
|
||||
This is an **internal architecture candidate**, not a release. The product
|
||||
@@ -120,36 +160,38 @@ Deliberately **UNVERIFIED** here: Windows/macOS native lanes, strict VM, WASM
|
||||
probe (target std not installed; `E0463`, not a forbidden native dependency)
|
||||
and performance/RSS. RC.4 evidence is not reused.
|
||||
|
||||
Remaining, separately owned work: stdlib Bundle Phase B (issue #11/#12),
|
||||
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.
|
||||
Remaining, separately owned work at that snapshot: stdlib Bundle Phase B (issue #11/#12),
|
||||
SDK physical repository after S07/S08 (**superseded by §0.13 — the split was
|
||||
reverted and the remote repository deleted**), regex/compression replacement
|
||||
under ADR-0062, foreign F-B (ADR-0063), platform and strict evidence, and the
|
||||
Engine/Native Host split only if the ADR-0071 reopening conditions appear.
|
||||
|
||||
## 0.13 Independent plugin SDK repository — issue #15 (unreleased candidate)
|
||||
## 0.13 Plugin SDK remains in the CLI workspace — split reverted (unreleased candidate)
|
||||
|
||||
This is a repository-ownership/architecture change, not a new product release.
|
||||
The contract and plugin ABI behaviour are unchanged. Evidence:
|
||||
[`evidence/2026-11-26-issue-15-sdk-independent-repository.md`](evidence/2026-11-26-issue-15-sdk-independent-repository.md);
|
||||
decision: [ADR-0072](adr/0072-sdk-independent-repository.md).
|
||||
This is an architecture correction, not a product/protocol change. Decision:
|
||||
[ADR-0073](adr/0073-sdk-stays-in-cli-workspace.md) (supersedes
|
||||
[ADR-0072](adr/0072-sdk-independent-repository.md)). Evidence:
|
||||
[`evidence/2026-11-26-issue-15-sdk-split-reverted.md`](evidence/2026-11-26-issue-15-sdk-split-reverted.md).
|
||||
|
||||
- The Rust SDK moved to the public repository
|
||||
[`cflmy/marqdo-plugin-sdk`](https://git.cflmy.cn/cflmy/marqdo-plugin-sdk)
|
||||
(commit `b31187a`), with its own workspace/lock, AGENTS rules, README, license
|
||||
and Woodpecker pipeline definition.
|
||||
- It consumes `marqdo-plugin-abi` from the CLI repository at the exact
|
||||
`rev = 2585915e16906dac75f8571bed02e7f6f868c6bc`; it never uses a `../cli`
|
||||
path, a floating branch, a submodule or a copied ABI/Value Wire.
|
||||
- The CLI repository no longer contains `crates/marqdo-plugin-sdk`,
|
||||
`tests/sdk-plugin` or the CLI-side SDK gate; the SDK does not appear in the
|
||||
workspace or `Cargo.lock`. The CLI does not depend on the SDK.
|
||||
- Clean-clone SDK build/tests and a real integration against the frozen
|
||||
released `3.0.0-rc.4` CLI pass (`Int 42`, tampered digest rejected). CLI
|
||||
workspace tests: 631 passed / 0 failed / 0 ignored (the five SDK tests moved
|
||||
to the SDK repository). The SDK
|
||||
repository's CI repeats those checks; enabling the Woodpecker project for the
|
||||
new repository is an administrative follow-up, not a code claim.
|
||||
- Engine/Native Host remain in the CLI workspace under ADR-0071; no other
|
||||
repository split is approved by this change.
|
||||
- The public `cflmy/marqdo-plugin-sdk` repository was **deleted**. The SDK
|
||||
source is restored as the CLI workspace crate `crates/marqdo-plugin-sdk`, with
|
||||
the same contract-only dependency graph (`marqdo-plugin-abi` + serde); it is
|
||||
not a remote repository, mirror or submodule.
|
||||
- The CLI keeps the atomic plugin-development surface: C header, `spec/`, the
|
||||
`marqdo-plugin-abi` contract, SDK helpers, fixture and real CLI invocation
|
||||
test change in one workspace/lock/candidate SHA. No cross-repository `rev`
|
||||
pin remains.
|
||||
- `tests/sdk-plugin` and `tools/ci/check_plugin_sdk.py` are restored; the gate
|
||||
builds the fixture with only the public SDK and invokes it through the real
|
||||
CLI with explicit trust/grant, rejecting a tampered artifact digest.
|
||||
- Logical ADR-0071 boundaries are unchanged: the runtime depends only on the
|
||||
neutral contract, `marqdo-plugin-abi` is a pure contract, loader/worker live
|
||||
in `marqdo-host::plugin`, CLI is the single assembly point.
|
||||
- External plugin access is unchanged: the CLI product and public repository
|
||||
carry the header/spec/SDK/loader; plugin authors compile their plugin, not the
|
||||
CLI. Engine/Native Host remain in the workspace; no other split is planned.
|
||||
- ADR-0072 and the old issue-#15 evidence carry Superseded banners. The remote
|
||||
replica is gone; Git history retains the decision/implementation record.
|
||||
|
||||
## 0.10 Closed public Analysis boundary — issue #10 (RC.4 released)
|
||||
|
||||
@@ -432,6 +474,9 @@ ownership / core resource kinds), ADR-0063 (foreign F-A). Executed evidence:
|
||||
recompute both digests with the runtime algorithm and fail on mismatch; smoke
|
||||
removes the bundle and requires a fail-closed run (no source fallback). Release
|
||||
discovery only falls back to the compile-time source tree in debug builds.
|
||||
Since issue #11 Phase A the Bundle is one required explicit build input
|
||||
(`--stdlib-dir`) with a pinned identity and a recorded source commit
|
||||
(ADR-0070); see §0.11.
|
||||
- **H-04 core resource kinds:** `marqdo_host::CORE_RESOURCE_KINDS` is the single
|
||||
registry used by the CLI manifest validator and every trusted host registration
|
||||
path; all six core kinds are rejected as a provider name and as a declared kind
|
||||
@@ -759,9 +804,11 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
|
||||
routed to the bundled stdlib (Compat-C, ADR-0030/0031); there is no legacy
|
||||
host formatter. `tools/pack-stdlib.py` additionally emits a byte-deterministic
|
||||
offline archive + descriptor as an extraction-ready artifact
|
||||
([evidence](evidence/2026-11-20-stdlib-package.md)). The stdlib intentionally
|
||||
stays in this repository for now (ADR-0039); extraction is a future option
|
||||
when size/release cadence requires it, not a pending gate.
|
||||
([evidence](evidence/2026-11-20-stdlib-package.md)). Issue #11 Phase A now
|
||||
consumes the Bundle through one explicit `--stdlib-dir` and one pinned
|
||||
identity (ADR-0070, §0.11); the production sources still stay in this
|
||||
repository until Phase B, which is gated on ecosystem issue #2 and the
|
||||
extension replacement evidence.
|
||||
- Resource streams (RFC-CM CM-A06, ADR-0025/0026/0040): opaque host-issued
|
||||
`Resource` handles with `resource.open/read/write/close`; bytes move only
|
||||
through `Memory`; stdin is read-only over one shared run cursor; stdout and
|
||||
@@ -780,7 +827,8 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
|
||||
snapshot; the current edge is `marqdo-runtime -> marqdo-host-contract` under
|
||||
ADR-0071), the bundled stdlib digest and the stdio/file/TCP endpoints; `crates/cli/tests/stdlib_product.rs`
|
||||
runs every public stdlib module (`clock/compress/console/csv/datetime/demo/env/format/fs/http/io/json/path/process/random/regex/stream/table/text/utf8`)
|
||||
through `std:` imports over `stdlib/tests/*.mq.md`. `tools/pack-stdlib.py`
|
||||
through `std:` imports over `stdlib/tests/*.mq.md` resolved from the pinned
|
||||
Bundle (`crates/cli/tests/support/stdlib.rs`). `tools/pack-stdlib.py`
|
||||
now sorts `.mq.md` by the same relative path key as the CLI. Source/test baseline
|
||||
`0d40de7`; later docs-only commits keep code/test bytes identical. Evidence:
|
||||
[`docs-and-test-migration`](evidence/2026-11-21-docs-and-test-migration.md).
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# ADR-0070 — One explicit stdlib Bundle build input (Phase A)
|
||||
|
||||
Status: **Accepted for implementation on the 3.0 prerelease line** (2026-11-26).
|
||||
Relates to: issue
|
||||
[#11](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11), ADR-0028 (bundled
|
||||
stdlib and `std:` imports), ADR-0039 (deferred extraction), ADR-0058 (public
|
||||
aliases), ADR-0062 (resource ownership), ADR-0068 (single current public
|
||||
contracts).
|
||||
Evidence:
|
||||
[`docs/evidence/2026-11-26-stdlib-source-coupling-inventory.md`](../evidence/2026-11-26-stdlib-source-coupling-inventory.md).
|
||||
|
||||
## Context
|
||||
|
||||
Issue #11 starts the extraction that ADR-0039 deferred: the CLI and the
|
||||
Provider Worker must build and run on their own, while a release is assembled
|
||||
from one explicitly provided, verifiable stdlib Bundle. The extraction trigger
|
||||
listed by ADR-0039 is now real: an ecosystem repository pins component commits
|
||||
and assembles the production Bundle, and nine component repositories own module
|
||||
sources.
|
||||
|
||||
At the implementation baseline `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` the
|
||||
stdlib source directory is implicit in four different ways, documented in the
|
||||
inventory linked above:
|
||||
|
||||
* both packaging entry points read the checkout's `stdlib/` with no build
|
||||
argument (`tools/pack-stdlib.py`, `tools/release/package.py`);
|
||||
* product tests, the semantic harness and the P2 closure lane rebuild
|
||||
`repo_root()/stdlib` independently;
|
||||
* the performance runner silently falls back to `ROOT / "stdlib"` when the
|
||||
binary has no sibling bundle;
|
||||
* the debug CLI resolves a compile-time source tree
|
||||
(`CARGO_MANIFEST_DIR/../../stdlib`) after the explicit override and the
|
||||
sibling directory.
|
||||
|
||||
Separating compile, package and product-test lanes later requires changing all
|
||||
of them at once, and none of them records which Bundle commit produced a test
|
||||
run. The runtime contracts themselves — `stdlib.json`, the
|
||||
`marqdo.stdlib-package` descriptor, Analysis `project.stdlib` and Observation
|
||||
identity — are not the problem and must not change.
|
||||
|
||||
## Decision
|
||||
|
||||
### 1. Explicit build input
|
||||
|
||||
`tools/pack-stdlib.py` and `tools/release/package.py` accept the same required
|
||||
`--stdlib-dir PATH` argument. It names an unpacked Bundle root that contains
|
||||
`stdlib.json`. There is no implicit default: a missing path, a missing manifest,
|
||||
a tree-digest mismatch, an alias-digest mismatch or a missing required module
|
||||
fails the command before any archive is written. Both entry points keep the
|
||||
existing deterministic archive layout, descriptor fields, digest algorithms
|
||||
and checksums.
|
||||
|
||||
Both entry points also accept an optional `--bundle-pin PATH`. When given, the
|
||||
input must match the pinned identity and the release record names the pinned
|
||||
source commit; the pin is not a substitute for verifying the Bundle's own
|
||||
manifest.
|
||||
|
||||
### 2. One pinned Bundle identity
|
||||
|
||||
`tools/stdlib/bundle-pin.json` records the Bundle name, version, source
|
||||
repository and commit, tree digest and alias digest. `tools/stdlib/bundle.py`
|
||||
is the single resolver and verifier for source-side consumers: tests, the
|
||||
performance runner and release CI resolve the Bundle through it instead of
|
||||
concatenating `stdlib/`.
|
||||
|
||||
An explicit `MARQDO_TEST_STDLIB_BUNDLE` (tests) or `--stdlib-dir` (tools) takes
|
||||
precedence over the pin's default location, but the input must still verify
|
||||
against the pin's digests. An invalid explicit input fails even when a valid
|
||||
sibling Bundle exists; silent fallback is forbidden. Phase B updates the pin to
|
||||
the Bundle assembled by the ecosystem repository; the algorithm does not change.
|
||||
|
||||
### 3. Runtime contract unchanged
|
||||
|
||||
`MARQDO_STDLIB_DIR` remains the explicit runtime override (invalid values fail
|
||||
hard), followed by `stdlib/` next to the executable. The debug-only
|
||||
compile-time source fallback remains in Phase A so the development loop keeps
|
||||
working; it is removed in Phase B together with the in-repo production sources.
|
||||
`stdlib.json`, `marqdo.stdlib-package`, Analysis `project.stdlib`, module ids
|
||||
and Observation identity keep their current shapes and values.
|
||||
|
||||
### 4. Separated test lanes
|
||||
|
||||
The lanes become explicit:
|
||||
|
||||
* **independent compilation** — `cargo build --locked -p marqdo-cli
|
||||
-p marqdo-provider-worker` in a copy without `stdlib/`, then a language-only
|
||||
program through the real CLI;
|
||||
* **loader unit tests** — small synthetic bundles built in a temporary
|
||||
directory, so loader logic does not depend on the product tree;
|
||||
* **product tests** — the whole pinned Bundle through `std:` and the real CLI;
|
||||
* **conformance** — the frozen, independent fixture corpus, unchanged.
|
||||
|
||||
### 5. Phase B gate
|
||||
|
||||
Phase B (switch to the ecosystem-assembled Bundle, delete the in-repo
|
||||
production sources, the debug source fallback and the replaced `std:` entries)
|
||||
requires the accepted component commits of ecosystem issue #2 and the extension
|
||||
replacement evidence named by issue #11. This ADR records the Phase A input
|
||||
boundary only; it does not authorize deleting sources or changing `std:`
|
||||
semantics.
|
||||
|
||||
## Consequences
|
||||
|
||||
* A packaging run can be pointed at a downloaded or separately built Bundle and
|
||||
still produce the same deterministic archive and `RELEASE_INFO.json` record.
|
||||
* Every product/perf CI run names the Bundle commit and digest it used; a
|
||||
stale Bundle is visible instead of implicit.
|
||||
* Phase B becomes a pin/CI change plus source removal, not a simultaneous
|
||||
rewrite of the test lanes.
|
||||
* The repository still carries the Bundle in Phase A, so the extraction is not
|
||||
claimed as complete. `docs/STATUS.md` must record the Phase A state, not the
|
||||
final externalized state.
|
||||
|
||||
## Non-goals
|
||||
|
||||
* Changing `std:` spelling, digest algorithms, module ids, public aliases or
|
||||
the `stdlib.json`/descriptor shapes.
|
||||
* Fetching a Bundle over the network, adding a package registry or a signature
|
||||
scheme.
|
||||
* Removing the debug source fallback, the in-repo `stdlib/` sources or any
|
||||
`std:` entry in Phase A.
|
||||
* Declaring the extraction, the external Conformance suite or the ecosystem
|
||||
switch done before their evidence exists.
|
||||
@@ -1,10 +1,6 @@
|
||||
# ADR-0071 — Engine / Host Contract / Native Host / CLI boundaries
|
||||
|
||||
Status: **Accepted** for the pre-stable 3.0 line (2026-11-26).
|
||||
The SDK portion of the repository decision was later implemented by
|
||||
[ADR-0072](0072-sdk-independent-repository.md) (independent public SDK
|
||||
repository pinned to this contract); the Engine/Native Host keep-in-workspace
|
||||
decision is unchanged.
|
||||
|
||||
Supersedes the historical review-RFC position that a Host contract crate is a
|
||||
second-step, optional move. It does not supersede the language contract
|
||||
@@ -95,10 +91,10 @@ maintainer, and an empty candidate repository would be a prohibited boundary
|
||||
violation. This ADR records **keep in workspace** as the legal conclusion and
|
||||
names the reopening conditions in `docs/architecture/CURRENT.md` §7.
|
||||
|
||||
The plugin SDK's physical move landed as [ADR-0072](0072-sdk-independent-repository.md):
|
||||
a standalone public repository consumes this contract at one pinned CLI `rev`.
|
||||
The Engine and Native Host stay here; no gitlink/submodule or empty
|
||||
`marqdo-cli-*` repository is created by this ADR.
|
||||
The plugin SDK's physical move is a follow-up: the contract is decoupled now,
|
||||
and the move requires a clean-directory build against a fixed contract revision
|
||||
(issue #13 S07/S08). No gitlink/submodule or empty `marqdo-cli-*` repository is
|
||||
created by this ADR.
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# ADR-0072 — Independent `marqdo-plugin-sdk` repository
|
||||
|
||||
Status: **Accepted** (2026-11-26).
|
||||
Status: **Superseded by [ADR-0073](0073-sdk-stays-in-cli-workspace.md)**
|
||||
(2026-11-26). The independent repository was deleted and the SDK returned to
|
||||
the CLI workspace; this document is kept as decision history only.
|
||||
|
||||
Complements [ADR-0071](0071-engine-host-contract-boundary.md) and implements the
|
||||
SDK follow-up tracked by issue [#15](https://git.cflmy.cn/cflmy/marqdo-cli/issues/15)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# ADR-0073 — Keep the plugin SDK in the CLI workspace; defer the repository split
|
||||
|
||||
Status: **Accepted** (2026-11-26).
|
||||
Supersedes [ADR-0072](0072-sdk-independent-repository.md).
|
||||
|
||||
## Context
|
||||
|
||||
ADR-0072 split `marqdo-plugin-sdk` into the public repository
|
||||
`cflmy/marqdo-plugin-sdk` and pinned it to one CLI contract `rev`. The
|
||||
implementation itself was technically sound (clean-clone build, frozen-CLI
|
||||
integration, no second ABI), but a re-evaluation against the pre-stable project's
|
||||
architecture showed that the **repository boundary was premature**, even though
|
||||
the **logical contract boundary is correct and stays**.
|
||||
|
||||
The relevant facts at this point in the prerelease line:
|
||||
|
||||
- the SDK is a small, contract-only consumer (six source files; dependencies are
|
||||
`marqdo-plugin-abi`, `serde`, `serde_json`);
|
||||
- plugin ABI 1.0, Value Wire 1 and the C header are frozen; the SDK has no
|
||||
independent version or release story beyond the ABI generation;
|
||||
- the C header, `spec/plugin-abi.md`, the `marqdo-plugin-abi` contract, the
|
||||
loader/worker and the SDK helpers evolve together and are owned by the same
|
||||
maintainers;
|
||||
- no registry publication or independent maintenance exists for the SDK;
|
||||
- the CLI product supports external plugin integration without the SDK (C ABI +
|
||||
loader are in the CLI), so the SDK is a developer kit, not a runtime feature.
|
||||
|
||||
Under issue #13's own criteria, "keep in workspace" is a legal conclusion when
|
||||
independent consumer/release evidence is absent. The split added a cross-repo
|
||||
`rev` pin, a second CI lane, a second source location and a documentation
|
||||
integrity burden (stale in-repo paths, weak entry links) without a current
|
||||
release or consumer benefit. The CLI's developer-facing contract, header, spec,
|
||||
SDK and examples should form one atomic change domain.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **The plugin SDK returns to the CLI workspace** as
|
||||
`crates/marqdo-plugin-sdk`, a contract-only crate. It keeps its current clean
|
||||
dependency graph: `marqdo-plugin-abi` + `serde`/`serde_json`; no loader,
|
||||
worker, host, sandbox or CLI dependency.
|
||||
2. **The independent repository is deleted.** Its source was restored from CLI
|
||||
Git history; no second copy of the SDK or contract remains. The SDK must not
|
||||
be reintroduced as a remote repository or as a submodule in this stage.
|
||||
3. **Logical boundaries stay exactly as ADR-0071 defined them**: the runtime
|
||||
depends only on `marqdo-host-contract`; `marqdo-plugin-abi` is a pure
|
||||
contract; execution-side loader/worker/manifest/artifact live in
|
||||
`marqdo-host::plugin`; the CLI is the single assembly point.
|
||||
4. **Atomicity is the priority for the pre-stable line.** ABI layout, header,
|
||||
spec, contract crate, SDK helpers, fixture and the real CLI invocation test
|
||||
land in one commit/PR/lock. There is no cross-repository pin to bump and no
|
||||
second current source tree.
|
||||
5. **External access remains in the CLI product.** The release archive and
|
||||
repository carry the C header, public plugin spec, loader/worker and the SDK
|
||||
source; plugin authors build their plugin against this repository (or use
|
||||
the header from another language). The CLI itself is not compiled by plugin
|
||||
users.
|
||||
6. **Future extraction is a new decision, not an implicit step.** It requires
|
||||
new evidence: independent SDK release (for example a published contract
|
||||
artifact), a real non-CLI consumer/maintainer, or a distribution need that
|
||||
the atomic workspace cannot serve. It then needs a new Accepted ADR and must
|
||||
not create a CLI↔SDK gitlink cycle.
|
||||
|
||||
## Verification
|
||||
|
||||
- SDK crate, fixture, CLI-side SDK gate and workspace/lock are restored; the
|
||||
CLI builds and tests them in the same workspace.
|
||||
- `tools/ci/check_dependency_boundaries.py` enforces the SDK's contract-only
|
||||
normal/build dependencies and its presence in the workspace as a reviewed
|
||||
crate.
|
||||
- `tools/ci/check_plugin_sdk.py` builds the SDK fixture with only the public SDK
|
||||
and loads it through the real CLI with explicit trust/grant; a tampered
|
||||
artifact digest is rejected.
|
||||
- The remote split repository was deleted after this decision; no temporary
|
||||
branch was created for the revert.
|
||||
- Full evidence: `docs/evidence/2026-11-26-issue-15-sdk-split-reverted.md`.
|
||||
|
||||
## Rejected alternatives
|
||||
|
||||
- **Keep the split because it was already implemented.** Sunk-cost reasoning;
|
||||
it does not satisfy the "necessary split" criterion for this stage.
|
||||
- **Keep the remote repository as a mirror/copy.** Two current SDK sources and
|
||||
a second contract consumer tree are explicitly forbidden; Git history already
|
||||
preserves ADR-0072's implementation.
|
||||
- **Make the SDK a submodule of the CLI.** Inverts the dependency direction and
|
||||
risks the CLI gitlink ↔ SDK → CLI contract cycle; the CLI does not consume
|
||||
the SDK at build time.
|
||||
- **Turn the SDK into a prebuilt binary so users need not compile.** Native
|
||||
plugins are compiled by their authors by definition; the SDK is a source-level
|
||||
helper. A prebuilt SDK is neither a plugin nor a compiler target.
|
||||
|
||||
## Consequences
|
||||
|
||||
- One atomic language/plugin-development change domain; one lock and one
|
||||
candidate SHA for ABI/header/spec/SDK/loader changes.
|
||||
- External plugin integration keeps working through the CLI's contract and
|
||||
loader; the SDK is discoverable in the same public repository as the header
|
||||
and spec.
|
||||
- The split work remains in Git history (ADR-0072, former PR #16) as decision
|
||||
history; it is not current architecture.
|
||||
+7
-2
@@ -70,9 +70,14 @@ Files: `0001`–`0050`, plus:
|
||||
pre-stable public boundary, replaced in place;
|
||||
* [0069](0069-public-analysis-boundary.md) — one public Analysis projection for
|
||||
independent document, lint and knowledge consumers.
|
||||
* [0070](0070-explicit-stdlib-bundle-build-input.md) — Phase A of the stdlib
|
||||
extraction: one required `--stdlib-dir` build input, one pinned Bundle
|
||||
identity for tests/perf/release CI; runtime contracts unchanged.
|
||||
* [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`.
|
||||
* [0072](0072-sdk-independent-repository.md) — **superseded**: the independent
|
||||
public SDK repository was deleted and the SDK returned to the CLI workspace.
|
||||
* [0073](0073-sdk-stays-in-cli-workspace.md) — keep the plugin SDK in the CLI
|
||||
workspace for the pre-stable atomic line; repository split deferred.
|
||||
@@ -19,7 +19,8 @@ resources, OS adapters and trusted extension execution; `crates/cli` remains the
|
||||
single product assembly. The plugin ABI crate is a public contract only: native
|
||||
loading, artifact/manifest execution and worker processes live in
|
||||
`marqdo-host::plugin`. The SDK depends on the contract, not on a loader or a
|
||||
host.
|
||||
host, and stays in this workspace as a contract-only developer crate
|
||||
([ADR-0073](../adr/0073-sdk-stays-in-cli-workspace.md)).
|
||||
|
||||
The Engine and the Native Host stay in **this workspace**. Issue #13 §9.2
|
||||
admission for a separate repository is not met yet: there is no real external
|
||||
@@ -48,6 +49,7 @@ in the same change.
|
||||
| `marqdo-sandbox` | Native Host support | OS isolation probe and strict launch |
|
||||
| `marqdo-foreign` | Native Host support | Controlled one-shot foreign kernels (F-A) |
|
||||
| `marqdo-plugin-abi` | Public contract | C ABI v1 layout, wire envelope and protocol errors |
|
||||
| `marqdo-plugin-sdk` | Public contract consumer | Third-party plugin development helpers |
|
||||
| `marqdo-worker-ipc` | Shared plumbing | One bounded worker frame transport |
|
||||
| `marqdo-provider-worker` | Shipped worker | Provider helper process |
|
||||
| `marqdo-package` | Product support | Project manifest, lock and dependency resolution |
|
||||
@@ -184,8 +186,11 @@ Layer rules:
|
||||
or a third-party plugin path.
|
||||
2. The platform layer owns I/O, clocks, entropy, sockets and file handles. It must
|
||||
not own JSON parsing, text formatting or memory allocation policy.
|
||||
3. The stdlib is `.mq.md` and ships in this repository. New ordinary algorithms
|
||||
go to `stdlib/` + tests + docs; they do not become Rust builtins.
|
||||
3. The stdlib is `.mq.md` and ships in this repository during Phase A of
|
||||
issue #11. New ordinary algorithms go to `stdlib/` + tests + docs; they do
|
||||
not become Rust builtins. Packaging and product tests take it as one
|
||||
explicit, pinned Bundle input (ADR-0070); Phase B moves the production
|
||||
sources to the ecosystem assembly after issue #2 acceptance.
|
||||
4. The CLI selects inputs, resolves configuration, assembles the host and routes
|
||||
human/machine output. It is not a semantic policy centre.
|
||||
5. Callable Plugin and Resource Provider share one registry/authorization/audit
|
||||
@@ -207,7 +212,7 @@ marqdo-host-contract -> marqdo-value, marqdo-span
|
||||
marqdo-host -> marqdo-host-contract, marqdo-plugin-abi, marqdo-foreign,
|
||||
marqdo-sandbox, marqdo-worker-ipc
|
||||
marqdo-plugin-abi -> marqdo-value, serde/serde_json (contract only)
|
||||
[cflmy/marqdo-plugin-sdk] -> cflmy/marqdo-cli#marqdo-plugin-abi @ pinned rev
|
||||
marqdo-plugin-sdk -> marqdo-plugin-abi (contract only)
|
||||
marqdo-provider-worker -> marqdo-worker-ipc
|
||||
```
|
||||
|
||||
@@ -279,7 +284,7 @@ that a phase is complete.
|
||||
| Priority | Gap | State |
|
||||
|---|---|---|
|
||||
| P0 | **Language syntax migration**: RFC-LANG-0002 single contract | **closed at `9c1723d`**; implementation, stdlib digest, examples and fixtures green; platform/strict evidence remains separate |
|
||||
| P0 | Stdlib release is a bundle in this repo; extraction is deferred (ADR-0039) | accepted, keep in repo |
|
||||
| P0 | Stdlib extraction (issue #11): explicit `--stdlib-dir` + one pinned Bundle for tests/perf/release CI | **Phase A implemented** (ADR-0070); Phase B (ecosystem assembly, source removal) waits on ecosystem issue #2 and the extension replacement evidence |
|
||||
| P0 | Documentation drift between `STATUS.md`, the architecture index and the evidence | being fixed by this migration and the docs gate |
|
||||
| P1 | Domain service ownership ledger (issue #13 §7): host-held `regex.*` and `compress.*` are ADR-0062 services, not a precedent for new domain operations | **DEFERRED** to the responsible `marqdo-ext-regex`/`marqdo-ext-archive` replacement issues; old entries stay until a real replacement passes authorization/negative tests |
|
||||
| P1 | `std:fs/file` read/write/copy, metadata/directory, append/read_at/walk are implemented; watch and binary offset reads remain open | open |
|
||||
@@ -325,15 +330,17 @@ that a phase is complete.
|
||||
|---|---|---|
|
||||
| Engine (`span`/`value`/`expression`/`markdown`/`ir`/`frontend`/`runtime`/`host-contract`) | **Keep in this workspace** as one atomic semantic-change domain | A real, non-in-repo consumer needs independent build/release, and the semantic change cost is acceptable |
|
||||
| Native Host (`host`/`sandbox`/`foreign`/plugin loader) | **Keep in this workspace**, dependent on the neutral contract | An independent platform maintainer or second product consumes it; security/conformance can be verified separately |
|
||||
| `marqdo-plugin-sdk` | **Moved to independent public repository** `cflmy/marqdo-plugin-sdk` ([ADR-0072](../adr/0072-sdk-independent-repository.md)) | Contract input is a pinned CLI git `rev`; clean-clone build + frozen-CLI integration are the SDK repository's gates. CLI must not depend on it or re-add a copy |
|
||||
| `marqdo-plugin-sdk` | **Keep in this workspace** as a contract-only developer crate. The ADR-0072 independent repository was deleted and the source restored ([ADR-0073](../adr/0073-sdk-stays-in-cli-workspace.md)); atomic ABI/header/spec/SDK changes are the priority for the pre-stable line | Independent SDK release/registry publication, a real non-CLI consumer or maintainer, and a new Accepted ADR. No submodule/gitlink |
|
||||
| Stdlib | Separate issue #11/#12 (Phase A build input); runtime contract unchanged | Ecosystem-assembled Bundle and extension replacement accepted; then retire the in-repo source authority |
|
||||
| Regex/compression domain services | **DEFERRED** under ADR-0062 ownership; no new domain operation may be added | A separately installable extension replaces the host-held service and the old entries are removed atomically |
|
||||
| Foreign F-A | Retained; no F-B, session or new transport in this change | Separate ADR and milestone |
|
||||
|
||||
No candidate empty `marqdo-engine`, `marqdo-host` or `marqdo-cli-*` repository
|
||||
is created by this decision. Git repository boundaries are ownership and release
|
||||
boundaries, not a mechanical projection of Cargo crates. The engine and native
|
||||
host are one source tree until the reopening evidence above exists.
|
||||
is created by this decision. The former independent SDK repository was deleted
|
||||
under ADR-0073; the SDK is back in this workspace and no remote copy is kept.
|
||||
Git repository boundaries are ownership and release boundaries, not a mechanical
|
||||
projection of Cargo crates. The engine, native host and plugin developer kit are
|
||||
one source tree until the reopening evidence above exists.
|
||||
|
||||
## 8. References
|
||||
|
||||
@@ -357,9 +364,10 @@ host are one source tree until the reopening evidence above exists.
|
||||
- [Compute-machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) and [core/stdlib RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) — design input.
|
||||
- [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) — historical review input; the current boundary decision is ADR-0071.
|
||||
- [ADR-0071: Engine / Host Contract / Native Host boundaries](../adr/0071-engine-host-contract-boundary.md) — accepted responsibility split and keep-in-workspace decision for issue #13.
|
||||
- [ADR-0072: Independent `marqdo-plugin-sdk` repository](../adr/0072-sdk-independent-repository.md) — the one deliberate repository split (public SDK leaf pinned to the CLI contract).
|
||||
- [Issue #15 SDK split evidence](../evidence/2026-11-26-issue-15-sdk-independent-repository.md) — clean-clone build and frozen-CLI integration.
|
||||
- [ADR-0073: Keep the plugin SDK in the CLI workspace](../adr/0073-sdk-stays-in-cli-workspace.md) — current decision: SDK atomicity, no split, no remote copy; supersedes ADR-0072.
|
||||
- [ADR-0072: Independent SDK repository](../adr/0072-sdk-independent-repository.md) — **superseded** decision history; the repository was deleted.
|
||||
- [Issue #13 engine/host evidence](../evidence/2026-11-26-issue-13-engine-host-boundary.md) — executed candidate commands and results.
|
||||
- [Issue #15 SDK split-revert evidence](../evidence/2026-11-26-issue-15-sdk-split-reverted.md) — repository deletion, source restoration and gates.
|
||||
- [RFC-EXT-0001](RFC-EXT-0001.md) — extensibility closure task specification (implementation status tracked here and in STATUS).
|
||||
- [ADR-0054: single callable binding](../adr/0054-callable-binding-single-source.md) — one registry/binding pass, runtime dispatch by identity.
|
||||
- [ADR-0055: resource provider CLI v2](../adr/0055-resource-provider-cli-v2.md) — provider v2 manifest/worker CLI closure and trust boundary.
|
||||
|
||||
@@ -83,8 +83,9 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and
|
||||
| Resource operations and core kinds | [0062](../adr/0062-resource-operation-ownership-and-core-kinds.md) | Accepted and implemented; architecture gate pins the reviewed lists |
|
||||
| Foreign F-A transition | [0063](../adr/0063-foreign-kernel-transition-fa.md) | Accepted: retained F-A primitive; F-B deferred |
|
||||
| Stable core inventory and external gate | [0064](../adr/0064-stable-core-extension-boundary.md) | Accepted and wired into Linux CI |
|
||||
| Engine / Host Contract / Native Host / CLI boundaries | [0071](../adr/0071-engine-host-contract-boundary.md) | Accepted and implemented by issue #13: runtime depends on the neutral contract, native host implements it, plugin ABI is contract-only, Engine/Native Host keep-in-workspace decision |
|
||||
| Independent plugin SDK repository | [0072](../adr/0072-sdk-independent-repository.md) | Accepted and implemented: public `cflmy/marqdo-plugin-sdk`, pinned to CLI contract commit, CLI does not depend on it |
|
||||
| Independent plugin SDK repository | [0072](../adr/0072-sdk-independent-repository.md) | **Superseded by ADR-0073**: repository deleted, SDK restored to the CLI workspace |
|
||||
| Plugin SDK stays in the CLI workspace | [0073](../adr/0073-sdk-stays-in-cli-workspace.md) | Accepted: atomic pre-stable changes, no split, no remote copy |
|
||||
| Engine / Host Contract / Native Host / CLI boundaries | [0071](../adr/0071-engine-host-contract-boundary.md) | Accepted and implemented by issue #13: runtime depends on the neutral contract, native host implements it, plugin ABI is contract-only, keep-in-workspace repository decision |
|
||||
| Manifest-driven Resource Control | [0065](../adr/0065-resource-control-vnext.md) | Proposed |
|
||||
| Structured Tasks and Channels | [0066](../adr/0066-structured-tasks-v1.md) | Proposed |
|
||||
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
|
||||
|
||||
+19
-3
@@ -14,8 +14,10 @@
|
||||
The default Docker pipeline runs on push and pull request. A fast `contract`
|
||||
lane exercises the public Analysis/Observation contracts through the real CLI
|
||||
and the independent Python consumers; the full `test` lane runs the Rust gates
|
||||
and the Windows cross-target compile check; `build` packages the archive, runs
|
||||
the from-archive smoke and the frozen external conformance suite.
|
||||
and the Windows cross-target compile check; `independent-build` exports the
|
||||
commit without `stdlib/` and proves both shipped binaries still build and run a
|
||||
language-only program; `build` packages the archive from the pinned stdlib
|
||||
Bundle, runs the from-archive smoke and the frozen external conformance suite.
|
||||
|
||||
```text
|
||||
contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries):
|
||||
@@ -27,23 +29,32 @@ contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries):
|
||||
dependency-direction gate (tools/ci/check_dependency_boundaries.py)
|
||||
|
||||
test (rust:1.100-bookworm, clippy/rustfmt, Node.js 22, MinGW, both binaries):
|
||||
python3 tools/stdlib/bundle.py (verify the pinned Bundle)
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo build --locked -p marqdo-provider-worker
|
||||
cargo test --workspace --locked
|
||||
docs_consistency / architecture_boundaries / stdlib_product
|
||||
stdlib_product again with MARQDO_TEST_STDLIB_BUNDLE + MARQDO_TEST_BUNDLE_PIN
|
||||
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
|
||||
|
||||
independent-build (rust:1.100-bookworm, git, python3):
|
||||
git archive HEAD, remove stdlib/, no ecosystem checkout
|
||||
cargo build --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
language-only check/call through the built CLI
|
||||
stdlib-dependent run must fail closed; no stdlib/ next to the binary
|
||||
|
||||
minimum-rust (rust:1.89-bookworm):
|
||||
cargo check --locked --workspace --all-targets
|
||||
|
||||
build (depends on test, minimum-rust, contract):
|
||||
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
package the deterministic archive for $CI_COMMIT_SHA
|
||||
python3 tools/stdlib/bundle.py; package --stdlib-dir stdlib --bundle-pin ...
|
||||
from-archive smoke (tools/release/smoke.py)
|
||||
frozen external conformance (tools/ci/run_frozen_extensions.sh, 7/7)
|
||||
```
|
||||
@@ -96,6 +107,11 @@ syntax; Debian bookworm's Node 18 fails those tests.
|
||||
workspace tests so the provider CLI tests use the real helper, and adds a
|
||||
`cargo check --workspace --all-targets --target x86_64-pc-windows-gnu`
|
||||
compile gate (native Windows/macOS runtime lanes stay on the GitHub matrix).
|
||||
* **ADR-0070 explicit Bundle:** the `test` lane verifies
|
||||
`tools/stdlib/bundle-pin.json` and runs the product suite once with an
|
||||
explicit `MARQDO_TEST_STDLIB_BUNDLE`; the new `independent-build` lane builds
|
||||
both binaries from a copy without `stdlib/` and requires the stdlib-dependent
|
||||
program to fail closed.
|
||||
* The Woodpecker **build** lane and the GitHub **release-candidate** lane build
|
||||
`marqdo` **and** `marqdo-provider-worker` and package both as siblings; the
|
||||
provider transport resolves only that sibling (no PATH fallback), so an
|
||||
|
||||
@@ -18,7 +18,7 @@ Foreign wire v1, Provider manifest v2, lock v4 and markdown profile
|
||||
|---|---|---|
|
||||
| AI/math/data/quantum/SKILL libraries, pure algorithms | `.mq.md` package | `index.mq.md`, `marqdo.yaml`, README, tests |
|
||||
| Knowledge/Proof/View/IDE/lint/analysis tools | CLI Tool protocol | standalone executable + `tool.json` + Analysis/Observation consumer |
|
||||
| High-performance native callable functions | Callable Plugin ABI v1 | `plugin.yaml`, host-targeted library, public SDK (`cflmy/marqdo-plugin-sdk`) + header |
|
||||
| High-performance native callable functions | Callable Plugin ABI v1 | `plugin.yaml`, host-targeted library, SDK/header |
|
||||
| New foreign language backend (R/Python/Julia/…) | Foreign Kernel | `kernel.json`, executable provider, pinned environment |
|
||||
| Hardware/device/external-stream resources | Resource Provider v2 | `provider.json`, C ABI library, worker helper |
|
||||
| Change `@exec` semantics, add keywords/types | **not** a third-party extension | core language RFC + migration + full conformance |
|
||||
@@ -61,7 +61,7 @@ only on `marqdo-host-contract`; the native host implements it; the plugin ABI
|
||||
crate is a contract (no loader/worker); the CLI is the only assembly point.
|
||||
Run `python3 tools/ci/check_dependency_boundaries.py`,
|
||||
`python3 tools/ci/check_engine_boundary.py` and
|
||||
the independent SDK repository's frozen-CLI check with the Rust suits. Do not create an
|
||||
`python3 tools/ci/check_plugin_sdk.py` with the Rust suits. Do not create an
|
||||
empty candidate repository for a boundary; a split needs the evidence and a new
|
||||
ADR.
|
||||
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
# Issue #11 Phase A — one explicit stdlib Bundle input
|
||||
|
||||
Date: 2026-11-26.
|
||||
Implementation baseline: `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`.
|
||||
Bundle source commit: `2cbde54602c07f62a62f341400bc9cb4764a93f8`.
|
||||
Decision: [ADR-0070](../adr/0070-explicit-stdlib-bundle-build-input.md).
|
||||
Inventory:
|
||||
[`2026-11-26-stdlib-source-coupling-inventory.md`](2026-11-26-stdlib-source-coupling-inventory.md).
|
||||
|
||||
Candidate commits (in order):
|
||||
|
||||
| Commit | Change |
|
||||
|---|---|
|
||||
| `b9c72e1` | ADR-0070 + source-coupling inventory |
|
||||
| `1b9d9c4` | `tools/stdlib/bundle.py`, `bundle-pin.json`, required `pack-stdlib.py --stdlib-dir` |
|
||||
| `422b9de` | `package.py --stdlib-dir/--bundle-pin`, `RELEASE_INFO.stdlib.source` |
|
||||
| `3a68260` | pinned test resolver, synthetic loader tests, product/conformance rewiring |
|
||||
| `ab6b6b1` | independent-build lane, perf Bundle pin, CI and docs |
|
||||
| `0e1efc7` | archive smoke/cold-install keep the language-only run after removing the Bundle |
|
||||
|
||||
The documentation commit that adds this record also updates `STATUS.md`, the
|
||||
architecture overview, `README.md` and `tests/README.md`. CI follow-up commit
|
||||
`2acaaef` folds the `independent-build` job into the existing `linux` evidence
|
||||
gate (the release-evidence schema accepts only its declared gate names).
|
||||
|
||||
Executed host: Linux x86_64 (glibc 2.43), `rustc 1.100.0 (0ef1bc386
|
||||
2026-11-09)`, `cargo 1.100.0 (3acc79c0c 2026-11-05)`, Python 3.14.4; the
|
||||
cold-install container is `ubuntu:24.04` (glibc 2.39) with `--network none`.
|
||||
|
||||
## 1. Pinned Bundle identity
|
||||
|
||||
```console
|
||||
$ python3 tools/stdlib/bundle.py
|
||||
{
|
||||
"aliases_digest": "sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb",
|
||||
"file_count": 42,
|
||||
"name": "marqdo-stdlib",
|
||||
"root": "<checkout>/stdlib",
|
||||
"source_commit": "2cbde54602c07f62a62f341400bc9cb4764a93f8",
|
||||
"tree_digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
```
|
||||
|
||||
`tools/stdlib/bundle-pin.json` records the same identity. The resolver accepts
|
||||
an explicit location but never an explicit identity: a valid-but-unpinned
|
||||
Bundle is rejected.
|
||||
|
||||
## 2. Failure paths (tools/ci/test_stdlib_bundle_tools.py)
|
||||
|
||||
64 `tools/ci` unit tests pass. The new cases cover:
|
||||
|
||||
* `--stdlib-dir` is required and a missing input fails before any output;
|
||||
* a missing `stdlib.json`, a tree-digest mismatch, an alias-digest mismatch and
|
||||
`public_aliases` without `aliases_digest` fail;
|
||||
* a symlink inside the Bundle is rejected;
|
||||
* an explicit Bundle that does not match the pin fails, even when the pinned
|
||||
default is valid;
|
||||
* a bad pin schema fails;
|
||||
* the `bundle.py` CLI exits 1 on an invalid explicit input and 0 with
|
||||
`--print-path` otherwise.
|
||||
|
||||
The runtime override rule is pinned by the loader unit test
|
||||
`bad_override_fails_closed_even_with_a_valid_sibling` (a bad
|
||||
`MARQDO_STDLIB_DIR` fails although a valid sibling `stdlib/` exists).
|
||||
|
||||
## 3. Deterministic packaging
|
||||
|
||||
Two standalone stdlib packs from the same explicit input and toolchain are
|
||||
byte-identical:
|
||||
|
||||
```console
|
||||
$ python3 tools/pack-stdlib.py --stdlib-dir stdlib \
|
||||
--bundle-pin tools/stdlib/bundle-pin.json --out-dir <a>
|
||||
$ python3 tools/pack-stdlib.py --stdlib-dir stdlib \
|
||||
--bundle-pin tools/stdlib/bundle-pin.json --out-dir <b>
|
||||
$ sha256sum <a>/marqdo-stdlib-0.1.0.tar.gz <b>/marqdo-stdlib-0.1.0.tar.gz
|
||||
f6dc8e7ad92bc58b815635aea923069919d6f5495078e53828ae4723d925a565 <a>/marqdo-stdlib-0.1.0.tar.gz
|
||||
f6dc8e7ad92bc58b815635aea923069919d6f5495078e53828ae4723d925a565 <b>/marqdo-stdlib-0.1.0.tar.gz
|
||||
```
|
||||
|
||||
Two release archives built from `ab6b6b1` with `--skip-example-build` (the
|
||||
host-built example artifacts were already present) are byte-identical:
|
||||
`f37e01c44e668a6daf0538b32e9825cc74392f0ccbd65362af2783629b6d2c48`.
|
||||
`RELEASE_INFO.json.stdlib.source` records
|
||||
`{"kind":"in-repo","repository":"cflmy/marqdo-cli","commit":"2cbde54602c07f62a62f341400bc9cb4764a93f8","path":"stdlib"}`
|
||||
and the tree/alias digests equal `stdlib.json`.
|
||||
|
||||
## 4. Product and performance lanes
|
||||
|
||||
The product, HTTP, table, alias-routing, P2 closure and semantic harnesses
|
||||
resolve the pinned Bundle through `crates/cli/tests/support/stdlib.rs`
|
||||
(`MARQDO_TEST_STDLIB_BUNDLE`/`MARQDO_TEST_BUNDLE_PIN` overrides are verified
|
||||
against the pin). Loader unit tests build synthetic Bundles instead of the
|
||||
product tree.
|
||||
|
||||
```console
|
||||
$ cargo test -p marqdo-cli --bin marqdo stdlib --offline
|
||||
4 passed (synthetic loader tests)
|
||||
$ cargo test -p marqdo-cli --test stdlib_product --offline
|
||||
16 passed
|
||||
$ cargo test -p marqdo-cli --test stdlib_bundle --test stdlib_http \
|
||||
--test stdlib_table --test stdlib_alias_routing --offline
|
||||
13 passed
|
||||
$ cargo test -p marqdo-cli --test architecture_boundaries \
|
||||
--test conformance_semantics --test p2_closure --offline
|
||||
16 passed
|
||||
$ python3 tools/perf/runner.py --no-build --binary target/debug/marqdo \
|
||||
--warmups 1 --samples 3 --allow-smoke --only hello-check ...
|
||||
correctness=VERIFIED status=SMOKE
|
||||
stdlib={... "source_commit":"2cbde54602c07f62a62f341400bc9cb4764a93f8" ...}
|
||||
```
|
||||
|
||||
## 5. Independent build (clean copy without stdlib)
|
||||
|
||||
`tools/ci/independent_build.py` exported `ab6b6b1` with `git archive`, removed
|
||||
`stdlib/`, and built both binaries with `--locked`:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "PASS",
|
||||
"source_sha": "ab6b6b1a23ec064fbc7de943c52befca18142a56",
|
||||
"binaries": {
|
||||
"marqdo": {"sha256": "428c25c60caa7762348bcffad96558591adf52440d44549a645390c927558757"},
|
||||
"marqdo-provider-worker": {"sha256": "3787942de6d35ce1c7f03c0848c8e08b6037495e98005c62704d34e664da795c"}
|
||||
},
|
||||
"checks": {
|
||||
"stdlib_source_removed": true,
|
||||
"language_only_check": "PASS",
|
||||
"language_only_call": "PASS:3",
|
||||
"stdlib_dependent_missing_bundle": "PASS",
|
||||
"no_sibling_stdlib": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The stdlib-dependent `run examples/hello.mq.md` failed with an explicit
|
||||
stdlib/print diagnostic instead of falling back to a source tree; the built
|
||||
`target/debug` directory contains no `stdlib/`.
|
||||
|
||||
## 6. Archive smoke and cold install
|
||||
|
||||
```console
|
||||
$ python3 tools/release/smoke.py --archive <archive>
|
||||
smoke: verified stdlib 0.1.0 tree=sha256:5407d36... aliases=sha256:5f513c0... files=42
|
||||
smoke: archive version 3.0.0-rc.4, source ab6b6b1a23ec064fbc7de943c52befca18142a56
|
||||
smoke: bundled stdlib missing -> fail-closed OK
|
||||
smoke: language-only program runs without the bundled stdlib
|
||||
smoke: PASS
|
||||
```
|
||||
|
||||
```console
|
||||
$ bash tools/release/cold-install.sh <archive> ab6b6b1a23ec064fbc7de943c52befca18142a56
|
||||
你好,Marqdo
|
||||
checked 2 module(s): ok
|
||||
checked 1 module(s): ok
|
||||
6
|
||||
runtime error[kernel.unavailable]: 打印 requires the bundled stdlib print module; install the official CLI bundle
|
||||
<language-only factorial call still prints 120>
|
||||
```
|
||||
|
||||
The container is `ubuntu:24.04`, `--network none`, user `65534:65534`, with no
|
||||
Cargo and no source checkout; only the archive bytes are mounted. Moving the
|
||||
shipped `stdlib/` aside keeps the language-only factorial call working and
|
||||
makes the `打印` program fail with the explicit `kernel.unavailable` message.
|
||||
|
||||
## 7. Gates on the candidate tree
|
||||
|
||||
```console
|
||||
$ cargo fmt --all -- --check
|
||||
FMT_OK
|
||||
$ cargo clippy --workspace --all-targets --offline -- -D warnings
|
||||
exit=0
|
||||
$ cargo test --workspace --locked --offline
|
||||
exit=0
|
||||
634 passed, 0 failed, 2 ignored across 72 test binaries
|
||||
```
|
||||
|
||||
The workspace run includes `docs_consistency` (7 passed),
|
||||
`architecture_boundaries`, the frozen conformance suites and every product
|
||||
lane. It was executed on the candidate tree plus this documentation change and
|
||||
is reproducible with `cargo test --workspace --locked`. Platform-native
|
||||
Windows/macOS runs were not re-executed for this docs-only candidate; the
|
||||
existing GitHub matrix remains the lane for them.
|
||||
|
||||
## 8. Not claimed
|
||||
|
||||
* Phase B: switching to the ecosystem-assembled Bundle, removing the in-repo
|
||||
production sources, removing the debug source fallback and deleting replaced
|
||||
`std:` entries. It is gated on ecosystem issue #2 and the extension
|
||||
replacement evidence named by issue #11.
|
||||
* Any `std:`/`stdlib.json`/`marqdo.stdlib-package`/Analysis/Observation shape
|
||||
change; none was made.
|
||||
* A docker cold-install on a Windows/macOS host or a native Windows/macOS
|
||||
product run for this candidate.
|
||||
@@ -42,7 +42,7 @@ to a different commit.
|
||||
| Dependency gate | `python3 tools/ci/check_dependency_boundaries.py` | PASS |
|
||||
| Dependency gate negative cases | `python3 -m unittest tools.ci.test_dependency_boundaries` / `python3 -m unittest discover -s tools/ci` | PASS (54 tool tests) |
|
||||
| Engine independence and differential execution | `python3 tools/ci/check_engine_boundary.py` | PASS |
|
||||
| Plugin SDK real consumption | `python3 tools/ci/check_plugin_sdk.py` | PASS at that candidate; the SDK and this gate moved to the independent repository under issue #15 / ADR-0072 (evidence: `2026-11-26-issue-15-sdk-independent-repository.md`) |
|
||||
| Plugin SDK real consumption | `python3 tools/ci/check_plugin_sdk.py` | PASS |
|
||||
| Existing product/conformance suites | included in workspace run; stdlib product suite additionally run | PASS |
|
||||
|
||||
Behavioral facts from the engine gate:
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# Evidence — issue #15 independent `marqdo-plugin-sdk` repository
|
||||
|
||||
> **Superseded.** This snapshot records the (later reverted) ADR-0072 split.
|
||||
> The SDK is back in the CLI workspace under
|
||||
> [ADR-0073](../adr/0073-sdk-stays-in-cli-workspace.md); the remote repository
|
||||
> was deleted. See `2026-11-26-issue-15-sdk-split-reverted.md`. Do not read this
|
||||
> file as current architecture.
|
||||
|
||||
Date: 2026-11-26 (Asia/Shanghai)
|
||||
Tracking issue: <https://git.cflmy.cn/cflmy/marqdo-cli/issues/15>
|
||||
Decision: [ADR-0072](../adr/0072-sdk-independent-repository.md)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Evidence — issue #15 plugin SDK split reverted to the CLI workspace
|
||||
|
||||
Date: 2026-11-26 (Asia/Shanghai)
|
||||
Tracking issue: <https://git.cflmy.cn/cflmy/marqdo-cli/issues/15>
|
||||
Decision: [ADR-0073](../adr/0073-sdk-stays-in-cli-workspace.md) (supersedes
|
||||
[ADR-0072](../adr/0072-sdk-independent-repository.md))
|
||||
Parent: issue #13 / [ADR-0071](../adr/0071-engine-host-contract-boundary.md)
|
||||
|
||||
## Decision
|
||||
|
||||
Parent CLI contract merge: `2585915e16906dac75f8571bed02e7f6f868c6bc`.
|
||||
Deleted split repository commits: `b31187a` / `c3134e4` (kept in Git history
|
||||
of the former repository only; no source copy remains).
|
||||
|
||||
The plugin SDK stays in the CLI workspace as a contract-only crate. The public
|
||||
repository `cflmy/marqdo-plugin-sdk` created by ADR-0072 was deleted; its source
|
||||
was restored from CLI Git history. The pre-stable line prioritizes atomic
|
||||
ABI/header/spec/SDK/loader changes in one workspace, lock and candidate SHA.
|
||||
The logical ADR-0071 boundaries are unchanged.
|
||||
|
||||
## Actions executed
|
||||
|
||||
| Step | Result |
|
||||
|---|---|
|
||||
| Restore `crates/marqdo-plugin-sdk` from CLI history | Restored contract-only crate (`marqdo-plugin-abi` + serde/serde_json); no loader/host/worker dependency |
|
||||
| Restore workspace member and lock | `cargo check --workspace --all-targets --locked` resolves the SDK in the workspace; `Cargo.lock` contains it again |
|
||||
| Restore `tests/sdk-plugin` and `tools/ci/check_plugin_sdk.py` | Real fixture/gate back in the CLI; builds only against the public SDK and invokes via the real CLI |
|
||||
| Restore architecture/dependency/docs references | `architecture_boundaries.rs`, `check_dependency_boundaries.py`, `docs_consistency` paths, README/AGENTS/spec/developer guides point at the in-repo crate again |
|
||||
| Delete remote `cflmy/marqdo-plugin-sdk` | Authorized by the maintainer; the repository and its branches are gone, no mirror remains |
|
||||
| No temporary branch | The revert is committed directly on `master` and pushed; old merged feature branches are deleted separately |
|
||||
| Record superseded history | ADR-0072 and the old issue-#15 evidence carry Superseded banners; ADR-0073 is the current decision |
|
||||
|
||||
## Verification (local, Linux x86_64, Rust 1.100)
|
||||
|
||||
| Gate | Command | Result |
|
||||
|---|---|---|
|
||||
| Formatting | `cargo fmt --all -- --check` | PASS |
|
||||
| Clippy | `cargo clippy --workspace --all-targets --locked -- -D warnings` | PASS |
|
||||
| Rust tests | `cargo test --workspace --locked --offline --no-fail-fast` | PASS — **636 passed / 0 failed / 2 ignored** (same as the pre-split workspace) |
|
||||
| Architecture boundaries | `cargo test -p marqdo-cli --test architecture_boundaries --locked` | PASS |
|
||||
| Docs consistency | `cargo test -p marqdo-cli --test docs_consistency --locked` | PASS |
|
||||
| Dependency direction | `python3 tools/ci/check_dependency_boundaries.py` | PASS — SDK back in the reviewed workspace allowlist with contract-only edges |
|
||||
| SDK real consumption | `python3 tools/ci/check_plugin_sdk.py` | PASS — builds fixture with only the SDK; real CLI returns `Int 42`; tampered digest rejected |
|
||||
| Engine differential | `python3 tools/ci/check_engine_boundary.py` | PASS |
|
||||
| Tools unit tests | `python3 -m unittest discover -s tools/ci -p "test_*.py"` | PASS |
|
||||
|
||||
Remote CI on the code commit `98d256f`: Woodpecker push pipeline **#112**
|
||||
success (contract/test/minimum-rust/build) and Gitea commit status `success`.
|
||||
This evidence-only follow-up does not change code, lock or protocol bytes. No
|
||||
split repository, mirror or submodule exists after the deletion.
|
||||
|
||||
## Current architecture facts
|
||||
|
||||
- `marqdo-plugin-abi` is still the pure public contract; loader/worker/manifest/
|
||||
artifact remain in `marqdo-host::plugin` (ADR-0071).
|
||||
- `marqdo-plugin-sdk` is a CLI workspace member with normal/build dependencies
|
||||
only on the contract + serde; the CLI product is the only assembly point.
|
||||
- Plugin authors get header, spec, SDK, examples and loader from one public CLI
|
||||
repository/release; they compile their plugin, not the CLI.
|
||||
- The CLI runtime does not depend on the SDK; external plugin loading remains
|
||||
available (C ABI header + `--plugin`/`--trust-native-plugin`/`--allow-plugin`
|
||||
+ worker transport).
|
||||
@@ -0,0 +1,72 @@
|
||||
# Stdlib source-directory coupling inventory (issue #11, Phase A)
|
||||
|
||||
Date: 2026-11-26.
|
||||
Implementation baseline: `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` (current
|
||||
`master`). Bundle source commit: `2cbde54602c07f62a62f341400bc9cb4764a93f8`
|
||||
(the last commit that touched `stdlib/` at the baseline). Pinned Bundle:
|
||||
`marqdo-stdlib` `0.1.0`, tree digest
|
||||
`sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713`,
|
||||
alias digest
|
||||
`sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb`.
|
||||
|
||||
This file inventories every direct reference to the checkout's stdlib source
|
||||
directory found for issue #11 Phase A, before the explicit build-input change.
|
||||
It is an inventory, not a claim that Phase A is finished; the executed evidence
|
||||
is recorded separately when the work lands. Decision:
|
||||
[ADR-0070](../adr/0070-explicit-stdlib-bundle-build-input.md).
|
||||
|
||||
## Packaging and release tooling
|
||||
|
||||
| Entry point | Reference | Phase A disposition |
|
||||
|---|---|---|
|
||||
| `tools/pack-stdlib.py` | `STDLIB = ROOT / "stdlib"` (line 17); used by the tree digest, manifest read, file list, archive and descriptor (lines 37–97) | required `--stdlib-dir`, optional `--bundle-pin`; shared digest/verify helper |
|
||||
| `tools/release/package.py` | `STDLIB = ROOT / "stdlib"` (line 37); `verify_stdlib` (lines 110–141), staging copy (line 229), `RELEASE_INFO.stdlib` (lines 245–264) | required `--stdlib-dir`, optional `--bundle-pin`; `RELEASE_INFO.stdlib.source` records the pinned commit |
|
||||
| `tools/release/smoke.py` | reads only the extracted archive's `install/stdlib` (lines 81–116) | unchanged; it stays an independent verifier of the shipped bytes |
|
||||
| `tools/perf/runner.py` | pops `MARQDO_STDLIB_DIR`, then falls back to `ROOT / "stdlib"` when the binary has no sibling bundle (lines 327–330) | resolve the pinned Bundle explicitly and always export `MARQDO_STDLIB_DIR`; no silent repo fallback |
|
||||
| `tools/ci/test_release_archive.py` | reads `ROOT/stdlib/stdlib.json` and `ROOT/stdlib` (lines 33, 40, 54) | pass the explicit/pinned path; add failure-path assertions |
|
||||
| `.github/workflows/ci.yml` | `package.py` invocation without a Bundle argument (line 224); product lane (lines 44–45) | pass `--stdlib-dir` + `--bundle-pin`; verify the pin in the product lane |
|
||||
| `.woodpecker/main.yml` | product lane (line 51), `package.py` invocation (line 80) | same as above |
|
||||
| `.woodpecker/performance.yml` | `package.py` invocation (line 25) | pass `--stdlib-dir` + `--bundle-pin`; perf runner resolves the pin |
|
||||
| `docs/releasing.md` | release command without a Bundle argument (line 119) | document the required input and the pin |
|
||||
|
||||
## Runtime and development discovery
|
||||
|
||||
| Entry point | Reference | Phase A disposition |
|
||||
|---|---|---|
|
||||
| `crates/cli/src/stdlib.rs` | debug-only `CARGO_MANIFEST_DIR/../../stdlib` fallback after `MARQDO_STDLIB_DIR` and the sibling directory (lines 73–82) | keep for the development loop; remove in Phase B |
|
||||
| `crates/cli/src/stdlib.rs` unit tests | `dev_bundle()` loads the whole in-repo tree (lines 457–492) | replace with synthetic small bundles so loader tests do not depend on the product tree |
|
||||
|
||||
## Test harnesses that rebuild `repo_root()/stdlib`
|
||||
|
||||
| Harness | Reference | Role | Phase A disposition |
|
||||
|---|---|---|---|
|
||||
| `crates/cli/tests/stdlib_product.rs` | `stdlib_dir()` (lines 35–37), fixtures (line 48), cwd/`MARQDO_STDLIB_DIR` (lines 130–138) | product | pinned resolver |
|
||||
| `crates/cli/tests/stdlib_bundle.rs` | `stdlib_dir()` (lines 19–20) | product | pinned resolver |
|
||||
| `crates/cli/tests/stdlib_http.rs` | cwd and `MARQDO_STDLIB_DIR` (lines 22–23) | product | pinned resolver |
|
||||
| `crates/cli/tests/stdlib_table.rs` | cwd and `MARQDO_STDLIB_DIR` (lines 21–22) | product | pinned resolver |
|
||||
| `crates/cli/tests/stdlib_alias_routing.rs` | copies `repo()/stdlib` (lines 64–65) | product | pinned resolver |
|
||||
| `crates/cli/tests/p2_closure.rs` | table self-test path, cwd and env (lines 112, 122–123) | product | pinned resolver |
|
||||
| `crates/cli/tests/conformance_semantics.rs` | alias binding (line 294), entry `std:` imports (line 431) | conformance | pinned resolver |
|
||||
| `crates/cli/tests/architecture_boundaries.rs` | in-repo digest/import gates (lines 90–114, 442–477) | architecture gate | pinned resolver plus the Phase A in-repo assertion |
|
||||
|
||||
## References that are intentionally not build inputs
|
||||
|
||||
* `crates/cli/src/analysis/*`, `crates/cli/src/loader.rs` and
|
||||
`crates/cli/src/commands.rs` consume the verified `StdlibBundle` identity at
|
||||
run time; they do not read the source directory.
|
||||
* `crates/marqdo-runtime/src/builtins_impl.rs` and
|
||||
`crates/marqdo-sandbox/*` mention stdlib only in diagnostics/tests.
|
||||
* `docs/evidence/*` and historical ADRs keep their recorded paths; they are
|
||||
decision history, not executable inputs.
|
||||
|
||||
## Acceptance for Phase A
|
||||
|
||||
1. A clean copy without `stdlib/` and without an ecosystem checkout builds
|
||||
`marqdo-cli` and `marqdo-provider-worker` with `--locked`.
|
||||
2. Both packaging entries fail without `--stdlib-dir`, and fail on a missing
|
||||
directory, a missing `stdlib.json`, a tree-digest mismatch, an alias-digest
|
||||
mismatch or a pin mismatch.
|
||||
3. Product tests, the performance runner and release CI resolve the Bundle
|
||||
through `tools/stdlib/bundle.py` and name its pinned commit and digest.
|
||||
4. The frozen Conformance corpus and the independent `tools/release/smoke.py`
|
||||
checks stay in place.
|
||||
+6
-3
@@ -27,9 +27,12 @@ dominated by emulation and is not comparable with native or KVM.
|
||||
## Tool
|
||||
|
||||
`tools/perf/runner.py` (schema `marqdo.perf.v2`) builds one release binary,
|
||||
records its SHA256/Cargo.lock/rustc/source SHA, verifies every workload's exact
|
||||
wire digest **before** timing, then reports warmups/samples, p50, p95, MAD,
|
||||
CPU user/sys, peak RSS and the environment manifest. See
|
||||
records its SHA256/Cargo.lock/rustc/source SHA, resolves one pinned stdlib
|
||||
Bundle (name, version, tree/alias digests, source commit) and passes it to every
|
||||
workload as `MARQDO_STDLIB_DIR`, verifies every workload's exact wire digest
|
||||
**before** timing, then reports warmups/samples, p50, p95, MAD, CPU user/sys,
|
||||
peak RSS and the environment manifest. A bad Bundle input or digest mismatch
|
||||
fails before any workload runs; there is no checkout fallback (ADR-0070). See
|
||||
[`tools/perf/README.md`](../tools/perf/README.md).
|
||||
|
||||
Rules enforced by the tool:
|
||||
|
||||
+11
-4
@@ -116,7 +116,8 @@ The archive is built deterministically from a clean tree at `SOURCE_SHA`:
|
||||
version="$(cargo metadata --no-deps --format-version 1 --offline \
|
||||
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
|
||||
sha="$(git rev-parse HEAD)"
|
||||
python3 tools/release/package.py --version "$version" --source-sha "$sha"
|
||||
python3 tools/release/package.py --version "$version" --source-sha "$sha" \
|
||||
--stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json
|
||||
# dist/marqdo-<version>-x86_64-unknown-linux-gnu.tar.gz(+.sha256)
|
||||
```
|
||||
|
||||
@@ -128,9 +129,15 @@ and self-test), `LICENSE-APACHE`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md
|
||||
artifacts so the examples run without a compiler) and `tests/consumers/`.
|
||||
|
||||
`RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`,
|
||||
`aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests
|
||||
with the same canonical algorithm as the runtime and refuses to package a mismatch
|
||||
with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04).
|
||||
`aliases_digest`, `file_count` and `files`, plus `stdlib.source` (kind,
|
||||
repository, commit, path) when `--bundle-pin` is given. `--stdlib-dir` is a
|
||||
required build input and names the unpacked Bundle root; `package.py` verifies
|
||||
its manifest and recomputes both digests with the same canonical algorithm as
|
||||
the runtime, and fails on a missing directory, a missing `stdlib.json`, a
|
||||
tree/alias digest mismatch or a pin mismatch before it stages anything
|
||||
(ADR-0070, RFC-EXT-0003 H-08 / T-PKG-04). The pin itself is resolved and
|
||||
verified by `python3 tools/stdlib/bundle.py`; tests, the performance runner and
|
||||
release CI use the same resolver instead of an implicit checkout path.
|
||||
The `protocols.analysis` field identifies the default Analysis major.
|
||||
`protocols.analysis_versions` lists all majors the archive can emit.
|
||||
The archive smoke exercises a published example and a consumer for each major. The bundled stdlib is a
|
||||
|
||||
@@ -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: extractLine truncated
|
||||
@@ -33,6 +33,7 @@ tests/
|
||||
│ ├── warnings/ 2 × warning-model/control fixtures + *.expected.json
|
||||
│ └── runtime/ 20 × runtime-error fixtures + *.expected.json
|
||||
├── embedding/ Independent Engine consumer (own workspace + lock)
|
||||
├── sdk-plugin/ Third-party plugin built only with the public Rust SDK
|
||||
└── README.md this file
|
||||
```
|
||||
|
||||
@@ -52,9 +53,28 @@ 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. |
|
||||
|
||||
## Stdlib Bundle lanes (ADR-0070)
|
||||
|
||||
The product lane consumes one pinned Bundle, never an implicit checkout path:
|
||||
|
||||
* `tools/stdlib/bundle-pin.json` pins the Bundle name, version, source commit,
|
||||
tree digest and alias digest; `tools/stdlib/bundle.py` resolves and verifies
|
||||
it.
|
||||
* `crates/cli/tests/support/stdlib.rs` gives the product/conformance harnesses
|
||||
the same Bundle. `MARQDO_TEST_STDLIB_BUNDLE` or `--stdlib-dir` changes the
|
||||
location but the Bundle must still match the pin; `MARQDO_TEST_BUNDLE_PIN`
|
||||
changes the pin file. A bad explicit input fails even when the default
|
||||
location is valid.
|
||||
* Loader unit tests in `crates/cli/src/stdlib.rs` build small synthetic
|
||||
Bundles, so loader logic does not depend on the product tree.
|
||||
* `tests/independent/language-only.mq.md` is the program
|
||||
`tools/ci/independent_build.py` runs through a CLI built from a copy without
|
||||
`stdlib/`; a stdlib-dependent program must fail closed in that copy.
|
||||
|
||||
## Running
|
||||
|
||||
Use the workspace cargo cache/target as documented in `AGENTS.md`:
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Language-only program
|
||||
|
||||
This fixture uses only the language itself: no `std:` import, no host
|
||||
capability, no foreign kernel and no plugin. It is the program the
|
||||
independent-build lane runs through a real CLI built from a copy without the
|
||||
`stdlib/` tree (ADR-0070).
|
||||
|
||||
## @exec main
|
||||
|
||||
`值 = 1 + 2`
|
||||
|
||||
`return 值`
|
||||
Generated
+198
@@ -0,0 +1,198 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-plugin-abi"
|
||||
version = "3.0.0-rc.4"
|
||||
dependencies = [
|
||||
"marqdo-value",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-plugin-sdk"
|
||||
version = "3.0.0-rc.4"
|
||||
dependencies = [
|
||||
"marqdo-plugin-abi",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-sdk-plugin-fixture"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"marqdo-plugin-sdk",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-span"
|
||||
version = "3.0.0-rc.4"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-value"
|
||||
version = "3.0.0-rc.4"
|
||||
dependencies = [
|
||||
"marqdo-span",
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "marqdo-sdk-plugin-fixture"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
# Independent workspace: this fixture must build with only the public SDK
|
||||
# artifacts, exactly as a third-party plugin would.
|
||||
[workspace]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" }
|
||||
@@ -0,0 +1,5 @@
|
||||
## @exec main
|
||||
|
||||
`结果 = sdk.add(a=20, b=22)`
|
||||
|
||||
`return 结果`
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Minimal third-party plugin built only against the public Rust SDK.
|
||||
//!
|
||||
//! It exercises the typed wire helpers (`decode_request`, `int_arg`,
|
||||
//! `success`) and a `Value::Int` result. Real negotiation, loading and
|
||||
//! invocation are performed by the frozen CLI in
|
||||
//! `tools/ci/check_plugin_sdk.py`.
|
||||
|
||||
use marqdo_plugin_sdk::wire;
|
||||
use marqdo_plugin_sdk::{mq_plugin_entry, CallContext, PluginError, Value};
|
||||
|
||||
fn add(_ctx: &mut CallContext, args: &[u8]) -> Result<Vec<u8>, 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<Vec<u8>, 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,
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ WORKSPACE_CRATES = {
|
||||
"marqdo-sandbox": "native host support: OS isolation probe and strict launch",
|
||||
"marqdo-foreign": "native host support: controlled one-shot foreign kernels (F-A)",
|
||||
"marqdo-plugin-abi": "public contract: C ABI types, wire envelope and protocol errors",
|
||||
"marqdo-plugin-sdk": "public contract consumer: third-party plugin development helpers",
|
||||
"marqdo-worker-ipc": "shared plumbing: one bounded worker frame transport",
|
||||
"marqdo-provider-worker": "shipped worker: provider helper process",
|
||||
"marqdo-package": "product support: project manifest, lock and dependency resolution",
|
||||
@@ -239,14 +240,22 @@ def check_workspace(metadata: dict) -> list[str]:
|
||||
f"dependency `{forbidden}`"
|
||||
)
|
||||
|
||||
# ADR-0072: the SDK is an independent repository. The CLI workspace must
|
||||
# not carry it again; a new member here would be an undocumented layer and
|
||||
# would resurrect a second contract-consumer copy.
|
||||
if "marqdo-plugin-sdk" in members:
|
||||
problems.append(
|
||||
"marqdo-plugin-sdk must not be a CLI workspace member; the SDK is the "
|
||||
"independent repository pinned to a contract revision (ADR-0072)"
|
||||
)
|
||||
sdk = "marqdo-plugin-sdk"
|
||||
if sdk in graph:
|
||||
closure = reachable(graph, sdk, BUILD_KINDS)
|
||||
for forbidden in (
|
||||
"libloading",
|
||||
"marqdo-worker-ipc",
|
||||
"marqdo-host",
|
||||
"marqdo-sandbox",
|
||||
"marqdo-cli",
|
||||
"marqdo-provider-worker",
|
||||
):
|
||||
if forbidden in closure:
|
||||
problems.append(
|
||||
f"plugin SDK reaches execution-side dependency `{forbidden}`: "
|
||||
f"{closure[forbidden]}"
|
||||
)
|
||||
|
||||
# CLT Tool / package identity is a product concern; the CLI is the only
|
||||
# crate allowed to combine engine + native host + package.
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real third-party plugin SDK consumption gate (issue #13 §6.3, S04-S05).
|
||||
|
||||
Builds the fixture in ``tests/sdk-plugin`` with only the public Rust SDK, creates
|
||||
the host-specific ``plugin.yaml``, then lets a real built CLI load and invoke it
|
||||
with explicit trust and an explicit plugin grant. A tampered digest must fail
|
||||
closed. No mock host, no direct Rust call into plugin internals.
|
||||
|
||||
Usage:
|
||||
python3 tools/ci/check_plugin_sdk.py [--offline]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
FIXTURE = REPO_ROOT / "tests" / "sdk-plugin"
|
||||
CALL_DOC = FIXTURE / "call.mq.md"
|
||||
|
||||
|
||||
class GateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def cargo() -> str:
|
||||
path = shutil.which("cargo")
|
||||
if path is None:
|
||||
raise GateError("cargo is not on PATH")
|
||||
return path
|
||||
|
||||
|
||||
def run(command: list[str], *, check: bool = True) -> subprocess.CompletedProcess:
|
||||
result = subprocess.run(
|
||||
command, cwd=REPO_ROOT, capture_output=True, text=True, check=False
|
||||
)
|
||||
if check and result.returncode != 0:
|
||||
raise GateError(
|
||||
f"`{' '.join(command)}` failed with {result.returncode}:\n"
|
||||
f"{result.stdout}\n{result.stderr}"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def host_triple() -> str:
|
||||
result = run(["rustc", "-vV"])
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith("host: "):
|
||||
return line[len("host: ") :].strip()
|
||||
raise GateError("rustc -vV did not report a host triple")
|
||||
|
||||
|
||||
def artifact_name() -> str:
|
||||
system = platform.system()
|
||||
if system == "Darwin":
|
||||
return "libmarqdo_sdk_plugin_fixture.dylib"
|
||||
if system == "Windows":
|
||||
return "marqdo_sdk_plugin_fixture.dll"
|
||||
return "libmarqdo_sdk_plugin_fixture.so"
|
||||
|
||||
|
||||
def write_manifest(
|
||||
directory: Path,
|
||||
digest: str,
|
||||
triple: str,
|
||||
artifact: str,
|
||||
*,
|
||||
tamper: bool = False,
|
||||
) -> None:
|
||||
effective = "0" * 64 if tamper else digest
|
||||
manifest = f"""plugin:
|
||||
name: sdk.demo
|
||||
version: 0.1.0
|
||||
abi: "^1.0"
|
||||
kind: native
|
||||
exports:
|
||||
- name: sdk.add
|
||||
signature: "($a: Int, $b: Int) -> Int"
|
||||
- name: sdk.echo
|
||||
signature: "($text: Text) -> Text"
|
||||
artifacts:
|
||||
- target: {triple}
|
||||
file: {artifact}
|
||||
sha256: "{effective}"
|
||||
"""
|
||||
(directory / "plugin.yaml").write_text(manifest, encoding="utf-8")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--offline", action="store_true")
|
||||
parser.add_argument(
|
||||
"--sdk-revision",
|
||||
default=None,
|
||||
help="informational: exact CLI/SDK source revision under test",
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
offline = ["--offline"] if arguments.offline else []
|
||||
try:
|
||||
run([cargo(), "build", "--locked", "-p", "marqdo-cli", *offline])
|
||||
run([cargo(), "build", "--locked", "--manifest-path", str(FIXTURE / "Cargo.toml"), *offline])
|
||||
name = artifact_name()
|
||||
built = FIXTURE / "target" / "debug" / name
|
||||
if not built.is_file():
|
||||
raise GateError(f"SDK fixture artifact not found: {built}")
|
||||
triple = host_triple()
|
||||
binary = REPO_ROOT / "target" / "debug" / "marqdo"
|
||||
if not binary.is_file():
|
||||
raise GateError(f"CLI binary not found: {binary}")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="marqdo-sdk-plugin-") as raw:
|
||||
directory = Path(raw)
|
||||
artifact = "plugin" + Path(name).suffix
|
||||
shutil.copyfile(built, directory / artifact)
|
||||
digest = hashlib.sha256((directory / artifact).read_bytes()).hexdigest()
|
||||
command = [
|
||||
str(binary),
|
||||
"call",
|
||||
str(CALL_DOC),
|
||||
"main",
|
||||
"--plugin",
|
||||
str(directory),
|
||||
"--trust-native-plugin",
|
||||
"--allow-plugin",
|
||||
"sdk.demo",
|
||||
]
|
||||
|
||||
write_manifest(directory, digest, triple, artifact)
|
||||
positive = run(command, check=False)
|
||||
if positive.returncode != 0 or positive.stdout.strip() != "42":
|
||||
raise GateError(
|
||||
"real CLI could not invoke the SDK plugin: "
|
||||
f"exit={positive.returncode} stdout={positive.stdout!r} "
|
||||
f"stderr={positive.stderr!r}"
|
||||
)
|
||||
print("PASS sdk-plugin-real-invocation (Int 42)")
|
||||
|
||||
write_manifest(directory, digest, triple, artifact, tamper=True)
|
||||
negative = run(command, check=False)
|
||||
if negative.returncode == 0:
|
||||
raise GateError("tampered plugin artifact digest was accepted")
|
||||
combined = negative.stdout + negative.stderr
|
||||
if "sha256" not in combined.lower() and "artifact" not in combined.lower():
|
||||
raise GateError(
|
||||
"tampered artifact failed without an artifact/sha256 diagnostic: "
|
||||
+ combined
|
||||
)
|
||||
print("PASS sdk-plugin-tampered-digest-rejected")
|
||||
except GateError as error:
|
||||
print(f"FAIL plugin-sdk: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print("PASS plugin-sdk")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove the CLI and Provider Worker build without any stdlib source (ADR-0070).
|
||||
|
||||
The script exports one committed revision with `git archive`, removes the
|
||||
`stdlib/` tree (there is no ecosystem checkout either), builds
|
||||
`marqdo-cli` + `marqdo-provider-worker` with `--locked`, and then:
|
||||
|
||||
* runs a language-only program through the freshly built CLI (`check` + `call`);
|
||||
* requires a stdlib-dependent program to fail closed — the debug source
|
||||
fallback points at the removed copy, so a success would be a real defect;
|
||||
* requires no `stdlib/` directory next to the built binary;
|
||||
* records both binary digests and the source SHA.
|
||||
|
||||
Usage:
|
||||
|
||||
python3 tools/ci/independent_build.py
|
||||
python3 tools/ci/independent_build.py --offline --keep
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BINARIES = ("marqdo", "marqdo-provider-worker")
|
||||
LANGUAGE_ONLY = Path("tests/independent/language-only.mq.md")
|
||||
STDLIB_DEPENDENT = Path("examples/hello.mq.md")
|
||||
MISSING_BUNDLE_PATTERN = re.compile(r"stdlib|symbol\.unknown|打印|print", re.IGNORECASE)
|
||||
|
||||
|
||||
class BuildError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def run(
|
||||
command: list[str],
|
||||
cwd: Path,
|
||||
*,
|
||||
env: dict[str, str] | None = None,
|
||||
timeout: float = 1800,
|
||||
check: bool = True,
|
||||
) -> subprocess.CompletedProcess:
|
||||
completed = subprocess.run(
|
||||
command,
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if check and completed.returncode != 0:
|
||||
raise BuildError(
|
||||
f"command failed ({completed.returncode}): {' '.join(command)}\n"
|
||||
f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"
|
||||
)
|
||||
return completed
|
||||
|
||||
|
||||
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_output(repo: Path, *arguments: str) -> bytes:
|
||||
completed = subprocess.run(
|
||||
["git", "-C", str(repo), *arguments],
|
||||
capture_output=True,
|
||||
)
|
||||
if completed.returncode != 0:
|
||||
raise BuildError(
|
||||
f"git {' '.join(arguments)} failed: {completed.stderr.decode(errors='replace')}"
|
||||
)
|
||||
return completed.stdout
|
||||
|
||||
|
||||
def export_revision(repo: Path, revision: str, destination: Path) -> str:
|
||||
try:
|
||||
head = git_output(repo, "rev-parse", revision).decode().strip()
|
||||
archive = git_output(repo, "archive", "--format=tar", revision)
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
raise BuildError(f"cannot export {revision} from {repo}: {error}") from error
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:") as tar:
|
||||
try:
|
||||
tar.extractall(destination, filter="fully_trusted")
|
||||
except TypeError: # Python < 3.12 without the PEP 706 backport
|
||||
tar.extractall(destination)
|
||||
return head
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--repo", default=str(ROOT))
|
||||
parser.add_argument("--source", default="HEAD", help="committed revision to export")
|
||||
parser.add_argument("--work-dir", default=None, help="explicit work directory (kept)")
|
||||
parser.add_argument("--target-dir", default=None, help="cargo target directory (kept)")
|
||||
parser.add_argument("--offline", action="store_true")
|
||||
parser.add_argument("--keep", action="store_true")
|
||||
parser.add_argument("--timeout", type=float, default=1800.0)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
repo = Path(args.repo).resolve()
|
||||
if args.work_dir:
|
||||
work = Path(args.work_dir).resolve()
|
||||
if work.exists():
|
||||
shutil.rmtree(work)
|
||||
keep = True
|
||||
else:
|
||||
work = Path(tempfile.mkdtemp(prefix="marqdo-independent-build-"))
|
||||
keep = args.keep
|
||||
target = Path(args.target_dir).resolve() if args.target_dir else work / "target"
|
||||
source = work / "source"
|
||||
try:
|
||||
source_sha = export_revision(repo, args.source, source)
|
||||
stdlib = source / "stdlib"
|
||||
if not stdlib.is_dir():
|
||||
raise BuildError(
|
||||
"the exported revision has no stdlib/ tree; the lane must remove a "
|
||||
"real Bundle to prove the build does not need it"
|
||||
)
|
||||
shutil.rmtree(stdlib)
|
||||
if stdlib.exists():
|
||||
raise BuildError(f"failed to remove {stdlib}")
|
||||
|
||||
env = os.environ.copy()
|
||||
env.pop("MARQDO_STDLIB_DIR", None)
|
||||
env["CARGO_TARGET_DIR"] = str(target)
|
||||
env.setdefault("NO_COLOR", "1")
|
||||
command = ["cargo", "build", "--locked", "-p", "marqdo-cli", "-p", "marqdo-provider-worker"]
|
||||
if args.offline:
|
||||
command.append("--offline")
|
||||
run(command, source, env=env, timeout=args.timeout)
|
||||
|
||||
binary = target / "debug" / "marqdo"
|
||||
if not binary.is_file():
|
||||
raise BuildError(f"the build produced no CLI binary at {binary}")
|
||||
if (binary.parent / "stdlib").exists():
|
||||
raise BuildError(f"a stdlib/ directory appeared next to {binary}")
|
||||
binaries = {}
|
||||
for name in BINARIES:
|
||||
path = target / "debug" / name
|
||||
if not path.is_file():
|
||||
raise BuildError(f"the build produced no {name} binary at {path}")
|
||||
binaries[name] = {"sha256": sha256_file(path), "size": path.stat().st_size}
|
||||
|
||||
checked = run([str(binary), "check", str(LANGUAGE_ONLY)], source, env=env, timeout=args.timeout)
|
||||
called = run(
|
||||
[str(binary), "call", str(LANGUAGE_ONLY), "main"],
|
||||
source,
|
||||
env=env,
|
||||
timeout=args.timeout,
|
||||
)
|
||||
if called.stdout.strip() != "3":
|
||||
raise BuildError(
|
||||
f"language-only call printed {called.stdout.strip()!r}, expected '3'"
|
||||
)
|
||||
missing = run(
|
||||
[str(binary), "run", str(STDLIB_DEPENDENT)],
|
||||
source,
|
||||
env=env,
|
||||
timeout=args.timeout,
|
||||
check=False,
|
||||
)
|
||||
if missing.returncode == 0:
|
||||
raise BuildError(
|
||||
"a stdlib-dependent program succeeded without any stdlib Bundle "
|
||||
"(a source fallback exists); this is a release blocker"
|
||||
)
|
||||
if not MISSING_BUNDLE_PATTERN.search(missing.stderr + missing.stdout):
|
||||
raise BuildError(
|
||||
"the missing-Bundle failure does not name the stdlib/print/symbol "
|
||||
f"cause:\n{missing.stderr}"
|
||||
)
|
||||
|
||||
summary = {
|
||||
"schema": "marqdo.independent-build",
|
||||
"schema_version": 1,
|
||||
"source_sha": source_sha,
|
||||
"source_revision": args.source,
|
||||
"copy": str(source),
|
||||
"target_dir": str(target),
|
||||
"binaries": binaries,
|
||||
"checks": {
|
||||
"stdlib_source_removed": True,
|
||||
"language_only_check": "PASS",
|
||||
"language_only_call": "PASS:3",
|
||||
"stdlib_dependent_missing_bundle": "PASS",
|
||||
"no_sibling_stdlib": True,
|
||||
},
|
||||
"status": "PASS",
|
||||
}
|
||||
print(json.dumps(summary, indent=2, sort_keys=True))
|
||||
return 0
|
||||
except BuildError as error:
|
||||
print(f"independent-build: error: {error}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
if not keep:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -82,6 +82,7 @@ def valid_workspace_edges() -> dict[str, list[str]]:
|
||||
"marqdo-span",
|
||||
]
|
||||
edges["marqdo-plugin-abi"] = ["marqdo-value"]
|
||||
edges["marqdo-plugin-sdk"] = ["marqdo-plugin-abi"]
|
||||
edges["marqdo-worker-ipc"] = []
|
||||
edges["marqdo-sandbox"] = []
|
||||
edges["marqdo-foreign"] = ["marqdo-worker-ipc"]
|
||||
@@ -184,15 +185,10 @@ class DependencyBoundaryTests(unittest.TestCase):
|
||||
"must not carry execution-side dependency `libloading`",
|
||||
)
|
||||
|
||||
def test_sdk_reappearing_as_workspace_member_is_rejected(self) -> None:
|
||||
edges = valid_workspace_edges()
|
||||
edges["marqdo-plugin-sdk"] = ["marqdo-plugin-abi"]
|
||||
workspace = metadata(edges, members=set(gate.WORKSPACE_CRATES) | {"marqdo-plugin-sdk"})
|
||||
consumer = metadata(valid_consumer_edges(), members={"marqdo-embedding-consumer"})
|
||||
problems = gate.evaluate(workspace, consumer)
|
||||
self.assertTrue(
|
||||
any("must not be a CLI workspace member" in problem for problem in problems),
|
||||
problems,
|
||||
def test_sdk_host_edge_is_rejected(self) -> None:
|
||||
self.assert_rejected(
|
||||
lambda edges: edges["marqdo-plugin-sdk"].append("marqdo-host"),
|
||||
"plugin SDK reaches execution-side dependency `marqdo-host`",
|
||||
)
|
||||
|
||||
def test_undocumented_workspace_crate_is_rejected(self) -> None:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
These tests are stdlib-only and do not build an archive; they pin the digest
|
||||
helpers that package.py/smoke.py share with the runtime and check that the
|
||||
release pipeline references a verified stdlib bundle instead of relying on the
|
||||
compile-time source path.
|
||||
release pipeline takes the stdlib Bundle as one explicit, verified input
|
||||
instead of relying on the compile-time source path (ADR-0070).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +12,8 @@ import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -31,10 +33,11 @@ class ReleaseArchiveContractTest(unittest.TestCase):
|
||||
self.package = load_module("release_package", ROOT / "tools/release/package.py")
|
||||
self.smoke = load_module("release_smoke", ROOT / "tools/release/smoke.py")
|
||||
self.manifest = json.loads((ROOT / "stdlib/stdlib.json").read_text(encoding="utf-8"))
|
||||
self.pin = json.loads((ROOT / "tools/stdlib/bundle-pin.json").read_text(encoding="utf-8"))
|
||||
|
||||
def test_tree_digest_matches_manifest(self) -> None:
|
||||
self.assertEqual(
|
||||
self.package.stdlib_tree_digest(), self.manifest["digest"]
|
||||
self.package.stdlib_tree_digest(ROOT / "stdlib"), self.manifest["digest"]
|
||||
)
|
||||
self.assertEqual(
|
||||
self.smoke.stdlib_tree_digest(ROOT / "stdlib"), self.manifest["digest"]
|
||||
@@ -51,7 +54,9 @@ class ReleaseArchiveContractTest(unittest.TestCase):
|
||||
)
|
||||
|
||||
def test_verify_record_names_required_files_and_count(self) -> None:
|
||||
record = self.package.verify_stdlib()
|
||||
record = self.package.verify_stdlib(
|
||||
ROOT / "stdlib", ROOT / "tools/stdlib/bundle-pin.json"
|
||||
)
|
||||
self.assertEqual(record["name"], self.manifest["name"])
|
||||
self.assertEqual(record["version"], self.manifest["version"])
|
||||
self.assertEqual(record["tree_digest"], self.manifest["digest"])
|
||||
@@ -60,13 +65,53 @@ class ReleaseArchiveContractTest(unittest.TestCase):
|
||||
self.assertIn("io.mq.md", record["files"])
|
||||
self.assertIn("io/console.mq.md", record["files"])
|
||||
self.assertEqual(record["file_count"], len(record["files"]))
|
||||
self.assertEqual(record["source"]["commit"], self.pin["source"]["commit"])
|
||||
self.assertEqual(record["source"]["kind"], "in-repo")
|
||||
|
||||
def test_package_stages_stdlib_next_to_the_binary_and_math_backend(self) -> None:
|
||||
def test_verify_record_has_no_source_without_a_pin(self) -> None:
|
||||
record = self.package.verify_stdlib(ROOT / "stdlib")
|
||||
self.assertNotIn("source", record)
|
||||
|
||||
def test_missing_explicit_input_fails_closed(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
stderr = io.StringIO()
|
||||
with contextlib.redirect_stderr(stderr):
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.package.verify_stdlib(Path(tmp) / "missing")
|
||||
self.assertEqual(raised.exception.code, 1)
|
||||
self.assertIn("does not exist", stderr.getvalue())
|
||||
|
||||
def test_tampered_explicit_input_and_wrong_pin_fail_closed(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
copy = Path(tmp) / "stdlib"
|
||||
shutil.copytree(ROOT / "stdlib", copy)
|
||||
(copy / "io.mq.md").write_text("## @knowledge tampered\n", encoding="utf-8")
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.package.verify_stdlib(copy)
|
||||
self.assertEqual(raised.exception.code, 1)
|
||||
|
||||
shutil.rmtree(copy)
|
||||
shutil.copytree(ROOT / "stdlib", copy)
|
||||
restamped = json.loads((copy / "stdlib.json").read_text(encoding="utf-8"))
|
||||
restamped["version"] = "9.9.9"
|
||||
(copy / "stdlib.json").write_text(json.dumps(restamped), encoding="utf-8")
|
||||
stderr = io.StringIO()
|
||||
with contextlib.redirect_stderr(stderr):
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.package.verify_stdlib(copy, ROOT / "tools/stdlib/bundle-pin.json")
|
||||
self.assertEqual(raised.exception.code, 1)
|
||||
self.assertIn("does not match the pin", stderr.getvalue())
|
||||
|
||||
def test_package_takes_one_explicit_stdlib_dir(self) -> None:
|
||||
source = (ROOT / "tools/release/package.py").read_text(encoding="utf-8")
|
||||
self.assertIn('copy_tree(STDLIB, stage_dir / "stdlib")', source)
|
||||
self.assertIn('"math-backend"', source.replace("math_backend", "math-backend"))
|
||||
self.assertIn('add_argument("--stdlib-dir", required=True)', source)
|
||||
self.assertIn('add_argument("--bundle-pin"', source)
|
||||
self.assertIn('copy_tree(stdlib_dir, stage_dir / "stdlib")', source)
|
||||
self.assertIn('"stdlib": stdlib_info', source)
|
||||
self.assertIn("verify_stdlib()", source)
|
||||
self.assertIn("verify_stdlib(", source)
|
||||
self.assertNotIn('STDLIB = ROOT / "stdlib"', source)
|
||||
self.assertIn('"math-backend"', source.replace("math_backend", "math-backend"))
|
||||
|
||||
def test_archive_declares_only_current_analysis_revision(self) -> None:
|
||||
self.smoke.verify_analysis_metadata({"analysis": 3})
|
||||
@@ -89,6 +134,7 @@ class ReleaseArchiveContractTest(unittest.TestCase):
|
||||
self.assertIn("verify_stdlib_bundle(install, info)", source)
|
||||
self.assertIn("verify_stdlib_bundle", source)
|
||||
self.assertIn("stdlib.hidden", source)
|
||||
self.assertIn("language-only program runs without the bundled stdlib", source)
|
||||
self.assertIn("expected 6", source)
|
||||
self.assertIn("permission.denied", source)
|
||||
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
"""Explicit stdlib Bundle input tests (ADR-0070 / issue #11 Phase A).
|
||||
|
||||
Covers the shared resolver (`tools/stdlib/bundle.py`) and the deterministic
|
||||
package entry point (`tools/pack-stdlib.py`). The digest helpers here are
|
||||
independent re-implementations so a bug in the shared helper cannot make the
|
||||
test agree with itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def load_module(name: str, path: Path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
assert spec.loader is not None
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def independent_tree_digest(root: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
paths = sorted(
|
||||
(path.relative_to(root).as_posix(), path)
|
||||
for path in root.rglob("*.mq.md")
|
||||
if path.is_file()
|
||||
)
|
||||
for relative, path in paths:
|
||||
digest.update(relative.encode())
|
||||
digest.update(b"\0")
|
||||
digest.update(path.read_bytes())
|
||||
digest.update(b"\0")
|
||||
return "sha256:" + digest.hexdigest()
|
||||
|
||||
|
||||
def independent_aliases_digest(aliases: list[dict]) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for alias in sorted(aliases, key=lambda item: (item["target_module"], item["target_function"])):
|
||||
digest.update(alias["target_module"].encode())
|
||||
digest.update(b"\0")
|
||||
digest.update(alias["target_function"].encode())
|
||||
digest.update(b"\0")
|
||||
for name in sorted(alias["public_names"]):
|
||||
digest.update(name.encode())
|
||||
digest.update(b"\0")
|
||||
return "sha256:" + digest.hexdigest()
|
||||
|
||||
|
||||
ALIASES = [
|
||||
{
|
||||
"public_names": ["print", "打印"],
|
||||
"target_module": "io.mq.md",
|
||||
"target_function": "写值",
|
||||
"expected_signature": "params(值)",
|
||||
"effects": ["write"],
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def make_bundle(root: Path, *, version: str = "9.9.9", name: str = "marqdo-stdlib") -> dict:
|
||||
"""Create a minimal Bundle with independently computed digests."""
|
||||
root.mkdir(parents=True)
|
||||
(root / "README.md").write_text("# test bundle\n")
|
||||
(root / "io.mq.md").write_text("## @knowledge io\n")
|
||||
(root / "io").mkdir()
|
||||
(root / "io" / "console.mq.md").write_text("## @knowledge console\n")
|
||||
manifest = {
|
||||
"schema": "marqdo.stdlib-bundle",
|
||||
"schema_version": 1,
|
||||
"name": name,
|
||||
"version": version,
|
||||
"digest": independent_tree_digest(root),
|
||||
"aliases_digest": independent_aliases_digest(ALIASES),
|
||||
"public_aliases": ALIASES,
|
||||
}
|
||||
(root / "stdlib.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
return manifest
|
||||
|
||||
|
||||
def write_pin(path: Path, manifest: dict, source_path: str, commit: str = "a" * 40) -> dict:
|
||||
pin = {
|
||||
"schema": "marqdo.stdlib-bundle-pin",
|
||||
"schema_version": 1,
|
||||
"name": manifest["name"],
|
||||
"version": manifest["version"],
|
||||
"source": {"kind": "test", "repository": "test/test", "commit": commit, "path": source_path},
|
||||
"tree_digest": manifest["digest"],
|
||||
"aliases_digest": manifest["aliases_digest"],
|
||||
}
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(pin, indent=2) + "\n")
|
||||
return pin
|
||||
|
||||
|
||||
class BundleResolverTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.bundle = load_module("stdlib_bundle", ROOT / "tools/stdlib/bundle.py")
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.dir = Path(self.tmp.name)
|
||||
|
||||
def test_repository_bundle_matches_the_pin(self) -> None:
|
||||
root, record, pin = self.bundle.resolve()
|
||||
self.assertEqual(root, (ROOT / "stdlib").resolve())
|
||||
self.assertEqual(record["tree_digest"], pin["tree_digest"])
|
||||
self.assertEqual(record["aliases_digest"], pin["aliases_digest"])
|
||||
self.assertEqual(record["name"], "marqdo-stdlib")
|
||||
self.assertIn("io.mq.md", record["files"])
|
||||
|
||||
def test_explicit_valid_bundle_still_has_to_match_the_pin(self) -> None:
|
||||
other = self.dir / "other-bundle"
|
||||
matching = make_bundle(other)
|
||||
pin_path = self.dir / "pin.json"
|
||||
write_pin(pin_path, matching, str(other))
|
||||
root, record, _ = self.bundle.resolve(other, pin_path)
|
||||
self.assertEqual(root, other.resolve())
|
||||
self.assertEqual(record["name"], "marqdo-stdlib")
|
||||
|
||||
pinned = load_module("stdlib_bundle_pin_check", ROOT / "tools/stdlib/bundle.py")
|
||||
self.assertRaisesRegex(
|
||||
pinned.BundleError,
|
||||
"does not match the pin",
|
||||
pinned.verify_pin,
|
||||
{"name": "marqdo-stdlib", "version": "0.1.0",
|
||||
"tree_digest": "sha256:" + "0" * 64, "aliases_digest": "sha256:" + "0" * 64},
|
||||
pinned.load_pin(ROOT / "tools/stdlib/bundle-pin.json"),
|
||||
)
|
||||
|
||||
def test_bad_explicit_input_fails_even_when_the_default_is_valid(self) -> None:
|
||||
with self.assertRaisesRegex(self.bundle.BundleError, "does not exist"):
|
||||
self.bundle.resolve(self.dir / "missing")
|
||||
|
||||
def test_missing_manifest_fails(self) -> None:
|
||||
bare = self.dir / "bare"
|
||||
bare.mkdir()
|
||||
(bare / "io.mq.md").write_text("## @knowledge io\n")
|
||||
with self.assertRaisesRegex(self.bundle.BundleError, "has no manifest"):
|
||||
self.bundle.verify(bare)
|
||||
|
||||
def test_tree_digest_mismatch_fails(self) -> None:
|
||||
bundle = self.dir / "tampered"
|
||||
make_bundle(bundle)
|
||||
(bundle / "io.mq.md").write_text("## @knowledge tampered\n")
|
||||
with self.assertRaisesRegex(self.bundle.BundleError, "tree digest mismatch"):
|
||||
self.bundle.verify(bundle)
|
||||
|
||||
def test_alias_digest_mismatch_fails(self) -> None:
|
||||
bundle = self.dir / "alias-tampered"
|
||||
manifest = make_bundle(bundle)
|
||||
manifest["aliases_digest"] = "sha256:" + "0" * 64
|
||||
(bundle / "stdlib.json").write_text(json.dumps(manifest) + "\n")
|
||||
with self.assertRaisesRegex(self.bundle.BundleError, "alias digest mismatch"):
|
||||
self.bundle.verify(bundle)
|
||||
|
||||
def test_public_aliases_without_a_digest_fail(self) -> None:
|
||||
bundle = self.dir / "no-alias-digest"
|
||||
manifest = make_bundle(bundle)
|
||||
del manifest["aliases_digest"]
|
||||
(bundle / "stdlib.json").write_text(json.dumps(manifest) + "\n")
|
||||
with self.assertRaisesRegex(self.bundle.BundleError, "without aliases_digest"):
|
||||
self.bundle.verify(bundle)
|
||||
|
||||
def test_symlink_inside_the_bundle_is_rejected(self) -> None:
|
||||
bundle = self.dir / "linked"
|
||||
make_bundle(bundle)
|
||||
try:
|
||||
(bundle / "escape.mq.md").symlink_to("/etc/hostname")
|
||||
except (OSError, NotImplementedError):
|
||||
self.skipTest("symbolic links are unavailable on this host")
|
||||
with self.assertRaisesRegex(self.bundle.BundleError, "symbolic link"):
|
||||
self.bundle.verify(bundle)
|
||||
|
||||
def test_bad_pin_schema_is_rejected(self) -> None:
|
||||
pin_path = self.dir / "bad-pin.json"
|
||||
pin_path.write_text(json.dumps({"schema": "other", "schema_version": 1}) + "\n")
|
||||
with self.assertRaisesRegex(self.bundle.BundleError, "schema_version"):
|
||||
self.bundle.load_pin(pin_path)
|
||||
|
||||
def test_cli_prints_the_resolved_path(self) -> None:
|
||||
stdout = io.StringIO()
|
||||
with contextlib.redirect_stdout(stdout):
|
||||
self.assertEqual(self.bundle.main(["--print-path"]), 0)
|
||||
self.assertEqual(Path(stdout.getvalue().strip()), (ROOT / "stdlib").resolve())
|
||||
|
||||
def test_cli_fails_for_an_invalid_explicit_input(self) -> None:
|
||||
stderr = io.StringIO()
|
||||
with contextlib.redirect_stderr(stderr):
|
||||
self.assertEqual(self.bundle.main(["--stdlib-dir", str(self.dir / "missing")]), 1)
|
||||
self.assertIn("does not exist", stderr.getvalue())
|
||||
|
||||
|
||||
class PackStdlibTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.pack = load_module("pack_stdlib", ROOT / "tools/pack-stdlib.py")
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.dir = Path(self.tmp.name)
|
||||
|
||||
def run_pack(self, *args: str) -> int:
|
||||
stdout = io.StringIO()
|
||||
with contextlib.redirect_stdout(stdout):
|
||||
return self.pack.main(list(args))
|
||||
|
||||
def test_stdlib_dir_is_required(self) -> None:
|
||||
with self.assertRaises(SystemExit) as raised, contextlib.redirect_stderr(io.StringIO()):
|
||||
self.pack.main([])
|
||||
self.assertEqual(raised.exception.code, 2)
|
||||
|
||||
def test_missing_input_fails(self) -> None:
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.run_pack("--stdlib-dir", str(self.dir / "missing"), "--out-dir", str(self.dir))
|
||||
self.assertIn("does not exist", str(raised.exception.code))
|
||||
|
||||
def test_missing_manifest_fails(self) -> None:
|
||||
bare = self.dir / "bare"
|
||||
bare.mkdir()
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.run_pack("--stdlib-dir", str(bare), "--out-dir", str(self.dir))
|
||||
self.assertIn("has no manifest", str(raised.exception.code))
|
||||
|
||||
def test_tampered_tree_fails(self) -> None:
|
||||
bundle = self.dir / "bundle"
|
||||
make_bundle(bundle)
|
||||
(bundle / "io.mq.md").write_text("## @knowledge tampered\n")
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.run_pack("--stdlib-dir", str(bundle), "--out-dir", str(self.dir))
|
||||
self.assertIn("tree digest mismatch", str(raised.exception.code))
|
||||
|
||||
def test_pin_mismatch_fails(self) -> None:
|
||||
bundle = self.dir / "bundle"
|
||||
manifest = make_bundle(bundle)
|
||||
pin_path = self.dir / "pin.json"
|
||||
pin = write_pin(pin_path, manifest, str(bundle))
|
||||
pin["tree_digest"] = "sha256:" + "0" * 64
|
||||
pin_path.write_text(json.dumps(pin) + "\n")
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self.run_pack(
|
||||
"--stdlib-dir", str(bundle), "--out-dir", str(self.dir), "--bundle-pin", str(pin_path)
|
||||
)
|
||||
self.assertIn("does not match the pin", str(raised.exception.code))
|
||||
|
||||
def test_pack_is_deterministic_and_records_the_bundle_identity(self) -> None:
|
||||
bundle = self.dir / "bundle"
|
||||
manifest = make_bundle(bundle)
|
||||
pin_path = self.dir / "pin.json"
|
||||
write_pin(pin_path, manifest, str(bundle))
|
||||
first = self.dir / "first"
|
||||
second = self.dir / "second"
|
||||
for out in (first, second):
|
||||
self.assertEqual(
|
||||
self.run_pack(
|
||||
"--stdlib-dir", str(bundle), "--out-dir", str(out),
|
||||
"--bundle-pin", str(pin_path),
|
||||
),
|
||||
0,
|
||||
)
|
||||
archive_name = "marqdo-stdlib-9.9.9.tar.gz"
|
||||
first_bytes = (first / archive_name).read_bytes()
|
||||
self.assertEqual(first_bytes, (second / archive_name).read_bytes())
|
||||
self.assertEqual(
|
||||
(first / f"{archive_name}.sha256").read_bytes(),
|
||||
(second / f"{archive_name}.sha256").read_bytes(),
|
||||
)
|
||||
descriptor = json.loads((first / "marqdo-stdlib-9.9.9.json").read_text())
|
||||
self.assertEqual(descriptor["schema"], "marqdo.stdlib-package")
|
||||
self.assertEqual(descriptor["schema_version"], 1)
|
||||
self.assertEqual(descriptor["name"], manifest["name"])
|
||||
self.assertEqual(descriptor["version"], manifest["version"])
|
||||
self.assertEqual(descriptor["tree_digest"], independent_tree_digest(bundle))
|
||||
self.assertEqual(descriptor["aliases_digest"], independent_aliases_digest(ALIASES))
|
||||
self.assertEqual(
|
||||
descriptor["archive_sha256"], "sha256:" + hashlib.sha256(first_bytes).hexdigest()
|
||||
)
|
||||
self.assertEqual(descriptor["files"], sorted(descriptor["files"]))
|
||||
|
||||
with tarfile.open(first / archive_name, mode="r:gz") as archive:
|
||||
members = archive.getmembers()
|
||||
self.assertEqual([m.name for m in members], descriptor["files"])
|
||||
for member in members:
|
||||
self.assertEqual(member.mtime, 0)
|
||||
self.assertIn(member.uid, (0,))
|
||||
self.assertEqual(member.gid, 0)
|
||||
self.assertEqual(member.mode, 0o644)
|
||||
self.assertEqual(
|
||||
archive.extractfile("io.mq.md").read(), (bundle / "io.mq.md").read_bytes()
|
||||
)
|
||||
|
||||
def test_repository_bundle_packs_against_the_committed_pin(self) -> None:
|
||||
out = self.dir / "out"
|
||||
self.assertEqual(
|
||||
self.run_pack(
|
||||
"--stdlib-dir", str(ROOT / "stdlib"), "--out-dir", str(out),
|
||||
"--bundle-pin", str(ROOT / "tools/stdlib/bundle-pin.json"),
|
||||
),
|
||||
0,
|
||||
)
|
||||
descriptor = json.loads((out / "marqdo-stdlib-0.1.0.json").read_text())
|
||||
manifest = json.loads((ROOT / "stdlib/stdlib.json").read_text())
|
||||
self.assertEqual(descriptor["tree_digest"], manifest["digest"])
|
||||
self.assertEqual(descriptor["aliases_digest"], manifest["aliases_digest"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+61
-64
@@ -1,74 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a deterministic offline marqdo-stdlib package.
|
||||
"""Build a deterministic offline marqdo-stdlib package from an explicit Bundle.
|
||||
|
||||
The archive is intended for the separate external stdlib repository/release
|
||||
workflow, not for the CLI's in-repo development fallback. It contains the
|
||||
Markdown stdlib tree, stdlib.json and README.md, with stable mtimes/ownership.
|
||||
The input is one unpacked Bundle root (a directory that contains
|
||||
`stdlib.json`), passed with the required `--stdlib-dir`. This script does not
|
||||
read the checkout's `stdlib/` implicitly: the CLI release and the separate
|
||||
stdlib release workflow both name the Bundle they package (ADR-0070).
|
||||
|
||||
The archive contains the Markdown stdlib tree, `stdlib.json` and every other
|
||||
file in the Bundle, with stable mtimes/ownership. An optional `--bundle-pin`
|
||||
also requires the input to match the pinned name/version/commit/digests.
|
||||
|
||||
Usage:
|
||||
|
||||
python3 tools/pack-stdlib.py --stdlib-dir stdlib \
|
||||
--bundle-pin tools/stdlib/bundle-pin.json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STDLIB = ROOT / "stdlib"
|
||||
DIST = ROOT / "dist"
|
||||
|
||||
|
||||
def aliases_digest(manifest: dict) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for alias in sorted(
|
||||
manifest.get("public_aliases", []),
|
||||
key=lambda a: (a["target_module"], a["target_function"]),
|
||||
):
|
||||
digest.update(alias["target_module"].encode())
|
||||
digest.update(b"\0")
|
||||
digest.update(alias["target_function"].encode())
|
||||
digest.update(b"\0")
|
||||
for name in sorted(alias["public_names"]):
|
||||
digest.update(name.encode())
|
||||
digest.update(b"\0")
|
||||
return f"sha256:{digest.hexdigest()}"
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent / "stdlib"))
|
||||
import bundle as stdlib_bundle # noqa: E402
|
||||
|
||||
|
||||
def tree_digest() -> str:
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted(
|
||||
STDLIB.rglob("*.mq.md"), key=lambda p: p.relative_to(STDLIB).as_posix()
|
||||
):
|
||||
relative = path.relative_to(STDLIB).as_posix()
|
||||
digest.update(relative.encode())
|
||||
digest.update(b"\0")
|
||||
digest.update(path.read_bytes())
|
||||
digest.update(b"\0")
|
||||
return digest.hexdigest()
|
||||
def gzip_open(raw):
|
||||
import gzip
|
||||
|
||||
return gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, filename="")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
manifest = json.loads((STDLIB / "stdlib.json").read_text())
|
||||
version = manifest["version"]
|
||||
digest = tree_digest()
|
||||
if manifest["digest"] != f"sha256:{digest}":
|
||||
raise SystemExit("stdlib.json digest does not match the tree")
|
||||
alias_digest = aliases_digest(manifest)
|
||||
if manifest.get("aliases_digest") != alias_digest:
|
||||
raise SystemExit("stdlib.json aliases_digest does not match public_aliases")
|
||||
def verify_input(root: Path, pin_path: Path | None) -> dict:
|
||||
try:
|
||||
record = stdlib_bundle.verify(root)
|
||||
stdlib_bundle.require_files(record, ("stdlib.json",))
|
||||
if record["aliases_digest"] is None:
|
||||
raise stdlib_bundle.BundleError(
|
||||
f"{root / 'stdlib.json'} declares no aliases_digest"
|
||||
)
|
||||
if pin_path is not None:
|
||||
pin = stdlib_bundle.load_pin(pin_path)
|
||||
stdlib_bundle.verify_pin(record, pin)
|
||||
except stdlib_bundle.BundleError as error:
|
||||
raise SystemExit(f"pack-stdlib: error: {error}") from error
|
||||
return record
|
||||
|
||||
files = sorted(
|
||||
[p for p in STDLIB.rglob("*") if p.is_file() and p.name != "stdlib.json"]
|
||||
+ [STDLIB / "stdlib.json"],
|
||||
key=lambda p: p.relative_to(STDLIB).as_posix(),
|
||||
)
|
||||
DIST.mkdir(exist_ok=True)
|
||||
archive = DIST / f"marqdo-stdlib-{version}.tar.gz"
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--stdlib-dir", required=True)
|
||||
parser.add_argument("--out-dir", default=str(DIST))
|
||||
parser.add_argument("--bundle-pin", default=None)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
root = Path(args.stdlib_dir)
|
||||
record = verify_input(root, Path(args.bundle_pin) if args.bundle_pin else None)
|
||||
version = record["version"]
|
||||
files = [root / name for name in record["files"]]
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
archive = out_dir / f"marqdo-stdlib-{version}.tar.gz"
|
||||
with archive.open("wb") as raw:
|
||||
with gzip_open(raw) as gz:
|
||||
with tarfile.open(fileobj=gz, mode="w") as tar:
|
||||
for path in files:
|
||||
relative = path.relative_to(STDLIB).as_posix()
|
||||
relative = path.relative_to(root).as_posix()
|
||||
info = tarfile.TarInfo(name=relative)
|
||||
data = path.read_bytes()
|
||||
info.size = len(data)
|
||||
@@ -81,28 +86,20 @@ def main() -> int:
|
||||
descriptor = {
|
||||
"schema": "marqdo.stdlib-package",
|
||||
"schema_version": 1,
|
||||
"name": manifest["name"],
|
||||
"name": record["name"],
|
||||
"version": version,
|
||||
"tree_digest": f"sha256:{digest}",
|
||||
"aliases_digest": alias_digest,
|
||||
"tree_digest": record["tree_digest"],
|
||||
"aliases_digest": record["aliases_digest"],
|
||||
"archive": archive.name,
|
||||
"archive_sha256": f"sha256:{archive_sha}",
|
||||
"files": [p.relative_to(STDLIB).as_posix() for p in files],
|
||||
"files": record["files"],
|
||||
}
|
||||
descriptor_path = DIST / f"marqdo-stdlib-{version}.json"
|
||||
descriptor_path = out_dir / f"marqdo-stdlib-{version}.json"
|
||||
descriptor_path.write_text(json.dumps(descriptor, indent=2) + "\n")
|
||||
(DIST / f"{archive.name}.sha256").write_text(
|
||||
f"{archive_sha} {archive.name}\n"
|
||||
)
|
||||
(out_dir / f"{archive.name}.sha256").write_text(f"{archive_sha} {archive.name}\n")
|
||||
print(json.dumps(descriptor, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def gzip_open(raw):
|
||||
import gzip
|
||||
|
||||
return gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, filename="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -27,6 +27,11 @@ workload whose wire output did not match the committed expected digest.
|
||||
governor, CPU affinity and toolchain. For an approved-node comparison
|
||||
it also requires an approved, correctness-verified MEASURED baseline.
|
||||
Record competing load and investigate differences before sign-off.
|
||||
* One explicit Bundle: `--stdlib-dir` (default: the pinned Bundle) is verified
|
||||
against `tools/stdlib/bundle-pin.json`, and every workload receives it as
|
||||
`MARQDO_STDLIB_DIR`. The report records the Bundle name, version, tree/alias
|
||||
digests and source commit. A bad input or digest mismatch fails before any
|
||||
workload runs; there is no checkout fallback (ADR-0070).
|
||||
* Avoid TCG/QEMU for final performance numbers; use native or KVM with fixed
|
||||
CPU affinity (`--cpu-list`) and an administrator-approved governor.
|
||||
* The suggested investigation thresholds are p50 +15% and peak RSS +20%; they
|
||||
|
||||
+25
-2
@@ -38,6 +38,9 @@ EXPECTED = ROOT / "tools" / "perf" / "expected"
|
||||
SCHEMA = "marqdo.perf.v2"
|
||||
MIN_WARMUPS = 5
|
||||
MIN_SAMPLES = 20
|
||||
|
||||
sys.path.insert(0, str(ROOT / "tools" / "stdlib"))
|
||||
import bundle as stdlib_bundle # noqa: E402
|
||||
P50_REGRESSION = 0.15
|
||||
RSS_REGRESSION = 0.20
|
||||
|
||||
@@ -312,6 +315,7 @@ def run_workload(
|
||||
record: bool,
|
||||
timeout: float,
|
||||
cpu_list: str,
|
||||
stdlib_dir: Path,
|
||||
) -> dict:
|
||||
name = workload["name"]
|
||||
prefix = []
|
||||
@@ -325,8 +329,9 @@ def run_workload(
|
||||
measured_argv = prefix + [str(binary)] + (workload.get("measure_argv") or workload["argv"])
|
||||
env = dict(os.environ)
|
||||
env.pop("MARQDO_STDLIB_DIR", None)
|
||||
if not (binary.parent / "stdlib" / "stdlib.json").is_file():
|
||||
env["MARQDO_STDLIB_DIR"] = str(ROOT / "stdlib")
|
||||
# One explicit, pinned Bundle for every workload; no sibling or checkout
|
||||
# fallback (ADR-0070).
|
||||
env["MARQDO_STDLIB_DIR"] = str(stdlib_dir)
|
||||
env.setdefault("NO_COLOR", "1")
|
||||
expected_document = load_expected(name)
|
||||
expected = expected_document.get("wire_sha256") if expected_document else None
|
||||
@@ -514,6 +519,8 @@ def compare_baseline(report: dict, baseline: dict) -> list[dict]:
|
||||
def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--binary", default=str(ROOT / "target" / "release" / "marqdo"))
|
||||
parser.add_argument("--stdlib-dir", default=None)
|
||||
parser.add_argument("--bundle-pin", default=str(ROOT / "tools" / "stdlib" / "bundle-pin.json"))
|
||||
parser.add_argument("--no-build", action="store_true")
|
||||
parser.add_argument("--warmups", type=int, default=MIN_WARMUPS)
|
||||
parser.add_argument("--samples", type=int, default=MIN_SAMPLES)
|
||||
@@ -528,6 +535,13 @@ def main(argv: list[str]) -> int:
|
||||
parser.add_argument("--allow-smoke", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
stdlib_dir, stdlib_record, stdlib_pin = stdlib_bundle.resolve(
|
||||
args.stdlib_dir, Path(args.bundle_pin)
|
||||
)
|
||||
except stdlib_bundle.BundleError as error:
|
||||
raise SystemExit(f"perf: error: {error}") from error
|
||||
|
||||
if args.samples < 1 or args.warmups < 0:
|
||||
raise SystemExit("samples must be >= 1 and warmups >= 0")
|
||||
if (args.samples < MIN_SAMPLES or args.warmups < MIN_WARMUPS) and not args.allow_smoke:
|
||||
@@ -571,6 +585,7 @@ def main(argv: list[str]) -> int:
|
||||
args.record_expected,
|
||||
args.timeout,
|
||||
args.cpu_list,
|
||||
stdlib_dir,
|
||||
)
|
||||
results.append(result)
|
||||
print(
|
||||
@@ -589,6 +604,14 @@ def main(argv: list[str]) -> int:
|
||||
report = {
|
||||
"schema": SCHEMA,
|
||||
"source_sha": source_sha,
|
||||
"stdlib": {
|
||||
"name": stdlib_record["name"],
|
||||
"version": stdlib_record["version"],
|
||||
"tree_digest": stdlib_record["tree_digest"],
|
||||
"aliases_digest": stdlib_record["aliases_digest"],
|
||||
"source_commit": stdlib_pin["source"].get("commit"),
|
||||
"root": str(stdlib_dir),
|
||||
},
|
||||
"platform_id": args.platform_id,
|
||||
"environment_approved": bool(args.approved_node),
|
||||
"binary": {
|
||||
|
||||
@@ -51,4 +51,5 @@ docker run --rm --network none --user 65534:65534 \
|
||||
exit 1
|
||||
fi
|
||||
grep -E "stdlib|symbol\.unknown|打印" /tmp/missing-stdlib.log
|
||||
test "$(./marqdo call examples/factorial.mq.md 阶乘 --arg n=5)" = 120
|
||||
' sh "$version" "$source_sha"
|
||||
+68
-75
@@ -4,7 +4,13 @@
|
||||
The archive is deterministic (sorted entries, commit timestamp, uid/gid 0) and
|
||||
contains the CLI, the provider worker helper (same directory, same target), the
|
||||
licenses/changelog/compatibility matrix, the public specs, the developer docs,
|
||||
the runnable examples and the public protocol consumers.
|
||||
the runnable examples, the public protocol consumers and the stdlib Bundle that
|
||||
`--stdlib-dir` names.
|
||||
|
||||
The stdlib Bundle is one required, explicit build input (ADR-0070): a missing
|
||||
directory, missing manifest, tree/alias digest mismatch or pin mismatch fails
|
||||
before anything is staged. An optional `--bundle-pin` also records the pinned
|
||||
source commit in `RELEASE_INFO.json.stdlib.source`.
|
||||
|
||||
It refuses to package a dirty tree, a version that does not match the Cargo
|
||||
workspace, or a HEAD that differs from `--source-sha`, and it fails if the
|
||||
@@ -16,7 +22,9 @@ Usage (from the repository root, after
|
||||
|
||||
python3 tools/release/package.py \
|
||||
--source-sha "$(git rev-parse HEAD)" \
|
||||
--version 3.0.0-rc.4
|
||||
--version 3.0.0-rc.4 \
|
||||
--stdlib-dir stdlib \
|
||||
--bundle-pin tools/stdlib/bundle-pin.json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,7 +42,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BINARIES = ("marqdo", "marqdo-provider-worker")
|
||||
STDLIB = ROOT / "stdlib"
|
||||
PRODUCT_STDLIB_FILES = ("stdlib.json", "io.mq.md", "io/console.mq.md")
|
||||
EXAMPLES_WITH_BUILD = (
|
||||
"plugin-demo",
|
||||
"plugin-multi-export",
|
||||
@@ -42,6 +50,9 @@ EXAMPLES_WITH_BUILD = (
|
||||
"math-backend",
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(ROOT / "tools" / "stdlib"))
|
||||
import bundle as stdlib_bundle # noqa: E402
|
||||
|
||||
|
||||
def fail(message: str) -> "NoReturn":
|
||||
print(f"package: error: {message}", file=sys.stderr)
|
||||
@@ -64,81 +75,51 @@ def sha256_file(path: Path) -> str:
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def sha256_bytes(*chunks: bytes) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for chunk in chunks:
|
||||
digest.update(chunk)
|
||||
return "sha256:" + digest.hexdigest()
|
||||
def stdlib_tree_digest(root: Path) -> str:
|
||||
"""Canonical stdlib tree digest, byte-identical to the CLI loader.
|
||||
|
||||
|
||||
def stdlib_tree_digest(root: Path = STDLIB) -> str:
|
||||
"""Canonical stdlib tree digest, byte-identical to
|
||||
`marqdo_cli::stdlib::tree_digest`: sorted `*.mq.md` relative POSIX paths,
|
||||
`path + NUL + bytes + NUL`."""
|
||||
paths = sorted(
|
||||
(path.relative_to(root).as_posix(), path)
|
||||
for path in root.rglob("*.mq.md")
|
||||
if path.is_file()
|
||||
)
|
||||
return sha256_bytes(
|
||||
*(
|
||||
chunk
|
||||
for relative, path in paths
|
||||
for chunk in (relative.encode(), b"\0", path.read_bytes(), b"\0")
|
||||
)
|
||||
)
|
||||
The algorithm lives in `tools/stdlib/bundle.py` (ADR-0070); `root` is the
|
||||
explicit `--stdlib-dir` input, never an implicit checkout path.
|
||||
"""
|
||||
return stdlib_bundle.tree_digest(root)
|
||||
|
||||
|
||||
def stdlib_aliases_digest(manifest: dict) -> str:
|
||||
"""Canonical public-alias digest, byte-identical to the CLI loader."""
|
||||
chunks: list[bytes] = []
|
||||
aliases = sorted(
|
||||
manifest.get("public_aliases", []),
|
||||
key=lambda alias: (alias["target_module"], alias["target_function"]),
|
||||
)
|
||||
for alias in aliases:
|
||||
chunks.append(alias["target_module"].encode())
|
||||
chunks.append(b"\0")
|
||||
chunks.append(alias["target_function"].encode())
|
||||
chunks.append(b"\0")
|
||||
for name in sorted(alias["public_names"]):
|
||||
chunks.append(name.encode())
|
||||
chunks.append(b"\0")
|
||||
return sha256_bytes(*chunks)
|
||||
return stdlib_bundle.aliases_digest(manifest)
|
||||
|
||||
|
||||
def verify_stdlib() -> dict:
|
||||
"""Validate the shipped stdlib tree and return the RELEASE_INFO record."""
|
||||
manifest_path = STDLIB / "stdlib.json"
|
||||
if not manifest_path.is_file():
|
||||
fail(f"missing bundled stdlib manifest {manifest_path}")
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
tree = stdlib_tree_digest()
|
||||
aliases = stdlib_aliases_digest(manifest)
|
||||
if tree != manifest.get("digest"):
|
||||
fail(f"stdlib tree digest {tree} does not match stdlib.json digest {manifest.get('digest')}")
|
||||
if aliases != manifest.get("aliases_digest"):
|
||||
fail(
|
||||
f"stdlib alias digest {aliases} does not match stdlib.json "
|
||||
f"aliases_digest {manifest.get('aliases_digest')}"
|
||||
)
|
||||
required = ["stdlib.json", "io.mq.md", "io/console.mq.md"]
|
||||
files = sorted(
|
||||
path.relative_to(STDLIB).as_posix()
|
||||
for path in STDLIB.rglob("*")
|
||||
if path.is_file()
|
||||
)
|
||||
for name in required:
|
||||
if name not in files:
|
||||
fail(f"bundled stdlib is missing required file {name}")
|
||||
return {
|
||||
"name": manifest.get("name"),
|
||||
"version": manifest.get("version"),
|
||||
"tree_digest": tree,
|
||||
"aliases_digest": aliases,
|
||||
"file_count": len(files),
|
||||
"files": files,
|
||||
}
|
||||
def verify_stdlib(root: Path, pin_path: Path | None = None) -> dict:
|
||||
"""Validate the explicit Bundle root and return the RELEASE_INFO record."""
|
||||
root = Path(root)
|
||||
try:
|
||||
record = stdlib_bundle.verify(root)
|
||||
stdlib_bundle.require_files(record, PRODUCT_STDLIB_FILES)
|
||||
if record["aliases_digest"] is None:
|
||||
raise stdlib_bundle.BundleError(
|
||||
f"{root / 'stdlib.json'} declares no aliases_digest"
|
||||
)
|
||||
info = {
|
||||
"name": record["name"],
|
||||
"version": record["version"],
|
||||
"tree_digest": record["tree_digest"],
|
||||
"aliases_digest": record["aliases_digest"],
|
||||
"file_count": record["file_count"],
|
||||
"files": record["files"],
|
||||
}
|
||||
if pin_path is not None:
|
||||
pin = stdlib_bundle.load_pin(pin_path)
|
||||
stdlib_bundle.verify_pin(record, pin)
|
||||
source = pin["source"]
|
||||
info["source"] = {
|
||||
"kind": source.get("kind"),
|
||||
"repository": source.get("repository"),
|
||||
"commit": source.get("commit"),
|
||||
"path": source.get("path"),
|
||||
}
|
||||
return info
|
||||
except stdlib_bundle.BundleError as error:
|
||||
fail(str(error))
|
||||
|
||||
|
||||
def host_target() -> str:
|
||||
@@ -206,7 +187,14 @@ def copy_tree(source: Path, destination: Path) -> None:
|
||||
shutil.copytree(source, destination, dirs_exist_ok=True)
|
||||
|
||||
|
||||
def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
|
||||
def stage(
|
||||
stage_dir: Path,
|
||||
version: str,
|
||||
source_sha: str,
|
||||
target: str,
|
||||
stdlib_dir: Path,
|
||||
stdlib_info: dict,
|
||||
) -> dict:
|
||||
stage_dir.mkdir(parents=True)
|
||||
release_dir = ROOT / "target" / "release"
|
||||
for name in BINARIES:
|
||||
@@ -226,7 +214,7 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
|
||||
|
||||
# The bundled stdlib is a required runtime artifact, not a build-machine
|
||||
# side effect: copy the verified tree next to the binary (ADR/SPEC H-08).
|
||||
copy_tree(STDLIB, stage_dir / "stdlib")
|
||||
copy_tree(stdlib_dir, stage_dir / "stdlib")
|
||||
|
||||
# Examples without local build output, then the freshly built extension
|
||||
# artifacts so a clean install can run every example without a compiler.
|
||||
@@ -242,7 +230,6 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
|
||||
shutil.copy2(limitations, stage_dir / "KNOWN_LIMITATIONS.md")
|
||||
|
||||
commit_time = int(git("show", "-s", "--format=%ct", "HEAD"))
|
||||
stdlib_info = verify_stdlib()
|
||||
binaries = {
|
||||
name: {
|
||||
"sha256": sha256_file(stage_dir / name),
|
||||
@@ -326,6 +313,8 @@ def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--source-sha", required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--stdlib-dir", required=True)
|
||||
parser.add_argument("--bundle-pin", default=None)
|
||||
parser.add_argument("--target", default=None)
|
||||
parser.add_argument("--out-dir", default=str(ROOT / "dist"))
|
||||
parser.add_argument("--skip-example-build", action="store_true")
|
||||
@@ -335,6 +324,10 @@ def main(argv: list[str]) -> int:
|
||||
ch not in "0123456789abcdef" for ch in args.source_sha
|
||||
):
|
||||
fail("--source-sha must be a full lowercase 40-character commit SHA")
|
||||
stdlib_dir = Path(args.stdlib_dir)
|
||||
stdlib_info = verify_stdlib(
|
||||
stdlib_dir, Path(args.bundle_pin) if args.bundle_pin else None
|
||||
)
|
||||
check_clean(args.source_sha)
|
||||
version = workspace_version()
|
||||
if version != args.version:
|
||||
@@ -349,7 +342,7 @@ def main(argv: list[str]) -> int:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
stage_dir = out_dir / f"marqdo-{version}-{target}"
|
||||
shutil.rmtree(stage_dir, ignore_errors=True)
|
||||
staged = stage(stage_dir, version, args.source_sha, target)
|
||||
staged = stage(stage_dir, version, args.source_sha, target, stdlib_dir, stdlib_info)
|
||||
archive = out_dir / f"marqdo-{version}-{target}.tar.gz"
|
||||
archive.unlink(missing_ok=True)
|
||||
make_archive(stage_dir, archive, staged["commit_time"])
|
||||
|
||||
@@ -281,6 +281,16 @@ def main(argv: list[str]) -> int:
|
||||
if "stdlib" not in message and "打印" not in message and "symbol.unknown" not in message:
|
||||
fail(f"missing-stdlib failure is not explicit: {message!r}")
|
||||
print("smoke: bundled stdlib missing -> fail-closed OK")
|
||||
# A program that uses only the language must still run.
|
||||
language_only = runner.run(
|
||||
["call", "examples/factorial.mq.md", "阶乘", "--arg", "n=5"]
|
||||
).stdout.strip()
|
||||
if language_only != "120":
|
||||
fail(
|
||||
f"language-only call failed without the bundled stdlib: "
|
||||
f"{language_only!r}"
|
||||
)
|
||||
print("smoke: language-only program runs without the bundled stdlib")
|
||||
finally:
|
||||
hidden.rename(install / "stdlib")
|
||||
factor = runner.run(
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schema": "marqdo.stdlib-bundle-pin",
|
||||
"schema_version": 1,
|
||||
"name": "marqdo-stdlib",
|
||||
"version": "0.1.0",
|
||||
"source": {
|
||||
"kind": "in-repo",
|
||||
"repository": "cflmy/marqdo-cli",
|
||||
"commit": "2cbde54602c07f62a62f341400bc9cb4764a93f8",
|
||||
"path": "stdlib",
|
||||
"note": "Phase A (ADR-0070): the pinned Bundle is the checkout tree at this commit. Phase B replaces this record with the accepted ecosystem Bundle commit and digest; do not change it in the same commit as test fixtures."
|
||||
},
|
||||
"tree_digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
|
||||
"aliases_digest": "sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb"
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One resolver and verifier for a stdlib Bundle (ADR-0070).
|
||||
|
||||
Every source-side consumer that needs the official Bundle — packaging tools,
|
||||
product tests, the performance runner and release CI — resolves it through
|
||||
this module instead of concatenating a checkout path. The identity comes from
|
||||
`tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest,
|
||||
alias digest); an explicit input may change the location but must still match
|
||||
the pinned digests.
|
||||
|
||||
The digest algorithms are byte-identical to `marqdo_cli::stdlib` and to
|
||||
`tools/release/smoke.py` (which stays an independent verifier of the shipped
|
||||
archive). Nothing here is used by the running CLI.
|
||||
|
||||
Usage:
|
||||
|
||||
python3 tools/stdlib/bundle.py [--stdlib-dir PATH] [--pin PATH] [--print-path]
|
||||
|
||||
Exit status is 1 for an invalid Bundle and 2 for a bad command line.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PIN_PATH = ROOT / "tools" / "stdlib" / "bundle-pin.json"
|
||||
PIN_SCHEMA = "marqdo.stdlib-bundle-pin"
|
||||
PIN_SCHEMA_VERSION = 1
|
||||
REQUIRED_MANIFEST_FIELDS = ("name", "version", "digest")
|
||||
|
||||
|
||||
class BundleError(Exception):
|
||||
"""An input is not a verifiable stdlib Bundle."""
|
||||
|
||||
|
||||
def _sha256_bytes(*chunks: bytes) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for chunk in chunks:
|
||||
digest.update(chunk)
|
||||
return "sha256:" + digest.hexdigest()
|
||||
|
||||
|
||||
def _walk_files(root: Path) -> list[Path]:
|
||||
"""Every regular file under `root`, sorted, rejecting symlinks.
|
||||
|
||||
Deterministic packaging must not follow a link outside the Bundle root or
|
||||
archive a link whose target differs by platform.
|
||||
"""
|
||||
files: list[Path] = []
|
||||
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
||||
dirnames.sort()
|
||||
base = Path(dirpath)
|
||||
for name in dirnames:
|
||||
if (base / name).is_symlink():
|
||||
raise BundleError(
|
||||
f"stdlib Bundle contains a symbolic link directory: "
|
||||
f"{(base / name).relative_to(root).as_posix()}"
|
||||
)
|
||||
for name in sorted(filenames):
|
||||
path = base / name
|
||||
if path.is_symlink():
|
||||
raise BundleError(
|
||||
f"stdlib Bundle contains a symbolic link: "
|
||||
f"{path.relative_to(root).as_posix()}"
|
||||
)
|
||||
if path.is_file():
|
||||
files.append(path)
|
||||
files.sort(key=lambda path: path.relative_to(root).as_posix())
|
||||
return files
|
||||
|
||||
|
||||
def load_manifest(root: Path) -> dict:
|
||||
manifest_path = root / "stdlib.json"
|
||||
if not root.is_dir():
|
||||
raise BundleError(f"stdlib Bundle directory does not exist: {root}")
|
||||
if not manifest_path.is_file():
|
||||
raise BundleError(f"stdlib Bundle has no manifest: {manifest_path}")
|
||||
try:
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
|
||||
raise BundleError(f"cannot read valid JSON from {manifest_path}: {error}") from error
|
||||
if not isinstance(manifest, dict):
|
||||
raise BundleError(f"{manifest_path} must contain a JSON object")
|
||||
for field in REQUIRED_MANIFEST_FIELDS:
|
||||
value = manifest.get(field)
|
||||
if not isinstance(value, str) or not value:
|
||||
raise BundleError(f"{manifest_path} has no non-empty `{field}`")
|
||||
return manifest
|
||||
|
||||
|
||||
def tree_digest(root: Path) -> str:
|
||||
"""`relative POSIX path + NUL + bytes + NUL` over every `*.mq.md` file."""
|
||||
root = Path(root)
|
||||
chunks: list[bytes] = []
|
||||
for path in _walk_files(root):
|
||||
if not path.name.endswith(".mq.md"):
|
||||
continue
|
||||
chunks.append(path.relative_to(root).as_posix().encode())
|
||||
chunks.append(b"\0")
|
||||
chunks.append(path.read_bytes())
|
||||
chunks.append(b"\0")
|
||||
return _sha256_bytes(*chunks)
|
||||
|
||||
|
||||
def aliases_digest(manifest: dict) -> str:
|
||||
"""Canonical digest over `public_aliases`, byte-identical to the loader."""
|
||||
chunks: list[bytes] = []
|
||||
aliases = sorted(
|
||||
manifest.get("public_aliases", []),
|
||||
key=lambda alias: (alias["target_module"], alias["target_function"]),
|
||||
)
|
||||
for alias in aliases:
|
||||
chunks.append(alias["target_module"].encode())
|
||||
chunks.append(b"\0")
|
||||
chunks.append(alias["target_function"].encode())
|
||||
chunks.append(b"\0")
|
||||
for name in sorted(alias["public_names"]):
|
||||
chunks.append(name.encode())
|
||||
chunks.append(b"\0")
|
||||
return _sha256_bytes(*chunks)
|
||||
|
||||
|
||||
def _verify_aliases(manifest: dict, manifest_path: Path) -> list[dict]:
|
||||
raw = manifest.get("public_aliases", [])
|
||||
if not isinstance(raw, list):
|
||||
raise BundleError(f"{manifest_path} public_aliases must be an array")
|
||||
seen: set[str] = set()
|
||||
aliases: list[dict] = []
|
||||
for entry in raw:
|
||||
if not isinstance(entry, dict):
|
||||
raise BundleError(f"{manifest_path} public alias must be an object")
|
||||
names = entry.get("public_names")
|
||||
if not isinstance(names, list) or not names:
|
||||
raise BundleError(f"{manifest_path} public alias declares no names")
|
||||
for name in names:
|
||||
if not isinstance(name, str) or not name:
|
||||
raise BundleError(f"{manifest_path} public alias name must be a non-empty string")
|
||||
if name in seen:
|
||||
raise BundleError(f"{manifest_path} public alias name `{name}` is declared twice")
|
||||
seen.add(name)
|
||||
module = entry.get("target_module")
|
||||
if not isinstance(module, str) or not module:
|
||||
raise BundleError(f"{manifest_path} public alias has no target_module")
|
||||
relative = Path(module)
|
||||
if relative.is_absolute() or ".." in relative.parts:
|
||||
raise BundleError(
|
||||
f"{manifest_path} public alias target_module `{module}` must stay inside the Bundle"
|
||||
)
|
||||
function = entry.get("target_function")
|
||||
if not isinstance(function, str) or not function:
|
||||
raise BundleError(f"{manifest_path} public alias has no target_function")
|
||||
aliases.append(entry)
|
||||
aliases.sort(key=lambda alias: (alias["target_module"], alias["target_function"]))
|
||||
return aliases
|
||||
|
||||
|
||||
def verify(root: Path) -> dict:
|
||||
"""Validate one unpacked Bundle root and return its identity record."""
|
||||
root = Path(root)
|
||||
manifest = load_manifest(root)
|
||||
manifest_path = root / "stdlib.json"
|
||||
tree = tree_digest(root)
|
||||
declared_tree = manifest["digest"]
|
||||
if declared_tree != tree:
|
||||
raise BundleError(
|
||||
f"stdlib tree digest mismatch: stdlib.json declares {declared_tree}, "
|
||||
f"the files are {tree}"
|
||||
)
|
||||
aliases = _verify_aliases(manifest, manifest_path)
|
||||
declared_aliases = manifest.get("aliases_digest")
|
||||
actual_aliases = aliases_digest(manifest)
|
||||
if declared_aliases is None and aliases:
|
||||
raise BundleError(f"{manifest_path} declares public_aliases without aliases_digest")
|
||||
if declared_aliases is not None and declared_aliases != actual_aliases:
|
||||
raise BundleError(
|
||||
f"stdlib public-alias digest mismatch: stdlib.json declares {declared_aliases}, "
|
||||
f"the alias table is {actual_aliases}"
|
||||
)
|
||||
files = sorted(path.relative_to(root).as_posix() for path in _walk_files(root))
|
||||
modules = [name for name in files if name.endswith(".mq.md")]
|
||||
if not modules:
|
||||
raise BundleError(f"stdlib Bundle {root} contains no .mq.md module")
|
||||
return {
|
||||
"name": manifest["name"],
|
||||
"version": manifest["version"],
|
||||
"tree_digest": tree,
|
||||
"aliases_digest": actual_aliases if declared_aliases is not None else None,
|
||||
"file_count": len(files),
|
||||
"files": files,
|
||||
}
|
||||
|
||||
|
||||
def require_files(record: dict, required: tuple[str, ...]) -> None:
|
||||
missing = [name for name in required if name not in record["files"]]
|
||||
if missing:
|
||||
raise BundleError(
|
||||
"stdlib Bundle is missing required file(s): " + ", ".join(missing)
|
||||
)
|
||||
|
||||
|
||||
def load_pin(path: Path = PIN_PATH) -> dict:
|
||||
path = Path(path)
|
||||
try:
|
||||
pin = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
|
||||
raise BundleError(f"cannot read Bundle pin {path}: {error}") from error
|
||||
if not isinstance(pin, dict):
|
||||
raise BundleError(f"Bundle pin {path} must contain a JSON object")
|
||||
if pin.get("schema") != PIN_SCHEMA or pin.get("schema_version") != PIN_SCHEMA_VERSION:
|
||||
raise BundleError(
|
||||
f"Bundle pin {path} must be {PIN_SCHEMA} schema_version {PIN_SCHEMA_VERSION}"
|
||||
)
|
||||
source = pin.get("source")
|
||||
if not isinstance(source, dict) or not isinstance(source.get("path"), str):
|
||||
raise BundleError(f"Bundle pin {path} has no source.path")
|
||||
for field in ("name", "version", "tree_digest", "aliases_digest"):
|
||||
if not isinstance(pin.get(field), str) or not pin[field]:
|
||||
raise BundleError(f"Bundle pin {path} has no non-empty `{field}`")
|
||||
return pin
|
||||
|
||||
|
||||
def verify_pin(record: dict, pin: dict) -> None:
|
||||
"""Require a verified Bundle record to match the pinned identity."""
|
||||
for field in ("name", "version", "tree_digest", "aliases_digest"):
|
||||
if record.get(field) != pin.get(field):
|
||||
raise BundleError(
|
||||
f"stdlib Bundle does not match the pin: {field} is "
|
||||
f"{record.get(field)!r}, the pin records {pin.get(field)!r}"
|
||||
)
|
||||
|
||||
|
||||
def resolve(
|
||||
explicit: str | Path | None = None,
|
||||
pin_path: Path = PIN_PATH,
|
||||
*,
|
||||
require_pin: bool = True,
|
||||
) -> tuple[Path, dict, dict]:
|
||||
"""Resolve and verify the Bundle, returning `(root, record, pin)`.
|
||||
|
||||
`explicit` overrides the pinned location but never the pinned identity
|
||||
unless `require_pin` is false. A bad explicit input fails even when the
|
||||
default location is valid; there is no fallback.
|
||||
"""
|
||||
pin = load_pin(pin_path)
|
||||
if explicit is None:
|
||||
root = ROOT / pin["source"]["path"]
|
||||
else:
|
||||
root = Path(explicit)
|
||||
record = verify(root)
|
||||
if require_pin:
|
||||
verify_pin(record, pin)
|
||||
require_files(
|
||||
record,
|
||||
(
|
||||
"stdlib.json",
|
||||
"io.mq.md",
|
||||
"io/console.mq.md",
|
||||
),
|
||||
)
|
||||
return root.resolve(), record, pin
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Resolve and verify the pinned stdlib Bundle (ADR-0070)."
|
||||
)
|
||||
parser.add_argument("--stdlib-dir", default=None)
|
||||
parser.add_argument("--pin", default=str(PIN_PATH))
|
||||
parser.add_argument("--print-path", action="store_true")
|
||||
parser.add_argument("--dump-pin", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
root, record, pin = resolve(args.stdlib_dir, Path(args.pin))
|
||||
except BundleError as error:
|
||||
print(f"bundle: error: {error}", file=sys.stderr)
|
||||
return 1
|
||||
if args.print_path:
|
||||
print(root)
|
||||
return 0
|
||||
if args.dump_pin:
|
||||
print(json.dumps(pin, indent=2, sort_keys=True))
|
||||
return 0
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"root": str(root),
|
||||
"name": record["name"],
|
||||
"version": record["version"],
|
||||
"tree_digest": record["tree_digest"],
|
||||
"aliases_digest": record["aliases_digest"],
|
||||
"source_commit": pin["source"].get("commit"),
|
||||
"file_count": record["file_count"],
|
||||
},
|
||||
indent=2,
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
Reference in new issue
Block a user