Author SHA1 Message Date
cflmy f8b82d4143 merge: bring master (issue #13 boundary + SDK revert) into issue #11 Phase A
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
2026-11-26 23:00:32 +08:00
cflmy f836f05998 docs: align the issue #13 snapshot with the SDK split revert
ci/woodpecker/push/main Pipeline was successful
- mark the old 0.12 remaining-work line as superseded by 0.13;
- record Woodpecker #112 success for the revert code commit in the evidence.

Docs-only change; no code/lock/protocol bytes move.
2026-11-26 21:28:24 +08:00
cflmy 98d256f5a2 refactor: keep the plugin SDK in the CLI workspace (revert split)
ci/woodpecker/push/main Pipeline was successful
The pre-stable line prioritizes atomic ABI/header/spec/SDK/loader changes over
a premature repository boundary. ADR-0073 supersedes ADR-0072:

- restore crates/marqdo-plugin-sdk as a contract-only CLI workspace crate
  (marqdo-plugin-abi + serde; no loader/host/worker dependency);
- restore tests/sdk-plugin and tools/ci/check_plugin_sdk.py, including the real
  CLI invocation and tampered-digest negative case;
- restore workspace/lock/architecture/dependency/docs/CI references; the SDK is
  a reviewed workspace member again and must not become a remote repo, mirror
  or submodule in this stage;
- ADR-0072 and the old issue #15 evidence are marked superseded; ADR-0073 and
  the split-revert evidence record the decision and the deleted remote repo;
- logical ADR-0071 boundaries are unchanged.

Workspace: 636 passed / 0 failed / 2 ignored; fmt, clippy, docs, architecture,
dependency, SDK gate and engine differential all PASS.

Refs #13, #15
2026-11-26 21:21:41 +08:00
cflmy 89acb709c6 Merge PR #16: independent plugin SDK repository
ci/woodpecker/push/main Pipeline was successful
Implements ADR-0072 / issue #15. SDK moved to cflmy/marqdo-plugin-sdk pinned to the CLI contract revision; CLI no longer carries or depends on it. CI push #108 and PR #110 green.
2026-11-26 20:13:11 +08:00
cflmy 3ab4aaa861 refactor: move the plugin SDK to its independent repository (issue #15)
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Implements ADR-0072 and the SDK physical migration tracked by issue #15:

- remove crates/marqdo-plugin-sdk, tests/sdk-plugin and the CLI-side
  check_plugin_sdk.py; the public cflmy/marqdo-plugin-sdk repository now owns
  the SDK workspace, lock, fixture, docs, AGENTS rules and CI definition.
- SDK consumes marqdo-plugin-abi at the exact CLI contract rev
  2585915e16906dac75f8571bed02e7f6f868c6bc; no path/submodule/copied contract.
- CLI does not depend on the SDK and must not re-add it as a workspace member
  or copy; dependency/architecture gates enforce this.
- docs: ADR-0072, CURRENT responsibility map/dependency graph, ADR-0071
  amendment, indexes, README, spec/plugin-abi, CI and developer entries.
- evidence: clean-clone SDK build/tests and real frozen 3.0.0-rc.4 CLI
  invocation (Int 42; tampered digest rejected).

CLI workspace: 631 passed / 0 failed / 0 ignored; fmt/clippy/docs/architecture/
dependency gates green.

Refs #15, #13
2026-11-26 19:48:24 +08:00
cflmy c769eafc60 docs: list the Phase A commits in the evidence record
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Add the smoke commit and the CI gate follow-up so the evidence names the
reviewed implementation sequence instead of a relative commit.
2026-11-26 15:59:07 +08:00
cflmy 2acaaefe77 ci: fold the independent build into the linux evidence gate
tools/ci/release_evidence.py accepts only its declared gate names; the
extra independent_build gate would have failed the release-evidence job.
The job still depends on independent-build and marks linux FAIL when it
does not pass.
2026-11-26 15:56:20 +08:00
cflmy 88ce91a9e1 docs: record the issue #11 Phase A state and evidence
Update STATUS, the architecture overview, README and tests/README with
the explicit Bundle input, pinned test/perf lanes and the independent
build. Add the Phase A evidence record: bundle identity, failure paths,
deterministic pack/package digests, independent build, archive smoke,
cold install and the 634-passed workspace gate. Phase B remains
explicitly unclaimed.
2026-11-26 15:52:04 +08:00
cflmy 0e1efc713e smoke: keep language-only execution after removing the Bundle
Moving the shipped stdlib aside must fail the print program with an
explicit diagnostic and still run a language-only program. The archive
smoke and the cold-install container now both call the factorial
example after the move, and the archive contract test pins the new
message.
2026-11-26 15:51:39 +08:00
cflmy ab6b6b1a23 ci: add the independent-build lane and pin the perf Bundle
Add tools/ci/independent_build.py: export HEAD without stdlib/, build
both shipped binaries with --locked, run a language-only check/call, and
require a stdlib-dependent run to fail closed with no sibling stdlib.
Add tests/independent/language-only.mq.md and run the lane as its own
GitHub job and Woodpecker step.

Perf runner resolves the pinned Bundle (--stdlib-dir/--bundle-pin),
exports it to every workload and records it in the report; GitHub and
Woodpecker lanes verify the pin and pass the product tests an explicit
Bundle. docs/ci.md and performance docs describe the lanes.
2026-11-26 15:25:40 +08:00
cflmy 3a68260cf2 tests: resolve one pinned Bundle and separate the loader lane
Add crates/cli/tests/support/stdlib.rs as the product/conformance test
resolver: explicit MARQDO_TEST_STDLIB_BUNDLE or the pinned path, always
verified against bundle-pin.json (name/version/commit/digests), with a
bad explicit override failing closed. Route stdlib_product,
stdlib_bundle, http, table, alias routing, p2_closure,
conformance_semantics and architecture_boundaries through it.

Loader unit tests now build small synthetic Bundles; discovery is split
into discover_with so the bad-override-no-fallback rule is testable.
2026-11-26 15:15:59 +08:00
cflmy 422b9de6d7 release: take the stdlib Bundle as one explicit, pinned input
package.py now requires --stdlib-dir and accepts --bundle-pin; it
verifies the manifest, required files, tree/alias digests and the pin
before staging, copies exactly that Bundle next to the binary, and
records stdlib.source{kind,repository,commit,path} in RELEASE_INFO.
Digest logic moves to tools/stdlib/bundle.py. GitHub/Woodpecker
release steps and docs/releasing.md pass the pinned input.
2026-11-26 15:07:29 +08:00
cflmy 1b9d9c4c26 stdlib: add one pinned Bundle resolver and explicit pack input
Add tools/stdlib/bundle.py + bundle-pin.json as the single source-side
Bundle identity (name, version, source commit, tree/alias digests) and
require tools/pack-stdlib.py --stdlib-dir instead of reading the
checkout implicitly. Missing input, missing manifest, digest/alias
mismatch, pin mismatch and symlinks fail closed; two packs are
byte-identical. Tests: tools/ci/test_stdlib_bundle_tools.py.
2026-11-26 15:00:26 +08:00
cflmy b9c72e1d2a docs: inventory stdlib source coupling and record the Phase A boundary
Record ADR-0070 (one explicit stdlib Bundle build input) and the
issue #11 Phase A inventory of every direct checkout-stdlib reference.
Baseline 4bbefc9; bundle source 2cbde54; no runtime contract change.
2026-11-26 14:54:11 +08:00
46 changed files with 2520 additions and 291 deletions

No files matched your search

+21 -4
View File
@@ -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
@@ -47,7 +49,10 @@ jobs:
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: |
@@ -99,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
@@ -227,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
@@ -245,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:
@@ -258,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() {
@@ -268,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" \
+4
View File
@@ -42,3 +42,7 @@ __pycache__/
/tests/embedding/target/
/tests/sdk-plugin/target/
/.tmp/
# Accidental curl/test capture files
/out
/log.txt
+12 -2
View File
@@ -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
@@ -52,12 +53,19 @@ steps:
- 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:
@@ -75,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
+5 -2
View File
@@ -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'
+1 -1
View File
@@ -35,7 +35,7 @@ correctness and release evidence before expanding the surface.
10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates.
11. RFC-LANG-0002 is implemented by the frontend, `marqdo-expression`, IR lowering, runtime and the bundled stdlib. Keep `spec/`, implementation, fixtures, stdlib digest and docs in lockstep; there is no legacy mapper or per-file syntax switch to fall back to. Do not make a release claim beyond the evidence recorded in `docs/STATUS.md`.
12. The language engine depends on the neutral `marqdo-host-contract` only; it must never link `marqdo-host`, the sandbox, foreign kernels, the plugin loader/worker, package or CLI in normal/build dependencies. `marqdo-host-contract` depends on `Value`/`Span` only. The native host implements the contract and must not depend back on the runtime/frontend/IR. The plugin ABI crate is a contract (no `dlopen`/worker/manifest execution); the SDK consumes the contract only. CLI is the one assembly point. This is enforced by `tools/ci/check_dependency_boundaries.py`, `tools/ci/check_engine_boundary.py`, `tools/ci/check_plugin_sdk.py` and `crates/cli/tests/architecture_boundaries.rs`; see ADR-0071.
13. Do not create empty candidate repositories (for example `marqdo-engine`/`marqdo-host`/`marqdo-cli-*`) to "solve" architecture. A repository split requires the issue #13 §9.2 evidence and a separate accepted ADR; "keep in workspace" is a valid recorded decision. Do not add a second Host trait, Value encoding, wire/RPC engine protocol or compatibility re-export path.
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
+15
View File
@@ -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
+61 -44
View File
@@ -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);
}
Self::discover_from_exe_dir(
std::env::current_exe()
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)),
)
.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(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}");
+13 -3
View File
@@ -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"]
+5 -2
View File
@@ -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()
+7 -3
View File
@@ -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!(
+4 -10
View File
@@ -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();
+4 -10
View File
@@ -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 {
+6 -12
View File
@@ -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!(
+5 -11
View File
@@ -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 {
+6 -12
View File
@@ -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!(
+356
View File
@@ -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
}
-1
View File
@@ -12,4 +12,3 @@ authors.workspace = true
marqdo-plugin-abi = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+82 -8
View File
@@ -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,10 +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 Plugin SDK remains in the CLI workspace — split reverted (unreleased candidate)
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 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)
@@ -406,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
@@ -733,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
@@ -754,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.
+108
View File
@@ -0,0 +1,108 @@
# ADR-0072 — Independent `marqdo-plugin-sdk` repository
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)
after the contract decoupling of issue #13.
## Context
Issue #13 / ADR-0071 separated the public plugin contract from its execution
side:
- `marqdo-plugin-abi` (CLI repository) now contains only the C ABI v1 layout,
the wire envelope and protocol errors;
- `dlopen`, manifest/artifact file handling, worker management and invocation
dispatch live in `marqdo-host::plugin`;
- `marqdo-plugin-sdk` consumed only the contract and was verified by a real
fixture loaded through the CLI.
The SDK is a leaf with a different consumer group (third-party plugin authors),
a different change cadence and an independent release need. Keeping it in the
CLI workspace made the architecture map imply that the CLI product owns SDK
publication and forced every SDK change through the CLI build. Issue #15
required either fixing the distribution input or recording a blocking ticket.
The CLI repository is public, so a fixed Cargo git `rev` is a fetchable
contract input; there is no need for a submodule, a vendored contract copy or a
second wire implementation.
This is a **deliberate, narrow repository split**, not a mechanical projection
of every crate: engine and native host remain in the CLI workspace (ADR-0071
reopening conditions unchanged), and no empty candidate repository is created.
## Decision
### Topology
| Item | Decision |
|---|---|
| SDK repository | Public `cflmy/marqdo-plugin-sdk` (`main`), own Cargo workspace and lock |
| Contract input | `marqdo-plugin-abi` from `https://git.cflmy.cn/cflmy/marqdo-cli.git` at exact `rev = 2585915e16906dac75f8571bed02e7f6f868c6bc` (the merge commit that landed ADR-0071) |
| CLI dependency on SDK | **None**. CLI normal/build/test lanes do not fetch or build the SDK |
| CLI workspace | `crates/marqdo-plugin-sdk` removed; the SDK is not a workspace member |
| Submodule/gitlink | **Not used** for this split; the SDK leaf must not create a CLI↔SDK identity cycle |
| Acceptance fixture | `tests/fixture` in the SDK repository only; real invocation uses a **frozen released CLI binary** via `tools/check_with_frozen_cli.py` |
| Contract authority | Unchanged: CLI owns the C header, Rust layout, Value Wire and error encodings; the SDK never defines a second contract |
| Publication | SDK releases are versioned independently against a contract generation; bumping the pinned CLI `rev` is a reviewed change |
### Rules
- The SDK repository must resolve and build from a clean clone without the CLI
checkout; only its fixed git dependency may reach the CLI repository.
- It must not depend on `libloading`, a native host, worker execution, sandbox
or CLI code.
- The SDK's fixture is a third-party plugin built with only the public SDK. It
is verified against a frozen CLI archive (same ABI 1.0 contract), not against a
locally rebuilt CLI.
- The CLI repository must not reintroduce the SDK as a workspace member, a
copied source tree or a compatibility path; `tools/ci/check_dependency_boundaries.py`
and `architecture_boundaries.rs` fail if it does.
- The CLI's public contract is authoritative; the SDK repository README and
AGENTS rules point back to `include/marqdo_plugin_abi_v1.h`,
`spec/plugin-abi.md` and the pinned commit.
- The existing security statement remains: a C ABI is not a sandbox, and native
loading requires explicit trust; the SDK grants no capability.
## Verification (candidate)
- SDK repository commit `b31187a` on `main`:
- clean-clone `cargo build --locked` and `cargo test --locked` pass;
- the fixture builds with only the SDK;
- `tools/check_with_frozen_cli.py --marqdo-bin <released marqdo 3.0.0-rc.4>`
returns `Int 42` and rejects a tampered artifact digest.
- CLI candidate removes the SDK crate, fixture and CLI-side gate; workspace
tests, architecture boundaries, docs consistency and dependency gates pass;
the SDK no longer appears in the workspace or lock file.
- Full evidence: `docs/evidence/2026-11-26-issue-15-sdk-independent-repository.md`.
## Rejected alternatives
- **Keep the SDK in the CLI workspace** while calling the contract "decoupled":
leaves two release cadences and ownership in one repo; issue #15 cannot close.
- **Git submodule/gitlink into the CLI repo**: CLI does not consume the SDK, so
a submodule would create an unnecessary recursive identity and checkout
failure mode.
- **Relative path dependency `../cli`**: not an independent build; forbidden by
issue #13 §6.2.
- **Copy `marqdo-plugin-abi`/Value Wire into the SDK repo**: would create a
second contract and wire encoder authority.
- **Publish the contract to a registry first**: no registry/release channel is
approved here; the public git `rev` is the available precise input. A future
published artifact can replace the git `rev` without changing authority.
## Consequences and rollback
- The architecture map now shows one CLI contract producer and one independent
SDK consumer; CLI CI no longer carries SDK-only checks, and SDK CI owns them.
- The SDK remains pinned to a CLI merge commit. Changing the contract or
advancing the pin is a deliberate cross-repository change with its own
evidence; a contract change must land in the CLI first, then the SDK pin is
bumped.
- Rollback is a complete known-good combination: keep the CLI commit and the SDK
pin that were verified together; do not restore a copied SDK or an old ABI.
- External SDK consumers can fetch the public CLI contract today. If a
registry-published contract or a different visibility policy is later chosen,
that is a new ADR, not an implicit change.
@@ -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.
+8
View File
@@ -70,6 +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) — **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.
+17 -8
View File
@@ -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
@@ -185,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
@@ -280,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 |
@@ -326,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` | Contract decoupled; physical move to an independent repository is a follow-up after the §6.3 external build and pinned-artifact mechanism | A clean-directory build against a fixed contract revision without the CLI checkout passes (S07/S08) |
| `marqdo-plugin-sdk` | **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
@@ -358,7 +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-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.
+2
View File
@@ -83,6 +83,8 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and
| Resource operations and core kinds | [0062](../adr/0062-resource-operation-ownership-and-core-kinds.md) | Accepted and implemented; architecture gate pins the reviewed lists |
| Foreign F-A transition | [0063](../adr/0063-foreign-kernel-transition-fa.md) | Accepted: retained F-A primitive; F-B deferred |
| Stable core inventory and external gate | [0064](../adr/0064-stable-core-extension-boundary.md) | Accepted and wired into Linux CI |
| 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 |
+18 -3
View File
@@ -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,11 +29,13 @@ 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)
@@ -39,12 +43,18 @@ test (rust:1.100-bookworm, clippy/rustfmt, Node.js 22, MinGW, both binaries):
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)
```
@@ -97,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
@@ -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.
@@ -0,0 +1,84 @@
# 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)
Parent: issue #13 / [ADR-0071](../adr/0071-engine-host-contract-boundary.md)
## Topology and identity
| Object | Exact identity |
|---|---|
| SDK repository | `cflmy/marqdo-plugin-sdk` (public), `main` at `b31187a` |
| CLI contract input | `marqdo-plugin-abi` from `https://git.cflmy.cn/cflmy/marqdo-cli.git` `rev = 2585915e16906dac75f8571bed02e7f6f868c6bc` (merge of PR #14) |
| CLI candidate | `architecture/sdk-independent-repository`; PR/CI SHA recorded by the PR |
| Frozen CLI acceptance binary | `marqdo` 3.0.0-rc.4 Linux x86_64 release archive, SHA-256 from the release `.sha256` asset |
| ABI | Plugin ABI 1.0 / Value Wire 1 / package + provider formats unchanged |
The SDK repository is its own Cargo workspace and lock. The CLI does not depend
on it, and the SDK does not depend on the CLI checkout, the native host, a
loader/worker, a sandbox or the CLI product.
## SDK repository verification (clean clone, independent of CLI checkout)
Commands run in a fresh `git clone https://git.cflmy.cn/cflmy/marqdo-plugin-sdk.git`
outside this repository:
| Gate | Command | Result |
|---|---|---|
| Locked build | `cargo build --locked` | PASS (contract fetched from the pinned public CLI git `rev`) |
| SDK tests | `cargo test --locked` | PASS (4 unit tests + 1 doc-test, 2 ignored doc examples) |
| Third-party fixture | `cargo build --locked --manifest-path tests/fixture/Cargo.toml` | PASS (built only from the SDK) |
| Frozen CLI invocation (S04/S07) | `python3 tools/check_with_frozen_cli.py --marqdo-bin frozen/marqdo` | PASS — real CLI returns `Int 42` |
| Tampered artifact (S05/S06) | same script, `sha256` replaced | PASS — rejected with artifact/sha256 diagnostic |
The frozen binary was the released 3.0.0-rc.4 archive, not a locally rebuilt CLI;
the plugin ABI is unchanged across the #13 decoupling, which is exactly the
cross-repository compatibility being tested.
SDK repository CI (`.woodpecker/main.yml`) repeats the workspace checks, the
fixture build and the frozen-CLI integration after downloading that released
archive. Enabling the Woodpecker project/webhook for the new repository is a
repository-administration step outside this change; the pipeline definition is
checked in and the same commands were executed manually above.
## CLI repository verification (this change)
| Gate | Command | Result |
|---|---|---|
| Workspace resolution | `cargo check --workspace --locked` | PASS; `marqdo-plugin-sdk` no longer appears in `Cargo.lock` |
| Formatting | `cargo fmt --all -- --check` | PASS |
| Clippy | `cargo clippy --workspace --all-targets --locked -- -D warnings` | PASS |
| Rust tests | `cargo test --workspace --locked --no-fail-fast` | PASS — 631 passed / 0 failed / 0 ignored (the removed SDK 4 unit + 1 doc test now run in the SDK repository; the two previously ignored SDK doc examples moved with them) |
| Architecture boundaries | `cargo test -p marqdo-cli --test architecture_boundaries --locked` | PASS — SDK absence/moved-repository assertion |
| Docs consistency | `cargo test -p marqdo-cli --test docs_consistency --locked` | PASS |
| Dependency direction | `python3 tools/ci/check_dependency_boundaries.py` | PASS — SDK no longer a workspace member; negative case added |
| Tools unit tests | `python3 -m unittest discover -s tools/ci -p "test_*.py"` | PASS |
| Engine differential | `python3 tools/ci/check_engine_boundary.py` | PASS (unchanged) |
Removed from the CLI workspace/repository in the same integration:
- `crates/marqdo-plugin-sdk/` (moved to the independent repository);
- `tests/sdk-plugin/` (fixture moved to `tests/fixture` in the SDK repository);
- `tools/ci/check_plugin_sdk.py` (its superset lives in the SDK repository and
uses a frozen CLI binary);
- workspace/lock entry, architecture/layer docs, CI lane entries and current
developer references.
## Not verified / follow-ups
- **Woodpecker activation** for the new public repository is administrative; the
pipeline definition is committed, but no remote pipeline run is claimed here.
- **Registry publication** of the contract crate is not introduced; the public
CLI git `rev` is the precise, fetchable input. A future published artifact
would be a new decision and would not change contract authority.
- Engine/Native Host remain in the CLI workspace under ADR-0071; this split does
not reopen that decision.
- No second ABI, wire encoder, loader or host copy exists in the SDK repository;
no compatibility/submodule path was added to the CLI repository.
@@ -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
View File
@@ -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
View File
@@ -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
View File
Whitespace-only changes.
-1
View File
@@ -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
+18
View File
@@ -57,6 +57,24 @@ Rust harnesses (all in `crates/cli/tests/`):
| `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`:
+12
View File
@@ -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 值`
+217
View File
@@ -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:]))
+54 -8
View File
@@ -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)
+316
View File
@@ -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
View File
@@ -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")
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(),
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"
)
DIST.mkdir(exist_ok=True)
archive = DIST / f"marqdo-stdlib-{version}.tar.gz"
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
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:]))
+5
View File
@@ -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
View File
@@ -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": {
+1
View File
@@ -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"
+66 -73
View File
@@ -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')}"
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"
)
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,
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"])
+10
View File
@@ -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(
+15
View File
@@ -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"
}
+308
View File
@@ -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:]))