Author SHA1 Message Date
cflmy e2162add22 docs: record the issue #13 CI evidence and domain service ledger
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Docs-only delta on top of the verified code SHA 9b4f0a0:
- Woodpecker PR pipeline #101 (test/minimum-rust/build all green, including
  archive smoke and frozen external conformance).
- domain-service ledger stays DEFERRED under ADR-0062 (no new domain op).
- STATUS/evidence update; no code, lock or protocol change.
2026-11-26 18:49:48 +08:00
cflmy 9b4f0a0822 refactor: extract neutral host contract and decouple plugin ABI (issue #13)
ci/woodpecker/pr/main Pipeline was successful
ci/woodpecker/push/main Pipeline was canceled
Implements the core M0-M3 boundary work from issue #13 / ADR-0071 without
changing language semantics or any public protocol:

- add marqdo-host-contract owning Host/HostOp/ExecutionContext/ResourceRead
  and the runtime observation facts; the engine depends on it only.
- marqdo-runtime no longer links marqdo-host; the native host implements the
  contract and has no reverse edge to runtime/frontend/IR.
- reduce marqdo-plugin-abi to the public C ABI/wire/error contract; move
  manifest/artifact/loader/worker execution into marqdo-host::plugin so the
  SDK carries no loader/worker/host dependency.
- add a real independent consumer (tests/embedding, own workspace+lock) that
  runs Markdown -> frontend -> IR -> runtime with bounded budgets and explicit
  effect refusal, plus differential CLI comparison.
- add an SDK-only third-party plugin fixture and real CLI invocation gate.
- replace the frozen-crate architecture test with a reviewed responsibility
  graph enforced from Cargo metadata, with negative unit cases.
- consolidate current docs/entry: ADR-0071, CURRENT responsibility map,
  developers/architecture indexes, historical banners, STATUS and evidence.
- record keep-in-workspace for Engine/Native Host; no empty candidate repo.

Evidence: docs/evidence/2026-11-26-issue-13-engine-host-boundary.md
Refs #13
2026-11-26 18:37:02 +08:00
117 changed files with 3784 additions and 2654 deletions

No files matched your search

+10 -21
View File
@@ -19,8 +19,6 @@ jobs:
components: rustfmt, clippy components: rustfmt, clippy
- name: Rust cache - name: Rust cache
uses: Swatinem/rust-cache@v2 uses: Swatinem/rust-cache@v2
- name: Verify the pinned stdlib Bundle
run: python3 tools/stdlib/bundle.py
- name: Formatting - name: Formatting
run: cargo fmt --all -- --check run: cargo fmt --all -- --check
- name: Clippy - name: Clippy
@@ -41,12 +39,15 @@ jobs:
run: cargo test -p marqdo-cli --test docs_consistency run: cargo test -p marqdo-cli --test docs_consistency
- name: Architecture boundaries - name: Architecture boundaries
run: cargo test -p marqdo-cli --test architecture_boundaries run: cargo test -p marqdo-cli --test architecture_boundaries
- name: Dependency-direction gate (Engine / Host Contract / Native Host)
run: python3 tools/ci/check_dependency_boundaries.py
- name: Engine independence and CLI differential execution
run: python3 tools/ci/check_engine_boundary.py
- name: Plugin SDK real consumption
run: python3 tools/ci/check_plugin_sdk.py
- name: CI evidence tool tests - name: CI evidence tool tests
run: python3 -m unittest discover -s tools/ci -p "test_*.py" run: python3 -m unittest discover -s tools/ci -p "test_*.py"
- name: Whole stdlib product tests (explicit pinned Bundle) - name: Whole stdlib product tests
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 run: cargo test -p marqdo-cli --test stdlib_product
- name: Validate public JSON schemas - name: Validate public JSON schemas
run: | run: |
@@ -98,16 +99,6 @@ jobs:
--trust-native-plugin \ --trust-native-plugin \
--allow-plugin demo.solver --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: schema:
name: schema instance validation + consumers name: schema instance validation + consumers
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -236,8 +227,7 @@ jobs:
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
version="$(cargo metadata --no-deps --format-version 1 --offline \ 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 -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 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 tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$GITHUB_SHA" dist/frozen-extension-evidence.json
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
@@ -255,7 +245,7 @@ jobs:
release-evidence: release-evidence:
name: release evidence manifest name: release evidence manifest
needs: [test, schema, cross-platform, frozen-extensions, independent-build] needs: [test, schema, cross-platform, frozen-extensions]
if: always() if: always()
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -268,7 +258,6 @@ jobs:
LINUX_RESULT: ${{ needs.test.result }} LINUX_RESULT: ${{ needs.test.result }}
SCHEMA_RESULT: ${{ needs.schema.result }} SCHEMA_RESULT: ${{ needs.schema.result }}
EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }} EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }}
INDEPENDENT_RESULT: ${{ needs.independent-build.result }}
run: | run: |
set -euo pipefail set -euo pipefail
state() { state() {
@@ -279,7 +268,7 @@ jobs:
esac esac
} }
linux="$(state "$LINUX_RESULT")" linux="$(state "$LINUX_RESULT")"
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ] || [ "$(state "$INDEPENDENT_RESULT")" != "PASS" ]; then if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ]; then
linux="FAIL" linux="FAIL"
fi fi
python3 tools/ci/release_evidence.py --profile rc --target-sha "$TARGET_SHA" \ python3 tools/ci/release_evidence.py --profile rc --target-sha "$TARGET_SHA" \
+5
View File
@@ -37,3 +37,8 @@ __pycache__/
*.pyc *.pyc
.perf-out-* .perf-out-*
.perf-err-* .perf-err-*
# Independent consumer/fixture build outputs and the local scratch dir
/tests/embedding/target/
/tests/sdk-plugin/target/
/.tmp/
+6 -12
View File
@@ -15,6 +15,7 @@ steps:
- apt-get update - apt-get update
- apt-get install -y --no-install-recommends ca-certificates python3 python3-jsonschema - apt-get install -y --no-install-recommends ca-certificates python3 python3-jsonschema
- cargo build --locked -p marqdo-cli -p marqdo-provider-worker - cargo build --locked -p marqdo-cli -p marqdo-provider-worker
- python3 tools/ci/check_dependency_boundaries.py
- | - |
set -eux set -eux
./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json ./target/debug/marqdo check tests/consumers/fixtures/observation/basic.mq.md --emit /tmp/analysis.json
@@ -39,7 +40,6 @@ steps:
- apt-get install -y --no-install-recommends curl ca-certificates python3 python3-jsonschema build-essential gcc-mingw-w64-x86-64 - 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 - - curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
- apt-get install -y --no-install-recommends nodejs - apt-get install -y --no-install-recommends nodejs
- python3 tools/stdlib/bundle.py
- cargo fmt --all -- --check - cargo fmt --all -- --check
- cargo clippy --workspace --all-targets -- -D warnings - cargo clippy --workspace --all-targets -- -D warnings
# Provider CLI tests resolve a real provider worker next to the CLI # Provider CLI tests resolve a real provider worker next to the CLI
@@ -48,20 +48,16 @@ steps:
- cargo test --workspace --locked - cargo test --workspace --locked
- cargo test -p marqdo-cli --test docs_consistency - cargo test -p marqdo-cli --test docs_consistency
- cargo test -p marqdo-cli --test architecture_boundaries - cargo test -p marqdo-cli --test architecture_boundaries
- python3 tools/ci/check_dependency_boundaries.py
- python3 tools/ci/check_engine_boundary.py
- python3 tools/ci/check_plugin_sdk.py
- python3 -m unittest discover -s tools/ci -p "test_*.py" - python3 -m unittest discover -s tools/ci -p "test_*.py"
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/stdlib" MARQDO_TEST_BUNDLE_PIN="$PWD/tools/stdlib/bundle-pin.json" cargo test -p marqdo-cli --test stdlib_product - cargo test -p marqdo-cli --test stdlib_product
# Windows compile gate: runtime lanes are native on GitHub; this catches # Windows compile gate: runtime lanes are native on GitHub; this catches
# cfg/compile regressions on the Linux CI without a Windows runner. # cfg/compile regressions on the Linux CI without a Windows runner.
- rustup target add x86_64-pc-windows-gnu - rustup target add x86_64-pc-windows-gnu
- cargo check --workspace --all-targets --target 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: minimum-rust:
image: rust:1.89-bookworm image: rust:1.89-bookworm
commands: commands:
@@ -79,15 +75,13 @@ steps:
# only supported transport and resolution is a sibling-of-CLI lookup. # only supported transport and resolution is a sibling-of-CLI lookup.
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker - cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- test -x target/release/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 # Build the deterministic archive from this exact commit and cold-install
# smoke-test it; the package script refuses a dirty tree or wrong SHA. # smoke-test it; the package script refuses a dirty tree or wrong SHA.
- | - |
set -eu set -eu
version="$(cargo metadata --no-deps --format-version 1 --offline \ 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 -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 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 tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$CI_COMMIT_SHA" dist/frozen-extension-evidence.json
cat dist/frozen-extension-evidence.json cat dist/frozen-extension-evidence.json
+2 -5
View File
@@ -10,7 +10,6 @@ steps:
commands: commands:
- apt-get update - apt-get update
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates git openssl build-essential - 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 - cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- | - |
set -eu set -eu
@@ -23,8 +22,7 @@ steps:
(cd "$perf_dir/beta" && cargo build --release --locked -p marqdo-cli) (cd "$perf_dir/beta" && cargo build --release --locked -p marqdo-cli)
version="$(target/release/marqdo --version | cut -d ' ' -f 2)" version="$(target/release/marqdo --version | cut -d ' ' -f 2)"
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" \ python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" --out-dir "$perf_dir"
--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" archive="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu.tar.gz"
(cd "$perf_dir" && sha256sum -c "$(basename "$archive.sha256")") (cd "$perf_dir" && sha256sum -c "$(basename "$archive.sha256")")
tar -xzf "$archive" -C "$perf_dir" tar -xzf "$archive" -C "$perf_dir"
@@ -39,8 +37,7 @@ steps:
(cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \ (cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \
--warmups 5 --samples 20 --platform-id woodpecker-agent-1 \ --warmups 5 --samples 20 --platform-id woodpecker-agent-1 \
--cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null) --cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null)
python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" \ python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" --warmups 5 --samples 20 \
--stdlib-dir "$candidate/stdlib" --warmups 5 --samples 20 \
--platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \ --platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \
--baseline "$perf_dir/beta.json" --out perf.json > /dev/null --baseline "$perf_dir/beta.json" --out perf.json > /dev/null
python3 - <<'PY' python3 - <<'PY'
+15 -12
View File
@@ -1,19 +1,20 @@
# Marqdo CLI — Agent / Contributor Operating Rules # Marqdo CLI — Agent / Contributor Operating Rules
**Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/DEVELOPMENT_BLUEPRINT.md` (architecture baseline; its language-mapping sections are historical), `docs/STATUS.md` (what is actually implemented, including the landed RFC-LANG-0002 migration), the relevant `spec/` files, `docs/adr/` for decisions at their date, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation or legacy Marqdo syntax is authoritative. **Start here:** read `docs/architecture/RFC-LANG-0002-unified-semantics.md` — it is the single current language authority — and its normative summary `spec/mapping.md` + `spec/expression.ebnf`. Then read `docs/architecture/CURRENT.md` (the single current architecture overview, including the Engine / Host Contract / Native Host map), [ADR-0071](docs/adr/0071-engine-host-contract-boundary.md) (boundary rules and keep-in-workspace decision), `docs/STATUS.md` (what is actually implemented), the relevant `spec/` files, `docs/adr/` for decisions at their date, the developer entry point `docs/developers/README.md`, `docs/contributor-guide.md`, and `tests/README.md` plus the conformance fixtures. Do not assume any current implementation, legacy Marqdo syntax, historical planning document or old architecture gate is authoritative.
For next-phase work, the authoritative release policy for the current For next-phase work, the authoritative release policy for the current
3.0 prerelease line is `docs/MARQDO_3_0_PRERELEASE_PLAN.md` (beta gates, 3.0 prerelease line is `docs/MARQDO_3_0_PRERELEASE_PLAN.md` (beta gates,
REL-01..REL-05, version axes, LTS conditions). `docs/STABLE_RELEASE_IMPLEMENTATION.md` REL-01..REL-05, version axes, LTS conditions). The current architecture and
(stable gates G-A/G-B/G-C) is historical roadmap input for the later stable dependency direction are owned by `docs/architecture/CURRENT.md` and
release; it does not override the 3.0 prerelease plan. Also read `docs/CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md` [ADR-0071](docs/adr/0071-engine-host-contract-boundary.md). The historical plans
(historical stabilization spec, baseline `0adebe4`), `docs/NEXT_PHASE_IMPLEMENTATION.md` (`DEVELOPMENT_BLUEPRINT.md`, `NEXT_PHASE_IMPLEMENTATION.md`,
(M0.6 plan), `docs/EXTENSIBILITY_AUDIT.md` (E01–E16), `COMPATIBILITY.md` and `STABLE_RELEASE_IMPLEMENTATION.md`, `CORE_STABILIZATION_AND_ECOSYSTEM_GATE.md`,
`docs/security-gate.md`. Older plans are historical input; the 3.0 prerelease plan is authoritative for `EXTENSIBILITY_AUDIT.md`, `NEXT_RELEASE_CI_CONVERGENCE.md`) are archived design
current release decisions, and the stable-release spec applies only when the history: read them with that status, do not use them as current requirements, and
project moves from beta to stable. do not create a second running-status page. `COMPATIBILITY.md` and
None describes implemented behavior; re-check against HEAD and tests. `strict` `docs/security-gate.md` remain current inputs. None describes implemented
remains fail-closed until G-C passes. behavior; re-check against HEAD and tests. `strict` remains fail-closed until
G-C passes.
The stable-release spec also governs scope: do not add a top-level CLI command, The stable-release spec also governs scope: do not add a top-level CLI command,
Knowledge/Proof/View special-casing, a second interpreter or a new package Knowledge/Proof/View special-casing, a second interpreter or a new package
@@ -33,6 +34,8 @@ correctness and release evidence before expanding the surface.
9. Side effects go through `CapabilityHost`; do not invent host bypasses for tests, plugins, math or foreign kernels. `check` and `inspect` cannot execute untrusted project code. 9. Side effects go through `CapabilityHost`; do not invent host bypasses for tests, plugins, math or foreign kernels. `check` and `inspect` cannot execute untrusted project code.
10. Language semantics, package format, ABI, authorization defaults or public CLI behavior changes require an ADR + tests + spec updates. 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`. 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.
## Pre-stable protocol changes ## Pre-stable protocol changes
@@ -51,7 +54,7 @@ closing a protocol replacement issue.
2. Update the normative spec **in place** first; there is never a second active syntax spec. 2. Update the normative spec **in place** first; there is never a second active syntax spec.
3. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST, execution IR and diagnostics. 3. Add a small `.mq.md` positive/negative conformance fixture and define the expected Markdown AST, execution IR and diagnostics.
4. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, expression parser, runtime and host separated. 4. Implement only the smallest module that satisfies this fixture. Keep Markdown parser, semantic mapper, expression parser, runtime and host separated.
5. Run formatting, clippy, unit tests, golden tests and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`). 5. Run formatting, clippy, unit tests, golden tests, the architecture/dependency gates and relevant security/ABI compatibility tests (`cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `cargo test -p marqdo-cli`, `python3 tools/ci/check_dependency_boundaries.py`, `python3 tools/ci/check_engine_boundary.py`, `python3 tools/ci/check_plugin_sdk.py`).
6. Write the tradeoff and state of completion in the PR. Never say a feature is finished because a design example looks executable. Update `spec/` and `docs/STATUS.md` when behavior or status changes; the docs describe what the code does and flag divergences explicitly. 6. Write the tradeoff and state of completion in the PR. Never say a feature is finished because a design example looks executable. Update `spec/` and `docs/STATUS.md` when behavior or status changes; the docs describe what the code does and flag divergences explicitly.
## Unresolved design topics ## Unresolved design topics
Generated
+15 -6
View File
@@ -420,6 +420,7 @@ dependencies = [
"marqdo-foreign", "marqdo-foreign",
"marqdo-frontend", "marqdo-frontend",
"marqdo-host", "marqdo-host",
"marqdo-host-contract",
"marqdo-ir", "marqdo-ir",
"marqdo-markdown", "marqdo-markdown",
"marqdo-package", "marqdo-package",
@@ -485,8 +486,10 @@ dependencies = [
"flate2", "flate2",
"getrandom 0.4.3", "getrandom 0.4.3",
"glob", "glob",
"hex",
"libloading", "libloading",
"marqdo-foreign", "marqdo-foreign",
"marqdo-host-contract",
"marqdo-plugin-abi", "marqdo-plugin-abi",
"marqdo-sandbox", "marqdo-sandbox",
"marqdo-span", "marqdo-span",
@@ -499,10 +502,20 @@ dependencies = [
"rustls-pemfile", "rustls-pemfile",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml",
"sha2",
"tempfile", "tempfile",
"thiserror", "thiserror",
] ]
[[package]]
name = "marqdo-host-contract"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-span",
"marqdo-value",
]
[[package]] [[package]]
name = "marqdo-ir" name = "marqdo-ir"
version = "3.0.0-rc.4" version = "3.0.0-rc.4"
@@ -542,15 +555,9 @@ dependencies = [
name = "marqdo-plugin-abi" name = "marqdo-plugin-abi"
version = "3.0.0-rc.4" version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"hex",
"libloading",
"marqdo-span",
"marqdo-value", "marqdo-value",
"marqdo-worker-ipc",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml",
"sha2",
"thiserror", "thiserror",
] ]
@@ -569,6 +576,7 @@ version = "3.0.0-rc.4"
dependencies = [ dependencies = [
"libloading", "libloading",
"marqdo-host", "marqdo-host",
"marqdo-host-contract",
"marqdo-sandbox", "marqdo-sandbox",
"marqdo-value", "marqdo-value",
"marqdo-worker-ipc", "marqdo-worker-ipc",
@@ -583,6 +591,7 @@ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-frontend", "marqdo-frontend",
"marqdo-host", "marqdo-host",
"marqdo-host-contract",
"marqdo-ir", "marqdo-ir",
"marqdo-sandbox", "marqdo-sandbox",
"marqdo-span", "marqdo-span",
+2
View File
@@ -13,6 +13,7 @@ members = [
"crates/marqdo-worker-ipc", "crates/marqdo-worker-ipc",
"crates/marqdo-plugin-sdk", "crates/marqdo-plugin-sdk",
"crates/marqdo-host", "crates/marqdo-host",
"crates/marqdo-host-contract",
"crates/marqdo-runtime", "crates/marqdo-runtime",
"crates/marqdo-package", "crates/marqdo-package",
"crates/marqdo-sandbox", "crates/marqdo-sandbox",
@@ -38,6 +39,7 @@ marqdo-foreign = { path = "crates/marqdo-foreign" }
marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" } marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" }
marqdo-worker-ipc = { path = "crates/marqdo-worker-ipc" } marqdo-worker-ipc = { path = "crates/marqdo-worker-ipc" }
marqdo-host = { path = "crates/marqdo-host" } marqdo-host = { path = "crates/marqdo-host" }
marqdo-host-contract = { path = "crates/marqdo-host-contract" }
marqdo-runtime = { path = "crates/marqdo-runtime" } marqdo-runtime = { path = "crates/marqdo-runtime" }
marqdo-package = { path = "crates/marqdo-package" } marqdo-package = { path = "crates/marqdo-package" }
marqdo-sandbox = { path = "crates/marqdo-sandbox" } marqdo-sandbox = { path = "crates/marqdo-sandbox" }
+9 -22
View File
@@ -49,8 +49,9 @@ release policy.
CI: the source of truth is the Gitea remote CI: the source of truth is the Gitea remote
[git.cflmy.cn/cflmy/marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) with [git.cflmy.cn/cflmy/marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) with
Woodpecker at [ci.cflmy.cn](https://ci.cflmy.cn); [`.woodpecker/main.yml`](.woodpecker/main.yml) Woodpecker at [ci.cflmy.cn](https://ci.cflmy.cn); [`.woodpecker/main.yml`](.woodpecker/main.yml)
runs fmt, clippy, workspace tests with `--locked`, the Windows cross-target runs fmt, clippy, workspace tests with `--locked`, the dependency-direction and
compile gate and a release build of both binaries. The strict OS-isolation lane engine-independence gates, the plugin SDK consumption gate, the Windows
cross-target compile gate and a release build of both binaries. The strict OS-isolation lane
requires the disposable VM described in [docs/ci.md](docs/ci.md); a GitHub requires the disposable VM described in [docs/ci.md](docs/ci.md); a GitHub
mirror is not used as the authoritative lane for this beta. mirror is not used as the authoritative lane for this beta.
@@ -63,21 +64,6 @@ cargo build -p marqdo-cli
# binary: target/debug/marqdo (or $CARGO_TARGET_DIR/debug/marqdo) # 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 ## Quickstart
```bash ```bash
@@ -309,17 +295,18 @@ crates/marqdo-ir module/unit/function/statement IR, builtin table
crates/marqdo-frontend heading scopes, mapping, inference, static calls crates/marqdo-frontend heading scopes, mapping, inference, static calls
crates/marqdo-foreign Python/Node one-shot kernel supervisor crates/marqdo-foreign Python/Node one-shot kernel supervisor
crates/marqdo-sandbox mode parsing + platform isolation detection crates/marqdo-sandbox mode parsing + platform isolation detection
crates/marqdo-plugin-abi C ABI v1 mirrors, manifest, artifacts, loader crates/marqdo-host-contract neutral Host trait, HostOp, context and runtime facts
crates/marqdo-plugin-sdk Rust plugin SDK and entry macro crates/marqdo-plugin-abi public C ABI v1 contract: layout, wire envelope, errors
crates/marqdo-host CapabilityHost, budgets, FS, foreign/plugin adapters, core resource kinds crates/marqdo-plugin-sdk Rust plugin SDK and entry macro (contract-only)
crates/marqdo-runtime tree-walk interpreter crates/marqdo-host Native Host: capability, resources, OS, plugin loader/worker
crates/marqdo-runtime tree-walk interpreter (depends only on the neutral contract)
crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery
crates/cli CLI composition root (binary `marqdo`) crates/cli CLI composition root (binary `marqdo`)
include/ frozen plugin C ABI header include/ frozen plugin C ABI header
spec/ normative language/format/ABI specs spec/ normative language/format/ABI specs
docs/ blueprint, ADRs, status, contributor guide docs/ blueprint, ADRs, status, contributor guide
examples/ runnable documents + multi-module + plugin demo examples/ runnable documents + multi-module + plugin demo
tests/ conformance/negative corpus (see tests/README.md) tests/ conformance/negative corpus, embedding consumer and SDK fixture
``` ```
## Documentation index ## Documentation index
+1
View File
@@ -18,6 +18,7 @@ marqdo-frontend = { workspace = true }
marqdo-foreign = { workspace = true } marqdo-foreign = { workspace = true }
marqdo-plugin-abi = { workspace = true } marqdo-plugin-abi = { workspace = true }
marqdo-host = { workspace = true } marqdo-host = { workspace = true }
marqdo-host-contract = { workspace = true }
marqdo-runtime = { workspace = true } marqdo-runtime = { workspace = true }
marqdo-package = { workspace = true } marqdo-package = { workspace = true }
marqdo-sandbox = { workspace = true } marqdo-sandbox = { workspace = true }
+4 -3
View File
@@ -3,7 +3,8 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use marqdo_host::{Host, StdHost}; use marqdo_host::StdHost;
use marqdo_host_contract::Host;
use marqdo_runtime::{run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value}; use marqdo_runtime::{run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictOutcome}; use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictOutcome};
use marqdo_span::Span; use marqdo_span::Span;
@@ -270,12 +271,12 @@ fn load_plugin_into_host(
.parent() .parent()
.map(|parent| parent.to_path_buf()) .map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from(".")); .unwrap_or_else(|| PathBuf::from("."));
let manifest = marqdo_plugin_abi::PluginManifest::load(&manifest_path) let manifest = marqdo_host::plugin::PluginManifest::load(&manifest_path)
.map_err(|error| format!("{}: {}", error.code, error.message))?; .map_err(|error| format!("{}: {}", error.code, error.message))?;
manifest manifest
.validate() .validate()
.map_err(|error| format!("{}: {}", error.code, error.message))?; .map_err(|error| format!("{}: {}", error.code, error.message))?;
if manifest.plugin.kind == marqdo_plugin_abi::PluginKind::Native && !trusted { if manifest.plugin.kind == marqdo_host::plugin::PluginKind::Native && !trusted {
return Err(format!( return Err(format!(
"loading `{}` in-process requires --trust-native-plugin; use `kind: worker` for crash isolation", "loading `{}` in-process requires --trust-native-plugin; use `kind: worker` for crash isolation",
manifest.plugin.name manifest.plugin.name
+3 -3
View File
@@ -274,7 +274,7 @@ pub fn execute(
&& static_plugins && static_plugins
.plugins .plugins
.iter() .iter()
.any(|plugin| plugin.kind == marqdo_plugin_abi::PluginKind::Native) .any(|plugin| plugin.kind == marqdo_host::plugin::PluginKind::Native)
{ {
return fail( return fail(
stream, stream,
@@ -558,9 +558,9 @@ mod tests {
base_dir: PathBuf::from("/fixtures/demo"), base_dir: PathBuf::from("/fixtures/demo"),
package: "demo.ext".into(), package: "demo.ext".into(),
version: "0.1.0".into(), version: "0.1.0".into(),
kind: marqdo_plugin_abi::PluginKind::Worker, kind: marqdo_host::plugin::PluginKind::Worker,
manifest_sha256: format!("sha256:{}", "b".repeat(64)), manifest_sha256: format!("sha256:{}", "b".repeat(64)),
artifact_target: marqdo_plugin_abi::HostTarget::current() artifact_target: marqdo_host::plugin::HostTarget::current()
.triple() .triple()
.to_string(), .to_string(),
artifact_sha256: "a".repeat(64), artifact_sha256: "a".repeat(64),
+2 -2
View File
@@ -44,7 +44,7 @@ pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
.parent() .parent()
.map(|parent| parent.to_path_buf()) .map(|parent| parent.to_path_buf())
.unwrap_or_else(|| PathBuf::from(".")); .unwrap_or_else(|| PathBuf::from("."));
let manifest = match marqdo_plugin_abi::PluginManifest::load(&manifest_path) { let manifest = match marqdo_host::plugin::PluginManifest::load(&manifest_path) {
Ok(manifest) => manifest, Ok(manifest) => manifest,
Err(error) => { Err(error) => {
report_plugin_error(&error, json); report_plugin_error(&error, json);
@@ -55,7 +55,7 @@ pub fn plugin_inspect(target: &Path, json: bool) -> i32 {
report_plugin_error(&error, json); report_plugin_error(&error, json);
return 1; return 1;
} }
let host_target = marqdo_plugin_abi::HostTarget::current(); let host_target = marqdo_host::plugin::HostTarget::current();
let artifact = match manifest.verify_artifact(&base_dir, &host_target) { let artifact = match manifest.verify_artifact(&base_dir, &host_target) {
Ok((path, artifact)) => { Ok((path, artifact)) => {
let abi = match manifest.abi_requirement() { let abi = match manifest.abi_requirement() {
+1 -1
View File
@@ -10,9 +10,9 @@
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf}; use std::path::{Component, Path, PathBuf};
use marqdo_host::plugin::{HostTarget, PluginKind, PluginManifest};
use marqdo_ir::callable::{CallableDescriptor, CallableId, CallableOrigin, CallableSignature}; use marqdo_ir::callable::{CallableDescriptor, CallableId, CallableOrigin, CallableSignature};
use marqdo_ir::SignatureKind; use marqdo_ir::SignatureKind;
use marqdo_plugin_abi::{HostTarget, PluginKind, PluginManifest};
use marqdo_span::Span; use marqdo_span::Span;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
+4 -4
View File
@@ -81,12 +81,12 @@ fn plugin_identity(extension: &ResolvedExtension) -> Result<LockedExtension, Pre
), ),
) )
})?; })?;
let manifest = marqdo_plugin_abi::PluginManifest::load(&extension.path) let manifest = marqdo_host::plugin::PluginManifest::load(&extension.path)
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?; .map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
manifest manifest
.validate() .validate()
.map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?; .map_err(|error| PrepareError::option(error.code.clone(), error.message.clone()))?;
let host = marqdo_plugin_abi::HostTarget::current(); let host = marqdo_host::plugin::HostTarget::current();
let artifact = manifest let artifact = manifest
.resolve_artifact(&host) .resolve_artifact(&host)
.map_err(|error| PrepareError::option("ext.no_matching_artifact", error.message))?; .map_err(|error| PrepareError::option("ext.no_matching_artifact", error.message))?;
@@ -161,7 +161,7 @@ fn provider_identity(extension: &ResolvedExtension) -> Result<LockedExtension, P
format!("`{}` has no version", extension.path.display()), format!("`{}` has no version", extension.path.display()),
) )
})?; })?;
let target = marqdo_plugin_abi::HostTarget::current() let target = marqdo_host::plugin::HostTarget::current()
.triple() .triple()
.to_string(); .to_string();
let artifacts = manifest let artifacts = manifest
@@ -293,7 +293,7 @@ fn kernel_identity(extension: &ResolvedExtension) -> Result<LockedExtension, Pre
version: format!("wire:{wire_version}"), version: format!("wire:{wire_version}"),
manifest_digest: hex(&Sha256::digest(&manifest_bytes)), manifest_digest: hex(&Sha256::digest(&manifest_bytes)),
artifact_digest: digest.to_ascii_lowercase(), artifact_digest: digest.to_ascii_lowercase(),
selected_target: marqdo_plugin_abi::HostTarget::current() selected_target: marqdo_host::plugin::HostTarget::current()
.triple() .triple()
.to_string(), .to_string(),
source: extension.from.clone(), source: extension.from.clone(),
+1 -1
View File
@@ -500,7 +500,7 @@ fn dispatch() -> i32 {
}, },
Command::External(args) => tool::dispatch(&args), Command::External(args) => tool::dispatch(&args),
Command::PluginWorker(args) => { Command::PluginWorker(args) => {
marqdo_plugin_abi::worker::serve(&args.manifest, &args.base_dir) marqdo_host::plugin::worker::serve(&args.manifest, &args.base_dir)
} }
} }
} }
+3 -3
View File
@@ -8,10 +8,10 @@ use std::rc::Rc;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use marqdo_host::{ use marqdo_host::{
FrameId, ObservationConfig, ObservationError, ObservationEvent, ObservationSink, ObservationConfig, ObservationError, ObservationEvent, ObservationSink, ValueState,
ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES,
DEFAULT_MAX_VALUE_BYTES,
}; };
use marqdo_host_contract::{FrameId, ParameterSource};
use marqdo_value::Value; use marqdo_value::Value;
use serde_json::{json, Value as Json}; use serde_json::{json, Value as Json};
+2 -2
View File
@@ -16,8 +16,8 @@
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use marqdo_host::plugin::{HostTarget, TargetTriple};
use marqdo_host::StdHost; use marqdo_host::StdHost;
use marqdo_plugin_abi::{HostTarget, TargetTriple};
use serde::Deserialize; use serde::Deserialize;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
@@ -577,7 +577,7 @@ fn is_lowercase_sha256(value: &str) -> bool {
} }
fn is_known_capability(name: &str) -> bool { fn is_known_capability(name: &str) -> bool {
marqdo_plugin_abi::KNOWN_CAPABILITIES.contains(&name) marqdo_host::plugin::KNOWN_CAPABILITIES.contains(&name)
} }
/// A dotted vendor capability proposal (validation only, never a grant). /// A dotted vendor capability proposal (validation only, never a grant).
+44 -61
View File
@@ -51,24 +51,14 @@ impl StdlibBundle {
/// machine path: the release archive must ship a verified `stdlib/` next to /// machine path: the release archive must ship a verified `stdlib/` next to
/// the binary (RFC-EXT-0003 H-08, ADR). /// the binary (RFC-EXT-0003 H-08, ADR).
pub fn discover() -> Result<Option<Self>, String> { pub fn discover() -> Result<Option<Self>, String> {
let override_dir = std::env::var_os(STDLIB_DIR_ENV).map(PathBuf::from); if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) {
let exe_dir = std::env::current_exe() return Self::load(PathBuf::from(dir)).map(Some);
}
Self::discover_from_exe_dir(
std::env::current_exe()
.ok() .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 /// Discover from the directory that holds the executable, without the explicit
@@ -464,41 +454,21 @@ pub fn aliases_digest(aliases: &[PublicAlias]) -> String {
mod tests { mod tests {
use super::*; use super::*;
/// A small synthetic Bundle so loader unit tests never depend on the fn dev_bundle() -> PathBuf {
/// product tree (ADR-0070 test-lane separation). PathBuf::from(env!("CARGO_MANIFEST_DIR"))
fn write_synthetic_bundle(root: &Path) { .join("..")
for (relative, body) in [ .join("..")
("io.mq.md", "## @knowledge test\n"), .join("stdlib")
("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] #[test]
fn synthetic_bundle_verifies_and_resolves() { fn dev_bundle_verifies_and_resolves() {
let dir = tempfile::tempdir().unwrap(); let bundle = StdlibBundle::load(dev_bundle()).unwrap();
write_synthetic_bundle(dir.path()); assert!(bundle.digest.starts_with("sha256:"));
let bundle = StdlibBundle::load(dir.path()).unwrap();
assert_eq!(bundle.version(), "0.0.0-test");
let io = bundle.resolve("io").unwrap(); let io = bundle.resolve("io").unwrap();
assert_eq!(io.relative_path, "io.mq.md"); assert_eq!(io.relative_path, "io.mq.md");
assert!(io.package.instance_id.starts_with("std:test-stdlib@")); assert!(io.package.instance_id.starts_with("std:marqdo-stdlib@"));
assert!(bundle.resolve("../escape").is_err()); assert!(bundle.resolve("../escape").is_err());
assert!(bundle.resolve("/absolute").is_err());
} }
#[test] #[test]
@@ -506,31 +476,44 @@ mod tests {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let bundle = dir.path().join("stdlib"); let bundle = dir.path().join("stdlib");
std::fs::create_dir_all(&bundle).unwrap(); std::fs::create_dir_all(&bundle).unwrap();
write_synthetic_bundle(&bundle); 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();
}
}
let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf())) let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf()))
.unwrap() .unwrap()
.expect("sibling stdlib"); .expect("sibling stdlib");
assert_eq!(found.root(), bundle.canonicalize().unwrap()); assert_eq!(found.root, bundle.canonicalize().unwrap());
} }
#[test] fn copy_dir(source: &std::path::Path, target: &std::path::Path) {
fn bad_override_fails_closed_even_with_a_valid_sibling() { std::fs::create_dir_all(target).unwrap();
let dir = tempfile::tempdir().unwrap(); for entry in std::fs::read_dir(source).unwrap() {
let sibling = dir.path().join("stdlib"); let entry = entry.unwrap();
std::fs::create_dir_all(&sibling).unwrap(); let destination = target.join(entry.file_name());
write_synthetic_bundle(&sibling); if entry.path().is_dir() {
let error = StdlibBundle::discover_with( copy_dir(&entry.path(), &destination);
Some(dir.path().join("missing")), } else {
Some(dir.path().to_path_buf()), std::fs::copy(entry.path(), destination).unwrap();
) }
.unwrap_err(); }
assert!(error.contains("cannot open stdlib directory"), "{error}");
} }
#[test] #[test]
fn digest_tamper_is_rejected() { fn digest_tamper_is_rejected() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
write_synthetic_bundle(dir.path()); 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();
}
}
std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap(); std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap();
let error = StdlibBundle::load(dir.path()).unwrap_err(); let error = StdlibBundle::load(dir.path()).unwrap_err();
assert!(error.contains("digest mismatch"), "{error}"); assert!(error.contains("digest mismatch"), "{error}");
+228 -66
View File
@@ -1,13 +1,12 @@
//! Architecture boundary gate (review RFC-CM P0/P1). //! Architecture boundary gate (review RFC-CM P0/P1).
//! //!
//! These checks pin the documented layering: the runtime depends on the host //! These checks pin the documented layering: the engine depends on the neutral
//! platform layer, the bundled stdlib stays in this repository, `std:` import //! Host contract (never the native host), the plugin ABI contract carries no
//! targets resolve only inside the bundle, and the host keeps the documented //! loader/worker execution side, the bundled stdlib stays in this repository,
//! stdio/file/TCP resource endpoints. They are source and digest checks, not an //! `std:` import targets resolve only inside the bundle, and the host keeps the
//! OS-sandbox proof. //! documented stdio/file/TCP resource endpoints. They are source and digest
//! checks, not an OS-sandbox proof; `tools/ci/check_dependency_boundaries.py`
#[path = "support/stdlib.rs"] //! adds the Cargo-metadata graph gate.
pub mod stdlib_support;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -26,79 +25,120 @@ fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display())) std::fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display()))
} }
const WORKSPACE_CRATES: &[&str] = &[ /// Issue #13 / ADR-0071: the reviewed responsibility allowlist is the crate
"marqdo-span", /// table in the single current architecture overview, not a frozen count. A new
"marqdo-value", /// crate must be added there (and to the dependency gate's reviewed map) in the
"marqdo-expression", /// same change.
"marqdo-markdown",
"marqdo-ir",
"marqdo-frontend",
"marqdo-foreign",
"marqdo-plugin-abi",
"marqdo-provider-worker",
"marqdo-worker-ipc",
"marqdo-plugin-sdk",
"marqdo-host",
"marqdo-runtime",
"marqdo-package",
"marqdo-sandbox",
"cli",
];
#[test] #[test]
fn workspace_crates_match_the_documented_layers() { fn workspace_crates_are_documented_responsibilities() {
let manifest = read(&repo_root().join("Cargo.toml")); let root = repo_root();
let manifest = read(&root.join("Cargo.toml"));
let members = manifest let members = manifest
.split("members = [") .split("members = [")
.nth(1) .nth(1)
.and_then(|rest| rest.split(']').next()) .and_then(|rest| rest.split(']').next())
.expect("workspace members"); .expect("workspace members");
let names: Vec<&str> = members let names: Vec<String> = members
.split(',') .split(',')
.map(|item| item.trim().trim_matches('"')) .map(|item| item.trim().trim_matches('"'))
.filter(|item| !item.is_empty()) .filter(|item| !item.is_empty())
.map(|member| {
let directory = member
.strip_prefix("crates/")
.expect("workspace members are crates/<name>");
let manifest = read(&root.join(member).join("Cargo.toml"));
manifest
.lines()
.find_map(|line| line.strip_prefix("name = "))
.map(|name| name.trim().trim_matches('"').to_string())
.unwrap_or_else(|| directory.to_string())
})
.collect(); .collect();
let expected: Vec<String> = WORKSPACE_CRATES let current = read(&root.join("docs/architecture/CURRENT.md"));
.iter() let responsibilities = current
.map(|name| format!("crates/{name}")) .split("## Workspace crate responsibility map")
.collect(); .nth(1)
assert_eq!( .expect("CURRENT.md must own the reviewed crate responsibility map")
names, .split("\n## ")
expected.iter().map(String::as_str).collect::<Vec<_>>(), .next()
"workspace members drifted; update docs/architecture/CURRENT.md with the layer" .unwrap_or("");
); for name in &names {
assert!( assert!(
!names.contains(&"crates/marqdo-stdlib"), responsibilities.contains(&format!("`{name}`")),
"the stdlib must stay in this repository (ADR-0039), not become a crate" "workspace crate `{name}` has no documented responsibility in CURRENT.md"
);
}
for name in [
"marqdo-host-contract",
"marqdo-host",
"marqdo-plugin-abi",
"marqdo-cli",
] {
assert!(
names.iter().any(|crate_name| crate_name == name),
"required layer crate `{name}` is missing from the workspace"
);
}
assert!(
!names.iter().any(|name| name == "marqdo-stdlib"),
"the stdlib is a Bundle input, not a workspace crate (ADR-0039/ADR-0070)"
); );
} }
#[test] #[test]
fn runtime_depends_on_the_host_platform_layer_without_a_cycle() { fn engine_depends_on_the_neutral_host_contract_only() {
let runtime = read(&repo_root().join("crates/marqdo-runtime/Cargo.toml")); let root = repo_root();
let runtime = read(&root.join("crates/marqdo-runtime/Cargo.toml"));
let runtime_dependencies = runtime
.split("[dependencies]")
.nth(1)
.expect("runtime dependencies")
.split("[dev-dependencies]")
.next()
.expect("runtime normal dependencies");
assert!( assert!(
runtime runtime_dependencies
.lines()
.any(|line| line.trim() == "marqdo-host-contract = { workspace = true }"),
"runtime must depend on the neutral marqdo-host-contract crate"
);
assert!(
!runtime_dependencies
.lines() .lines()
.any(|line| line.trim() == "marqdo-host = { workspace = true }"), .any(|line| line.trim() == "marqdo-host = { workspace = true }"),
"runtime must keep the documented marqdo-runtime -> marqdo-host direction" "runtime normal/build dependencies must not link the native host"
); );
let host = read(&repo_root().join("crates/marqdo-host/Cargo.toml")); let contract = read(&root.join("crates/marqdo-host-contract/Cargo.toml"));
let contract_deps: Vec<&str> = contract
.split("[dependencies]")
.nth(1)
.expect("contract dependencies")
.lines()
.filter_map(|line| line.split('=').next())
.map(str::trim)
.filter(|name| !name.is_empty() && !name.starts_with('['))
.collect();
assert_eq!(
contract_deps,
["marqdo-span", "marqdo-value"],
"the host contract must stay platform neutral (value/span only)"
);
let host = read(&root.join("crates/marqdo-host/Cargo.toml"));
for forbidden in ["marqdo-runtime", "marqdo-frontend", "marqdo-ir ="] {
assert!( assert!(
!host.contains("marqdo-runtime"), !host.contains(forbidden),
"marqdo-host must not depend back on marqdo-runtime" "the native host must not depend back on `{forbidden}`"
);
}
assert!(
host.contains("marqdo-host-contract = { workspace = true }"),
"the native host must implement the neutral contract crate"
); );
} }
#[test] #[test]
fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() { fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
let root = stdlib_support::bundle_dir(); let root = repo_root().join("stdlib");
// 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 = let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap(); serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
assert_eq!(manifest["name"], "marqdo-stdlib"); assert_eq!(manifest["name"], "marqdo-stdlib");
@@ -113,7 +153,7 @@ fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
#[test] #[test]
fn stdlib_imports_resolve_inside_the_bundle() { fn stdlib_imports_resolve_inside_the_bundle() {
let root = stdlib_support::bundle_dir(); let root = repo_root().join("stdlib");
for entry in walk_markdown(&root) { for entry in walk_markdown(&root) {
let is_test = entry.starts_with(root.join("tests")); let is_test = entry.starts_with(root.join("tests"));
let text = read(&entry); let text = read(&entry);
@@ -163,7 +203,6 @@ fn shared_worker_transport_is_neutral_and_not_duplicated() {
} }
for user in [ for user in [
"crates/marqdo-host/Cargo.toml", "crates/marqdo-host/Cargo.toml",
"crates/marqdo-plugin-abi/Cargo.toml",
"crates/marqdo-provider-worker/Cargo.toml", "crates/marqdo-provider-worker/Cargo.toml",
] { ] {
assert!( assert!(
@@ -174,8 +213,8 @@ fn shared_worker_transport_is_neutral_and_not_duplicated() {
// The four-byte length prefix and its bounds live in exactly one crate. // The four-byte length prefix and its bounds live in exactly one crate.
for private in [ for private in [
"crates/marqdo-host/src/plugin_worker.rs", "crates/marqdo-host/src/plugin_worker.rs",
"crates/marqdo-host/src/plugin/worker.rs",
"crates/marqdo-host/src/provider_worker.rs", "crates/marqdo-host/src/provider_worker.rs",
"crates/marqdo-plugin-abi/src/worker.rs",
"crates/marqdo-provider-worker/src/main.rs", "crates/marqdo-provider-worker/src/main.rs",
] { ] {
let text = read(&root.join(private)); let text = read(&root.join(private));
@@ -419,12 +458,12 @@ fn builtin_names_and_aliases_are_reviewed() {
} }
// Exhaustive matches make a new HostOp or Value variant require review under ADR-0064. // Exhaustive matches make a new HostOp or Value variant require review under ADR-0064.
const _: fn(marqdo_host::HostOp) = |operation| match operation { const _: fn(marqdo_host_contract::HostOp) = |operation| match operation {
marqdo_host::HostOp::ForeignRun marqdo_host_contract::HostOp::ForeignRun
| marqdo_host::HostOp::ForeignCall | marqdo_host_contract::HostOp::ForeignCall
| marqdo_host::HostOp::FsRead | marqdo_host_contract::HostOp::FsRead
| marqdo_host::HostOp::FsWrite | marqdo_host_contract::HostOp::FsWrite
| marqdo_host::HostOp::PluginInvoke => (), | marqdo_host_contract::HostOp::PluginInvoke => (),
}; };
const _: fn(marqdo_value::Value) = |value| match value { const _: fn(marqdo_value::Value) = |value| match value {
@@ -449,7 +488,7 @@ const _: fn(marqdo_value::Value) = |value| match value {
/// hard-coded runtime names. Recompute the canonical metadata digest. /// hard-coded runtime names. Recompute the canonical metadata digest.
#[test] #[test]
fn official_stdlib_public_aliases_are_verified_metadata() { fn official_stdlib_public_aliases_are_verified_metadata() {
let root = stdlib_support::bundle_dir(); let root = repo_root().join("stdlib");
let manifest: serde_json::Value = let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap(); serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
let aliases = manifest["public_aliases"] let aliases = manifest["public_aliases"]
@@ -575,6 +614,129 @@ fn domain_math_kernel_is_not_part_of_the_core() {
} }
} }
/// E02/E03: there is exactly one Host trait/HostOp definition and it belongs to
/// the neutral contract; the native host only implements it.
#[test]
fn host_contract_is_the_single_side_effect_interface() {
let root = repo_root();
let mut host_traits = Vec::new();
let mut host_ops = Vec::new();
for source in walk_rs(&root.join("crates")) {
let relative = source
.strip_prefix(&root)
.unwrap()
.to_string_lossy()
.to_string();
if relative.contains("/tests/") {
continue;
}
let text = read(&source);
if text.contains("pub trait Host {") {
host_traits.push(relative.clone());
}
if text.contains("pub enum HostOp {") {
host_ops.push(relative);
}
}
assert_eq!(
host_traits,
["crates/marqdo-host-contract/src/host.rs"],
"the Host trait must be defined once in the neutral contract"
);
assert_eq!(
host_ops,
["crates/marqdo-host-contract/src/host.rs"],
"HostOp must be defined once in the neutral contract"
);
let runtime = read(&root.join("crates/marqdo-runtime/src/interpreter.rs"));
assert!(
runtime.contains("use marqdo_host_contract::{"),
"the interpreter must consume the neutral contract"
);
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
assert!(
host.contains("impl Host for StdHost"),
"StdHost remains the single native host implementation"
);
}
/// A05/S01: the public ABI crate is a contract, not a loader; execution side
/// lives in the native host and the SDK consumes only the contract.
#[test]
fn plugin_contract_carries_no_native_execution() {
let root = repo_root();
let abi = read(&root.join("crates/marqdo-plugin-abi/Cargo.toml"));
for forbidden in ["libloading", "marqdo-worker-ipc", "serde_yaml", "sha2"] {
assert!(
!abi.contains(forbidden),
"marqdo-plugin-abi must not depend on execution-side `{forbidden}`"
);
}
for module in ["loader", "worker", "manifest", "artifact"] {
assert!(
!root
.join(format!("crates/marqdo-plugin-abi/src/{module}.rs"))
.exists(),
"`{module}` is execution-side and belongs to the native host"
);
}
for module in ["loader", "worker", "manifest", "artifact"] {
assert!(
root.join(format!("crates/marqdo-host/src/plugin/{module}.rs"))
.exists(),
"native host must own plugin `{module}`"
);
}
let sdk = read(&root.join("crates/marqdo-plugin-sdk/Cargo.toml"));
for forbidden in [
"marqdo-host",
"marqdo-cli",
"libloading",
"marqdo-worker-ipc",
] {
assert!(
!sdk.contains(forbidden),
"the plugin SDK must not depend on `{forbidden}`"
);
}
}
/// E01/E04: the independent embedding consumer is a real package outside the
/// workspace and depends only on engine crates.
#[test]
fn embedding_consumer_is_engine_only() {
let root = repo_root();
let consumer = read(&root.join("tests/embedding/Cargo.toml"));
assert!(
consumer.contains("[workspace]"),
"the embedding consumer must be its own workspace to avoid feature unification"
);
assert!(
consumer.contains("marqdo-runtime"),
"the embedding consumer must execute through the real runtime"
);
for forbidden in [
"marqdo-host",
"marqdo-cli",
"marqdo-sandbox",
"marqdo-foreign",
] {
let dependency_line = format!("\n{forbidden} =");
assert!(
!consumer.contains(&dependency_line),
"the embedding consumer must not depend on `{forbidden}`"
);
}
assert!(
root.join("tests/embedding/Cargo.lock").is_file(),
"the independent consumer must pin its own lock file"
);
assert!(
root.join("tools/ci/check_engine_boundary.py").is_file(),
"the build-and-run engine gate must exist"
);
}
fn hex(bytes: &[u8]) -> String { fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2); let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes { for byte in bytes {
+1 -1
View File
@@ -11,7 +11,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Output}; use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget}; use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0); static COUNTER: AtomicU32 = AtomicU32::new(0);
+4 -6
View File
@@ -20,12 +20,10 @@
//! expectation; the checked-in goldens were reviewed individually. //! expectation; the checked-in goldens were reviewed individually.
use std::fs; use std::fs;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use marqdo_host::{Capabilities, Host, StdHost}; use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_ir::{ModuleId, Program, ResolvedImport}; use marqdo_ir::{ModuleId, Program, ResolvedImport};
use marqdo_runtime::{run, EvaluatedArg}; use marqdo_runtime::{run, EvaluatedArg};
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
@@ -294,7 +292,7 @@ fn normalise_relative(path: &Path) -> String {
/// unique registry, run the single binding pass and install its table. There is /// unique registry, run the single binding pass and install its table. There is
/// no `print_override` and no runtime name guessing. /// no `print_override` and no runtime name guessing.
fn bind_calls_with_stdlib_aliases(program: &mut Program) { fn bind_calls_with_stdlib_aliases(program: &mut Program) {
let root = stdlib_support::bundle_dir(); let root = repo_root().join("stdlib");
let mut loaded = std::collections::BTreeSet::new(); let mut loaded = std::collections::BTreeSet::new();
let mut official = Vec::new(); let mut official = Vec::new();
if root.join("stdlib.json").is_file() { if root.join("stdlib.json").is_file() {
@@ -431,7 +429,7 @@ fn install_entry_stdlib_imports(
module_id: &ModuleId, module_id: &ModuleId,
analysis: &marqdo_frontend::AnalysisResult, analysis: &marqdo_frontend::AnalysisResult,
) { ) {
let root = stdlib_support::bundle_dir(); let root = repo_root().join("stdlib");
let Some(imports) = analysis let Some(imports) = analysis
.document .document
.frontmatter() .frontmatter()
+1 -1
View File
@@ -9,7 +9,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Output}; use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget}; use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0); static COUNTER: AtomicU32 = AtomicU32::new(0);
+1 -1
View File
@@ -783,7 +783,7 @@ fn lock_and_sync_locked_detect_dependency_tampering() {
/// the Linux-only example manifest. This is what makes the integration test a /// the Linux-only example manifest. This is what makes the integration test a
/// real test on macOS/Windows rather than an accidental "no matching artifact". /// real test on macOS/Windows rather than an accidental "no matching artifact".
fn host_triple() -> String { fn host_triple() -> String {
marqdo_plugin_abi::artifact::current_target_triple() marqdo_host::plugin::artifact::current_target_triple()
.as_str() .as_str()
.to_string() .to_string()
} }
+1 -1
View File
@@ -280,7 +280,7 @@ fn native_plugin_is_fail_closed_in_event_mode() {
let digest = hex::encode(sha2::Sha256::digest(fs::read(&artifact).unwrap())); let digest = hex::encode(sha2::Sha256::digest(fs::read(&artifact).unwrap()));
let manifest = format!( let manifest = format!(
"plugin:\n name: demo.solver\n version: 0.1.0\n abi: \"^1.0\"\n kind: native\n exports:\n - name: solver.add\n signature: \"($a: Int, $b: Int) -> Int\"\n requires:\n - math.compute\n artifacts:\n - target: {}\n file: solver.so\n sha256: \"{}\"\n", "plugin:\n name: demo.solver\n version: 0.1.0\n abi: \"^1.0\"\n kind: native\n exports:\n - name: solver.add\n signature: \"($a: Int, $b: Int) -> Int\"\n requires:\n - math.compute\n artifacts:\n - target: {}\n file: solver.so\n sha256: \"{}\"\n",
marqdo_plugin_abi::HostTarget::current().triple(), marqdo_host::plugin::HostTarget::current().triple(),
digest digest
); );
fs::write(plugin_dir.join("plugin.yaml"), manifest).unwrap(); fs::write(plugin_dir.join("plugin.yaml"), manifest).unwrap();
+3 -7
View File
@@ -3,9 +3,6 @@
#[path = "support/observation.rs"] #[path = "support/observation.rs"]
pub mod observation; pub mod observation;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
@@ -112,8 +109,7 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
#[test] #[test]
fn p2_stdlib_table_also_runs_in_pure_mode() { fn p2_stdlib_table_also_runs_in_pure_mode() {
let bundle = stdlib_support::bundle_dir(); let path = repo_root().join("stdlib").join("tests").join("table.mq.md");
let path = bundle.join("tests").join("table.mq.md");
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args([ .args([
"run", "run",
@@ -123,8 +119,8 @@ fn p2_stdlib_table_also_runs_in_pure_mode() {
"--output", "--output",
"json", "json",
]) ])
.current_dir(&bundle) .current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", &bundle) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output() .output()
.expect("run table self-test"); .expect("run table self-test");
assert_eq!( assert_eq!(
+1 -1
View File
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Output}; use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{sha256_file, HostTarget}; use marqdo_host::plugin::{sha256_file, HostTarget};
static COUNTER: AtomicU32 = AtomicU32::new(0); static COUNTER: AtomicU32 = AtomicU32::new(0);
+1 -1
View File
@@ -24,7 +24,7 @@ use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::OnceLock; use std::sync::OnceLock;
use marqdo_plugin_abi::HostTarget; use marqdo_host::plugin::HostTarget;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
const MARKER_ENV: &str = "MARQDO_TEST_PROVIDER_MARKER"; const MARKER_ENV: &str = "MARQDO_TEST_PROVIDER_MARKER";
+10 -4
View File
@@ -5,9 +5,6 @@
//! runtime name special case and no hard-coded per-function scan. //! runtime name special case and no hard-coded per-function scan.
#![cfg(unix)] #![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Output}; use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
@@ -38,6 +35,15 @@ 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 { fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo")); let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
command.args(args).current_dir(dir); command.args(args).current_dir(dir);
@@ -56,7 +62,7 @@ fn stdout(output: &Output) -> String {
} }
fn copy_stdlib(target: &Path) { fn copy_stdlib(target: &Path) {
let source = stdlib_support::bundle_dir(); let source = repo().join("stdlib");
std::fs::create_dir_all(target).unwrap(); std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(&source).unwrap() { for entry in std::fs::read_dir(&source).unwrap() {
let entry = entry.unwrap(); let entry = entry.unwrap();
+10 -4
View File
@@ -1,17 +1,23 @@
//! Bundled stdlib (`std:`) and frozen-CLI closure tests (CM-A10). //! 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::path::{Path, PathBuf};
use std::process::Command; 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 { fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo") env!("CARGO_BIN_EXE_marqdo")
} }
fn stdlib_dir() -> PathBuf { fn stdlib_dir() -> PathBuf {
stdlib_support::bundle_dir() repo_root().join("stdlib")
} }
fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output { fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output {
+12 -6
View File
@@ -3,18 +3,24 @@
#[path = "support/observation.rs"] #[path = "support/observation.rs"]
pub mod observation; pub mod observation;
#[path = "support/stdlib.rs"] use std::path::Path;
pub mod stdlib_support;
use std::process::Command; use std::process::Command;
fn repo_root() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
#[test] #[test]
fn stdlib_http_parses_chunked_responses_and_builds_requests() { fn stdlib_http_parses_chunked_responses_and_builds_requests() {
let bundle = stdlib_support::bundle_dir();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/http.mq.md", "--output", "json"]) .args(["run", "tests/http.mq.md", "--output", "json"])
.current_dir(&bundle) .current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", &bundle) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output() .output()
.expect("run http self-test"); .expect("run http self-test");
assert_eq!( assert_eq!(
+11 -5
View File
@@ -8,14 +8,20 @@
#[path = "support/observation.rs"] #[path = "support/observation.rs"]
pub mod observation; pub mod observation;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::io::Write; use std::io::Write;
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use std::sync::{Mutex, MutexGuard}; 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(()); static FS_LOCK: Mutex<()> = Mutex::new(());
fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> { fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
@@ -27,7 +33,7 @@ fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
} }
fn stdlib_dir() -> PathBuf { fn stdlib_dir() -> PathBuf {
stdlib_support::bundle_dir() repo_root().join("stdlib")
} }
struct TestFile { struct TestFile {
+12 -6
View File
@@ -3,17 +3,23 @@
#[path = "support/observation.rs"] #[path = "support/observation.rs"]
pub mod observation; pub mod observation;
#[path = "support/stdlib.rs"] use std::path::Path;
pub mod stdlib_support;
use std::process::Command; 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 { fn run_table_self_test() -> serde_json::Value {
let bundle = stdlib_support::bundle_dir();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/table.mq.md", "--output", "json"]) .args(["run", "tests/table.mq.md", "--output", "json"])
.current_dir(&bundle) .current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", &bundle) .env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.output() .output()
.expect("run table self-test"); .expect("run table self-test");
assert_eq!( assert_eq!(
-356
View File
@@ -1,356 +0,0 @@
//! 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
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "marqdo-host-contract"
description = "Platform-neutral Host contract: the only side-effect boundary the runtime may know"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
authors.workspace = true
[dependencies]
marqdo-span = { workspace = true }
marqdo-value = { workspace = true }
File renamed without changes.
+194
View File
@@ -0,0 +1,194 @@
//! The host boundary used by the interpreter and future frontends.
//!
//! The trait is implemented by the native CLI host, by the independent
//! embedding/test host and by any future host. Implementations own effects,
//! grants and budgets; the runtime only requests operations through this
//! interface and never performs external I/O itself.
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
use crate::context::ExecutionContext;
use crate::observe::{FrameId, RuntimeObservation};
use crate::resource::ResourceRead;
/// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostOp {
/// One-shot foreign execution.
ForeignRun,
/// Typed foreign call.
ForeignCall,
/// Read a project file.
FsRead,
/// Write a project file.
FsWrite,
/// Invoke a plugin export.
PluginInvoke,
}
impl HostOp {
/// Stable operation name used in traces and diagnostics.
pub const fn name(self) -> &'static str {
match self {
HostOp::ForeignRun => "foreign.run",
HostOp::ForeignCall => "foreign.call",
HostOp::FsRead => "fs.read",
HostOp::FsWrite => "fs.write",
HostOp::PluginInvoke => "plugin.invoke",
}
}
}
/// The host boundary used by the interpreter and future View/IDE frontends.
pub trait Host {
/// Invoke one operation with already-evaluated arguments.
fn invoke(
&mut self,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError>;
/// Open a resource/stream by kind, descriptor and requested rights.
///
/// Default: unavailable. Only the standard host implements the first
/// resource kinds (ADR-0025).
fn resource_open(
&mut self,
_kind: &str,
_descriptor: &str,
_rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Read up to `max_bytes` from a resource into host memory.
fn resource_read(
&mut self,
_handle: ResourceHandle,
_max_bytes: usize,
ctx: &ExecutionContext,
) -> Result<ResourceRead, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Write bytes to a resource; returns the accepted count.
fn resource_write(
&mut self,
_handle: ResourceHandle,
_bytes: &[u8],
ctx: &ExecutionContext,
) -> Result<usize, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Close a resource handle.
fn resource_close(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<(), RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Accept one inbound TCP connection from a `tcp-listener` handle.
///
/// Default: unavailable. The standard host returns a new `Resource` in a
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
fn resource_accept(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide tcp listeners",
))
}
/// Execute one non-streaming resource operation (ADR-0041).
///
/// Default: unavailable. The standard host implements the `fs.*` group;
/// every call is capability-checked and project-mode only.
fn resource_request(
&mut self,
_operation: &str,
_args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource operations",
))
}
/// Consume evaluation fuel.
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check call-stack depth.
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check the wall-clock deadline.
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError>;
/// Take the buffered program output.
fn take_output(&mut self) -> Vec<u8>;
/// Whether the host has an installed observation sink.
///
/// The default host is inert; the interpreter uses this to skip building
/// any observation event when there is no capture destination.
fn observation_enabled(&self) -> bool {
false
}
/// Announce a successfully bound call frame.
///
/// Returns the run-unique frame identity, or `None` when observation is
/// disabled. Argument binding must have completed before this is called;
/// a binding failure never produces a frame.
fn observation_begin_frame(
&mut self,
_function_id: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<Option<FrameId>, RuntimeError> {
Ok(None)
}
/// Close a previously announced frame, including failure paths.
fn observation_end_frame(
&mut self,
_frame_id: Option<FrameId>,
_status: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<(), RuntimeError> {
Ok(())
}
/// Emit one borrowed runtime observation event. Default: ignored.
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
Ok(())
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Platform-neutral Host contract.
//!
//! This crate owns the only side-effect interface the language engine knows:
//! the [`Host`] trait, its [`HostOp`] surface, the per-call
//! [`ExecutionContext`], the opaque resource read result and the runtime
//! observation notifications. It is a Rust compile-time interface inside one
//! codebase, not a wire protocol: there is no HTTP, RPC, C ABI or dynamic
//! loading boundary here.
//!
//! The crate is deliberately neutral. It depends only on the language value
//! and span types; it must never link the native host, the CLI, the sandbox,
//! foreign kernels, the plugin loader or a project filesystem. Native and
//! embedded hosts implement [`Host`] without re-implementing any language
//! semantics. Authorization, budgets, resource identity and OS isolation stay
//! owned by the trusted host implementation that consumes this contract.
pub mod context;
pub mod host;
pub mod observe;
pub mod resource;
pub use context::ExecutionContext;
pub use host::{Host, HostOp};
pub use observe::{FrameId, LoopTransfer, ParameterSource, RuntimeObservation};
pub use resource::ResourceRead;
+118
View File
@@ -0,0 +1,118 @@
//! Runtime observation facts shared by the interpreter and the host contract.
//!
//! Only the types the interpreter itself produces and hands to [`crate::Host`]
//! live here. The host implementation keeps the concrete sink, redaction,
//! encoding and budget state; the public Observation protocol remains the
//! CLI's single producer. This module must not grow a second event vocabulary.
use marqdo_span::Span;
use marqdo_value::Value;
/// Opaque run-scoped call-instance identity.
///
/// Not a function identity, not a source location and never a memory pointer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FrameId(pub u64);
impl FrameId {
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
pub fn as_wire(self) -> String {
format!("f{}", self.0)
}
}
/// Where a bound parameter's value came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParameterSource {
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
Provided,
/// Evaluated from the declared default expression.
Default,
}
impl ParameterSource {
/// Stable wire name.
pub const fn as_str(self) -> &'static str {
match self {
ParameterSource::Provided => "provided",
ParameterSource::Default => "default",
}
}
}
/// The action carried by a structured loop transfer observation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopTransfer {
/// Exit the enclosing loop.
Break,
/// Proceed to the enclosing loop's next condition check.
Continue,
}
impl LoopTransfer {
/// The event kind in Observation.
pub fn event_kind(self) -> &'static str {
match self {
Self::Break => "control.break",
Self::Continue => "control.continue",
}
}
}
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
///
/// Value and control observations carry the owning call frame.
#[derive(Debug)]
pub enum RuntimeObservation<'a> {
/// A local memory operation committed.
Effect {
operation: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A `return` statement committed (before the call exits).
Return {
frame_id: Option<FrameId>,
value_type: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A branch condition evaluated.
BranchEval {
frame_id: Option<FrameId>,
result: bool,
module_id: &'a str,
span: Option<Span>,
},
/// A loop condition evaluated.
LoopIteration {
frame_id: Option<FrameId>,
decision: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: Option<FrameId>,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// A local variable assignment committed.
VariableAssigned {
frame_id: Option<FrameId>,
name: &'a str,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
/// A parameter was bound.
ParameterBound {
frame_id: Option<FrameId>,
name: &'a str,
source: ParameterSource,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
}
@@ -0,0 +1,10 @@
//! Values crossing the resource stream methods of [`crate::Host`].
/// Bytes returned by one stream read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceRead {
/// Bytes actually read (may be empty at EOF).
pub bytes: Vec<u8>,
/// Whether the stream has reached EOF.
pub eof: bool,
}
+4
View File
@@ -12,6 +12,7 @@ authors.workspace = true
libloading = { workspace = true } libloading = { workspace = true }
rustls = { workspace = true } rustls = { workspace = true }
rustls-native-certs = { workspace = true } rustls-native-certs = { workspace = true }
marqdo-host-contract = { workspace = true }
marqdo-plugin-abi = { workspace = true } marqdo-plugin-abi = { workspace = true }
marqdo-worker-ipc = { workspace = true } marqdo-worker-ipc = { workspace = true }
flate2 = { workspace = true } flate2 = { workspace = true }
@@ -23,6 +24,9 @@ marqdo-value = { workspace = true }
marqdo-foreign = { workspace = true } marqdo-foreign = { workspace = true }
marqdo-sandbox = { workspace = true } marqdo-sandbox = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
serde_yaml = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
+13 -192
View File
@@ -9,27 +9,30 @@ use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
use marqdo_plugin_abi::{ use crate::plugin::{
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest, CapabilityHandler, HostTarget, LoadOptions, LoadedPlugin, PluginKind, PluginManifest,
}; };
use marqdo_host_contract::{
ExecutionContext, FrameId, Host, HostOp, ResourceRead, RuntimeObservation,
};
use marqdo_plugin_abi::{ErrorKind as PluginErrorKind, PluginError};
use marqdo_span::Span; use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value}; use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
use rustls::pki_types::CertificateDer; use rustls::pki_types::CertificateDer;
use crate::budget::Budget; use crate::budget::Budget;
use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker}; use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
use crate::context::ExecutionContext;
use crate::fs::ProjectFs; use crate::fs::ProjectFs;
use crate::handles::{contains_plugin_handle, PluginHandleTable}; use crate::handles::{contains_plugin_handle, PluginHandleTable};
use crate::observe::{ use crate::observe::{
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError, encode_value, estimate_event_bytes, ObservationConfig, ObservationError, ObservationEvent,
ObservationEvent, ObservationSink, ObservationState, RuntimeObservation, ObservationSink, ObservationState,
}; };
use crate::plugin_worker::WorkerPlugin; use crate::plugin_worker::WorkerPlugin;
use crate::provider_c::{load_package, CResourceProvider}; use crate::provider_c::{load_package, CResourceProvider};
use crate::provider_worker::WorkerResourceProvider; use crate::provider_worker::WorkerResourceProvider;
use crate::resource::{ use crate::resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider, is_core_resource_kind, ResourceProvider, ResourceTable, SharedResourceProvider,
}; };
use marqdo_sandbox::{PlatformCapabilities, SandboxMode}; use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
@@ -38,187 +41,6 @@ mod providers;
mod resource_ops; mod resource_ops;
mod resource_requests; mod resource_requests;
/// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostOp {
/// One-shot foreign execution.
ForeignRun,
/// Typed foreign call.
ForeignCall,
/// Read a project file.
FsRead,
/// Write a project file.
FsWrite,
/// Invoke a plugin export.
PluginInvoke,
}
impl HostOp {
/// Stable operation name used in traces and diagnostics.
pub const fn name(self) -> &'static str {
match self {
HostOp::ForeignRun => "foreign.run",
HostOp::ForeignCall => "foreign.call",
HostOp::FsRead => "fs.read",
HostOp::FsWrite => "fs.write",
HostOp::PluginInvoke => "plugin.invoke",
}
}
}
/// The host boundary used by the interpreter and future View/IDE frontends.
pub trait Host {
/// Invoke one operation with already-evaluated arguments.
fn invoke(
&mut self,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError>;
/// Open a resource/stream by kind, descriptor and requested rights.
///
/// Default: unavailable. Only the standard host implements the first
/// resource kinds (ADR-0025).
fn resource_open(
&mut self,
_kind: &str,
_descriptor: &str,
_rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Read up to `max_bytes` from a resource into host memory.
fn resource_read(
&mut self,
_handle: ResourceHandle,
_max_bytes: usize,
ctx: &ExecutionContext,
) -> Result<ResourceRead, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Write bytes to a resource; returns the accepted count.
fn resource_write(
&mut self,
_handle: ResourceHandle,
_bytes: &[u8],
ctx: &ExecutionContext,
) -> Result<usize, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Close a resource handle.
fn resource_close(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<(), RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource streams",
))
}
/// Accept one inbound TCP connection from a `tcp-listener` handle.
///
/// Default: unavailable. The standard host returns a new `Resource` in a
/// recoverable `{ok,value}` map or `{ok:false,code:"tcp.timeout"}`.
fn resource_accept(
&mut self,
_handle: ResourceHandle,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide tcp listeners",
))
}
/// Execute one non-streaming resource operation (ADR-0041).
///
/// Default: unavailable. The standard host implements the `fs.*` group;
/// every call is capability-checked and project-mode only.
fn resource_request(
&mut self,
_operation: &str,
_args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"this host does not provide resource operations",
))
}
/// Consume evaluation fuel.
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check call-stack depth.
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError>;
/// Check the wall-clock deadline.
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError>;
/// Take the buffered program output.
fn take_output(&mut self) -> Vec<u8>;
/// Whether the host has an installed observation sink.
///
/// The default host is inert; the interpreter uses this to skip building
/// any observation event when there is no capture destination.
fn observation_enabled(&self) -> bool {
false
}
/// Announce a successfully bound call frame.
///
/// Returns the run-unique frame identity, or `None` when observation is
/// disabled. Argument binding must have completed before this is called;
/// a binding failure never produces a frame.
fn observation_begin_frame(
&mut self,
_function_id: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<Option<FrameId>, RuntimeError> {
Ok(None)
}
/// Close a previously announced frame, including failure paths.
fn observation_end_frame(
&mut self,
_frame_id: Option<FrameId>,
_status: &str,
_module_id: &str,
_span: Option<Span>,
) -> Result<(), RuntimeError> {
Ok(())
}
/// Emit one borrowed runtime observation event. Default: ignored.
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
Ok(())
}
}
/// Default capability host implementation. /// Default capability host implementation.
pub struct StdHost { pub struct StdHost {
/// Requested sandbox mode. /// Requested sandbox mode.
@@ -372,7 +194,7 @@ impl StdHost {
exports.insert(export.name.clone(), export.signature.clone()); exports.insert(export.name.clone(), export.signature.clone());
} }
let artifact = manifest let artifact = manifest
.resolve_artifact(&marqdo_plugin_abi::HostTarget::current()) .resolve_artifact(&HostTarget::current())
.map_err(map_plugin_error)?; .map_err(map_plugin_error)?;
let manifest_digest = artifact.sha256.clone(); let manifest_digest = artifact.sha256.clone();
let transport = match manifest.plugin.kind { let transport = match manifest.plugin.kind {
@@ -398,8 +220,8 @@ impl StdHost {
broker.allow_vendor(capability.clone()); broker.allow_vendor(capability.clone());
} }
let package = manifest.plugin.name.clone(); let package = manifest.plugin.name.clone();
let options = marqdo_plugin_abi::LoadOptions { let options = LoadOptions {
host_target: marqdo_plugin_abi::HostTarget::current(), host_target: HostTarget::current(),
capability_handler: Some(Box::new(move |capability, request| { capability_handler: Some(Box::new(move |capability, request| {
broker.execute(&package, capability, request) broker.execute(&package, capability, request)
})), })),
@@ -419,8 +241,7 @@ impl StdHost {
broker.allow_vendor(capability.clone()); broker.allow_vendor(capability.clone());
} }
let package = manifest.plugin.name.clone(); let package = manifest.plugin.name.clone();
let handler: marqdo_plugin_abi::CapabilityHandler = let handler: CapabilityHandler = Box::new(move |capability, request| {
Box::new(move |capability, request| {
broker.execute(&package, capability, request) broker.execute(&package, capability, request)
}); });
PluginTransport::Worker( PluginTransport::Worker(
+2 -2
View File
@@ -11,8 +11,8 @@ use std::time::Duration;
use marqdo_value::{to_wire, ErrorCategory, RuntimeError, Value}; use marqdo_value::{to_wire, ErrorCategory, RuntimeError, Value};
use crate::context::ExecutionContext; use crate::host::StdHost;
use crate::host::{HostOp, StdHost}; use marqdo_host_contract::{ExecutionContext, HostOp};
pub(crate) fn foreign( pub(crate) fn foreign(
host: &mut StdHost, host: &mut StdHost,
+21 -12
View File
@@ -1,17 +1,28 @@
//! CapabilityHost: capability checks, resource budgets, observation and the //! Native Host: the one concrete implementation of the neutral
//! only bridge to math, foreign kernels, files and plugins. //! [`marqdo_host_contract::Host`] boundary.
//! //!
//! Blueprint §9 and §7.3: every side effect goes through this boundary, checks //! Every side effect goes through this crate, checks happen at the point of
//! happen at the point of execution, and host failures are structured errors. //! execution, and host failures are structured errors. The crate owns the OS
//! adapters, capability grants, resource handles, observation sink and trusted
//! extension execution; it never owns language semantics and never depends back
//! on the runtime, frontend or IR.
//!
//! Responsibility map (ADR-0071):
//! - [`capability`]/[`budget`]: grants, broker, audit, fuel/stack/deadline/output;
//! - [`resource`], [`fs`], `process`: resource kinds, handles and OS effects;
//! - [`plugin`], `plugin_worker`, `provider_c`, `provider_worker`, [`kernels`]:
//! trusted plugin/provider/foreign execution (no second static binder);
//! - [`observe`]: the runtime observation sink, redaction, budget and encoding;
//! - [`host`]: `StdHost` assembly and the single dispatch table.
pub mod budget; pub mod budget;
pub mod capability; pub mod capability;
pub mod context;
pub mod fs; pub mod fs;
pub mod handles; pub mod handles;
pub mod host; pub mod host;
pub mod kernels; pub mod kernels;
pub mod observe; pub mod observe;
pub mod plugin;
mod plugin_worker; mod plugin_worker;
mod process; mod process;
mod provider_c; mod provider_c;
@@ -23,18 +34,16 @@ pub use capability::{
Capabilities, CapabilityAudit, CapabilityBroker, CapabilityHandler, CapabilityRequest, Capabilities, CapabilityAudit, CapabilityBroker, CapabilityHandler, CapabilityRequest,
FsReadHandler, CORE_CAPABILITIES, RESERVED_HANDLER_PREFIXES, FsReadHandler, CORE_CAPABILITIES, RESERVED_HANDLER_PREFIXES,
}; };
pub use context::ExecutionContext;
pub use fs::ProjectFs; pub use fs::ProjectFs;
pub use handles::{contains_plugin_handle, PluginHandleTable}; pub use handles::{contains_plugin_handle, PluginHandleTable};
pub use host::{arity, expect_text, Host, HostOp, StdHost}; pub use host::{arity, expect_text, StdHost};
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation}; pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
pub use observe::{ pub use observe::{
encode_value, estimate_event_bytes, FrameId, LoopTransfer, ObservationConfig, ObservationError, encode_value, estimate_event_bytes, ObservationConfig, ObservationError, ObservationEvent,
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation, ObservationSink, ObservedValue, ValueState, DEFAULT_MAX_OBSERVATION_BYTES,
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_OBSERVATION_EVENTS, DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
}; };
pub use resource::{ pub use resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider, is_core_resource_kind, ResourceProvider, ResourceTable, SharedResourceProvider,
CORE_RESOURCE_KINDS, CORE_RESOURCE_KINDS,
}; };
+1 -109
View File
@@ -12,6 +12,7 @@
use std::collections::BTreeSet; use std::collections::BTreeSet;
use marqdo_host_contract::{FrameId, LoopTransfer, ParameterSource};
use marqdo_span::Span; use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError, Value}; use marqdo_value::{ErrorCategory, RuntimeError, Value};
@@ -24,38 +25,6 @@ pub const DEFAULT_MAX_VALUE_BYTES: usize = 256;
/// Maximum committed stdio bytes carried by one chunk event. /// Maximum committed stdio bytes carried by one chunk event.
pub const MAX_STREAM_CHUNK_BYTES: usize = 64 * 1024; pub const MAX_STREAM_CHUNK_BYTES: usize = 64 * 1024;
/// Opaque run-scoped call-instance identity.
///
/// Not a function identity, not a source location and never a memory pointer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FrameId(pub u64);
impl FrameId {
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
pub fn as_wire(self) -> String {
format!("f{}", self.0)
}
}
/// Where a bound parameter's value came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParameterSource {
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
Provided,
/// Evaluated from the declared default expression.
Default,
}
impl ParameterSource {
/// Stable wire name.
pub const fn as_str(self) -> &'static str {
match self {
ParameterSource::Provided => "provided",
ParameterSource::Default => "default",
}
}
}
/// Observation policy for one run. /// Observation policy for one run.
/// ///
/// `structural` always implies frame identity; value events only exist for /// `structural` always implies frame identity; value events only exist for
@@ -238,83 +207,6 @@ pub enum ObservationEvent<'a> {
}, },
} }
/// The action carried by a structured loop transfer observation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopTransfer {
/// Exit the enclosing loop.
Break,
/// Proceed to the enclosing loop's next condition check.
Continue,
}
impl LoopTransfer {
/// The event kind in Observation.
pub fn event_kind(self) -> &'static str {
match self {
Self::Break => "control.break",
Self::Continue => "control.continue",
}
}
}
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
///
/// Value and control observations carry the owning call frame.
#[derive(Debug)]
pub enum RuntimeObservation<'a> {
/// A local memory operation committed.
Effect {
operation: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A `return` statement committed (before the call exits).
Return {
frame_id: Option<FrameId>,
value_type: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// A branch condition evaluated.
BranchEval {
frame_id: Option<FrameId>,
result: bool,
module_id: &'a str,
span: Option<Span>,
},
/// A loop condition evaluated.
LoopIteration {
frame_id: Option<FrameId>,
decision: &'a str,
module_id: &'a str,
span: Option<Span>,
},
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: Option<FrameId>,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// A local variable assignment committed.
VariableAssigned {
frame_id: Option<FrameId>,
name: &'a str,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
/// A parameter was bound.
ParameterBound {
frame_id: Option<FrameId>,
name: &'a str,
source: ParameterSource,
value: &'a Value,
module_id: &'a str,
span: Option<Span>,
},
}
/// Sink installed by the composition root (the CLI JSONL writer in product /// Sink installed by the composition root (the CLI JSONL writer in product
/// builds, an in-memory recorder in tests). /// builds, an in-memory recorder in tests).
pub trait ObservationSink { pub trait ObservationSink {
@@ -11,7 +11,7 @@ use std::path::Path;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use crate::error::PluginError; use marqdo_plugin_abi::PluginError;
/// Length of a lowercase hexadecimal sha256 digest. /// Length of a lowercase hexadecimal sha256 digest.
pub const SHA256_HEX_LEN: usize = 64; pub const SHA256_HEX_LEN: usize = 64;
@@ -16,16 +16,16 @@ use std::ptr;
use libloading::{Library, Symbol}; use libloading::{Library, Symbol};
use serde::Deserialize; use serde::Deserialize;
use crate::abi::{ use super::artifact::HostTarget;
use super::manifest::{PluginKind, PluginManifest};
use marqdo_plugin_abi::abi::{
check_host_api, negotiate, result, AbiVersion, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes, check_host_api, negotiate, result, AbiVersion, MqBytes, MqCallContext, MqHostApi, MqOwnedBytes,
MqPluginApi, MqPluginEntryV1, MqPluginInvoke, PluginMetadata, ABI_MAJOR, ABI_MINOR, MqPluginApi, MqPluginEntryV1, MqPluginInvoke, PluginMetadata, ABI_MAJOR, ABI_MINOR,
ENTRY_SYMBOL, MAX_CAPABILITY_REPLY_BYTES, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES, ENTRY_SYMBOL, MAX_CAPABILITY_REPLY_BYTES, MAX_ERROR_WIRE_BYTES, MAX_EXPORT_NAME_BYTES,
MAX_RESULT_WIRE_BYTES, MAX_SIGNATURE_WIRE_BYTES, MAX_RESULT_WIRE_BYTES, MAX_SIGNATURE_WIRE_BYTES,
}; };
use crate::artifact::HostTarget; use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
use crate::error::PluginError; use marqdo_plugin_abi::PluginError;
use crate::manifest::{PluginKind, PluginManifest};
use crate::wire::{WireRequest, WireResponse};
/// A callback the host installs to answer capability requests from a plugin. /// A callback the host installs to answer capability requests from a plugin.
/// ///
@@ -304,13 +304,13 @@ impl LoadedPlugin {
/// This is primarily for ABI conformance tests; prefer /// This is primarily for ABI conformance tests; prefer
/// [`LoadedPlugin::invoke`] for normal use. /// [`LoadedPlugin::invoke`] for normal use.
pub fn invoke_raw(&mut self, function: &str, args_wire: &[u8]) -> Result<Vec<u8>, PluginError> { pub fn invoke_raw(&mut self, function: &str, args_wire: &[u8]) -> Result<Vec<u8>, PluginError> {
if args_wire.len() > crate::abi::MAX_REQUEST_WIRE_BYTES { if args_wire.len() > marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES {
return Err(PluginError::wire( return Err(PluginError::wire(
"request_too_large", "request_too_large",
format!( format!(
"request wire is {} bytes, limit is {}", "request wire is {} bytes, limit is {}",
args_wire.len(), args_wire.len(),
crate::abi::MAX_REQUEST_WIRE_BYTES marqdo_plugin_abi::abi::MAX_REQUEST_WIRE_BYTES
), ),
)); ));
} }
@@ -10,12 +10,12 @@ use std::path::{Component, Path, PathBuf};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::abi::{ use super::artifact::{is_valid_sha256_hex, TargetTriple};
use super::artifact::{verify_sha256_file, HostTarget};
use marqdo_plugin_abi::abi::{
AbiVersion, ABI_MAJOR, ABI_MINOR, MAX_EXPORT_NAME_BYTES, MAX_SIGNATURE_WIRE_BYTES, AbiVersion, ABI_MAJOR, ABI_MINOR, MAX_EXPORT_NAME_BYTES, MAX_SIGNATURE_WIRE_BYTES,
}; };
use crate::artifact::{is_valid_sha256_hex, TargetTriple}; use marqdo_plugin_abi::PluginError;
use crate::artifact::{verify_sha256_file, HostTarget};
use crate::error::PluginError;
/// Maximum number of exports a single plugin may register. /// Maximum number of exports a single plugin may register.
pub const MAX_EXPORTS: usize = 256; pub const MAX_EXPORTS: usize = 256;
@@ -648,7 +648,7 @@ plugin:
#[test] #[test]
fn malformed_yaml_is_rejected() { fn malformed_yaml_is_rejected() {
let error = PluginManifest::parse_str("plugin: [unclosed").expect_err("must fail"); let error = PluginManifest::parse_str("plugin: [unclosed").expect_err("must fail");
assert_eq!(error.kind, crate::error::ErrorKind::Manifest); assert_eq!(error.kind, marqdo_plugin_abi::ErrorKind::Manifest);
assert_eq!(error.code, "manifest_parse_failed"); assert_eq!(error.code, "manifest_parse_failed");
assert!(PluginManifest::parse_str("not_a_plugin: 1").is_err()); assert!(PluginManifest::parse_str("not_a_plugin: 1").is_err());
} }
@@ -683,7 +683,7 @@ plugin:
), ),
Err(error) => assert_eq!( Err(error) => assert_eq!(
error.kind, error.kind,
crate::error::ErrorKind::Manifest, marqdo_plugin_abi::ErrorKind::Manifest,
"`{field}` = `{value}` should fail manifest handling" "`{field}` = `{value}` should fail manifest handling"
), ),
} }
+26
View File
@@ -0,0 +1,26 @@
//! Execution side of the Callable Plugin ABI: manifest/artifact validation,
//! native loading, invocation dispatch and the worker process.
//!
//! The public contract (C layout, wire envelope and protocol errors) lives in
//! `marqdo-plugin-abi`; this module owns `dlopen`, process spawning, artifact
//! file selection and trusted invocation. The CLI may consume the static
//! descriptor types for `check`/`inspect` preparation, but preparation never
//! loads a library or starts a process.
//!
//! The `include/marqdo_plugin_abi_v1.h` header and the Rust layout assertions
//! in `marqdo_plugin_abi::abi` remain the single ABI authority.
pub mod artifact;
pub mod loader;
pub mod manifest;
pub mod worker;
pub use artifact::{
current_target_triple, is_valid_sha256_hex, sha256_bytes, sha256_file, verify_sha256_file,
HostTarget, TargetTriple,
};
pub use loader::{CapabilityHandler, LoadOptions, LoadedPlugin, RegisteredExport};
pub use manifest::{
AbiRequirement, Artifact, Export, PackageVersion, PluginInfo, PluginKind, PluginManifest,
KNOWN_CAPABILITIES,
};
@@ -13,10 +13,10 @@ use std::sync::{Arc, Mutex};
use serde_json::{json, Value}; use serde_json::{json, Value};
use crate::error::PluginError; use super::loader::{LoadOptions, LoadedPlugin};
use crate::loader::{LoadOptions, LoadedPlugin}; use super::manifest::{PluginKind, PluginManifest};
use crate::manifest::{PluginKind, PluginManifest}; use marqdo_plugin_abi::wire::{WireRequest, WireResponse};
use crate::wire::{WireRequest, WireResponse}; use marqdo_plugin_abi::PluginError;
/// Hidden CLI command name used to start a worker. /// Hidden CLI command name used to start a worker.
pub const WORKER_COMMAND: &str = "__plugin-worker"; pub const WORKER_COMMAND: &str = "__plugin-worker";
@@ -91,7 +91,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
let handler_stdout = Arc::clone(&stdout); let handler_stdout = Arc::clone(&stdout);
let handler_ids = Arc::clone(&next_request_id); let handler_ids = Arc::clone(&next_request_id);
let handler_calls = Arc::clone(&capability_calls); let handler_calls = Arc::clone(&capability_calls);
let capability_handler: crate::loader::CapabilityHandler = Box::new( let capability_handler: super::loader::CapabilityHandler = Box::new(
move |capability, request| { move |capability, request| {
if handler_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CAPABILITY_REQUESTS { if handler_calls.fetch_add(1, Ordering::SeqCst) >= MAX_CAPABILITY_REQUESTS {
return Err(PluginError::capability( return Err(PluginError::capability(
@@ -185,7 +185,7 @@ pub fn serve(manifest_path: &Path, base_dir: &Path) -> i32 {
}, },
); );
let options = LoadOptions { let options = LoadOptions {
host_target: crate::artifact::HostTarget::current(), host_target: super::artifact::HostTarget::current(),
capability_handler: Some(capability_handler), capability_handler: Some(capability_handler),
}; };
let mut plugin = match LoadedPlugin::open_with(&native_manifest, base_dir, options) { let mut plugin = match LoadedPlugin::open_with(&native_manifest, base_dir, options) {
+3 -4
View File
@@ -15,13 +15,12 @@ use std::path::Path;
use std::process::{Child, Command, Stdio}; use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use marqdo_plugin_abi::worker::{ use crate::plugin::worker::{
response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES, response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES,
WORKER_COMMAND, WORKER_COMMAND,
}; };
use marqdo_plugin_abi::{ use crate::plugin::{CapabilityHandler, PluginManifest};
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse, use marqdo_plugin_abi::{PluginError, WireRequest, WireResponse};
};
use marqdo_worker_ipc::{Connection, FrameError, TransportError}; use marqdo_worker_ipc::{Connection, FrameError, TransportError};
use serde_json::json; use serde_json::json;
+1 -1
View File
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
use marqdo_value::{ErrorCategory, RuntimeError, Value}; use marqdo_value::{ErrorCategory, RuntimeError, Value};
use crate::context::ExecutionContext; use marqdo_host_contract::ExecutionContext;
fn process_error(code: &str, message: &str) -> Value { fn process_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
+2 -1
View File
@@ -12,7 +12,8 @@ use libloading::Library;
use marqdo_span::Span; use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError}; use marqdo_value::{ErrorCategory, RuntimeError};
use crate::resource::{ResourceProvider, ResourceRead}; use crate::resource::ResourceProvider;
use marqdo_host_contract::ResourceRead;
const ABI_VERSION: u32 = 1; const ABI_VERSION: u32 = 1;
const ERROR_MAX: usize = 1024; const ERROR_MAX: usize = 1024;
+2 -1
View File
@@ -18,7 +18,8 @@ use marqdo_span::Span;
use marqdo_worker_ipc::{Connection, FrameError, TransportError}; use marqdo_worker_ipc::{Connection, FrameError, TransportError};
use serde_json::{json, Value as Json}; use serde_json::{json, Value as Json};
use crate::resource::{ResourceProvider, ResourceRead}; use crate::resource::ResourceProvider;
use marqdo_host_contract::ResourceRead;
use marqdo_value::{ErrorCategory, RuntimeError}; use marqdo_value::{ErrorCategory, RuntimeError};
const MAX_FRAME_BYTES: usize = 1024 * 1024; const MAX_FRAME_BYTES: usize = 1024 * 1024;
+1 -9
View File
@@ -13,6 +13,7 @@ use rustls::{ClientConnection, StreamOwned};
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use marqdo_host_contract::ResourceRead;
use marqdo_span::Span; use marqdo_span::Span;
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError}; use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
@@ -83,15 +84,6 @@ pub trait ResourceProvider: Send {
/// Shared provider handle registered on the host. /// Shared provider handle registered on the host.
pub type SharedResourceProvider = Arc<Mutex<Box<dyn ResourceProvider>>>; pub type SharedResourceProvider = Arc<Mutex<Box<dyn ResourceProvider>>>;
/// Bytes returned by one stream read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceRead {
/// Bytes actually read (may be empty at EOF).
pub bytes: Vec<u8>,
/// Whether the stream has reached EOF.
pub eof: bool,
}
struct StdinCursor { struct StdinCursor {
bytes: Vec<u8>, bytes: Vec<u8>,
position: usize, position: usize,
+4 -3
View File
@@ -3,12 +3,13 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost}; use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
use marqdo_value::ErrorCategory; use marqdo_value::ErrorCategory;
fn context() -> marqdo_host::ExecutionContext { fn context() -> marqdo_host_contract::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None) marqdo_host_contract::ExecutionContext::new("test".to_string(), None)
} }
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle { fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
@@ -5,8 +5,9 @@ use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_host::{Capabilities, Host, HostOp, StdHost}; use marqdo_host::plugin::{sha256_file, HostTarget, PluginManifest};
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest}; use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{Host, HostOp};
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value}; use marqdo_value::{ErrorCategory, Value};
@@ -11,9 +11,9 @@ use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_plugin_abi::{ use marqdo_host::plugin::{sha256_file, HostTarget, LoadedPlugin, PluginManifest};
sha256_file, ErrorKind, HostTarget, LoadedPlugin, PluginManifest, Value, WireRequest, use marqdo_plugin_abi::{ErrorKind, WireRequest};
}; use marqdo_value::Value;
static TEMP_COUNTER: AtomicU32 = AtomicU32::new(0); static TEMP_COUNTER: AtomicU32 = AtomicU32::new(0);
+3 -3
View File
@@ -8,10 +8,10 @@ use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use marqdo_host::{ use marqdo_host::{
encode_value, Capabilities, ExecutionContext, FrameId, Host, ObservationConfig, encode_value, Capabilities, ObservationConfig, ObservationError, ObservationEvent,
ObservationError, ObservationEvent, ObservationSink, ParameterSource, RuntimeObservation, ObservationSink, StdHost, ValueState,
StdHost, ValueState,
}; };
use marqdo_host_contract::{ExecutionContext, FrameId, Host, ParameterSource, RuntimeObservation};
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value}; use marqdo_value::{ErrorCategory, Value};
+3 -2
View File
@@ -6,8 +6,9 @@ use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use marqdo_host::{Capabilities, Host, HostOp, StdHost}; use marqdo_host::plugin::{sha256_file, HostTarget, PluginManifest};
use marqdo_plugin_abi::{sha256_file, HostTarget, PluginManifest}; use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{Host, HostOp};
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
use marqdo_value::Value; use marqdo_value::Value;
+4 -3
View File
@@ -2,7 +2,8 @@
use std::path::Path; use std::path::Path;
use marqdo_host::{Capabilities, ExecutionContext, Host, HostOp, StdHost}; use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{ExecutionContext, Host, HostOp};
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value}; use marqdo_value::{ErrorCategory, Value};
@@ -325,12 +326,12 @@ impl marqdo_host::ResourceProvider for MockProvider {
token: u64, token: u64,
max_bytes: usize, max_bytes: usize,
_span: Option<marqdo_span::Span>, _span: Option<marqdo_span::Span>,
) -> Result<marqdo_host::ResourceRead, marqdo_value::RuntimeError> { ) -> Result<marqdo_host_contract::ResourceRead, marqdo_value::RuntimeError> {
assert_eq!(token, 7); assert_eq!(token, 7);
let start = self.position; let start = self.position;
let end = start.saturating_add(max_bytes).min(self.data.len()); let end = start.saturating_add(max_bytes).min(self.data.len());
self.position = end; self.position = end;
Ok(marqdo_host::ResourceRead { Ok(marqdo_host_contract::ResourceRead {
bytes: self.data[start..end].to_vec(), bytes: self.data[start..end].to_vec(),
eof: end >= self.data.len(), eof: end >= self.data.len(),
}) })
+4 -3
View File
@@ -1,9 +1,10 @@
use marqdo_host::{Capabilities, Host, StdHost}; use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
use marqdo_value::ErrorCategory; use marqdo_value::ErrorCategory;
fn context() -> marqdo_host::ExecutionContext { fn context() -> marqdo_host_contract::ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None) marqdo_host_contract::ExecutionContext::new("test".to_string(), None)
} }
fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle { fn handle(value: marqdo_value::Value) -> marqdo_value::ResourceHandle {
+1 -7
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "marqdo-plugin-abi" name = "marqdo-plugin-abi"
description = "Versioned C ABI v1 bindings, manifest validation and artifact loading" description = "Public plugin ABI v1 contract: C layout, wire envelope and protocol errors"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -9,13 +9,7 @@ repository.workspace = true
authors.workspace = true authors.workspace = true
[dependencies] [dependencies]
marqdo-span = { workspace = true }
marqdo-value = { workspace = true } marqdo-value = { workspace = true }
marqdo-worker-ipc = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
serde_yaml = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
libloading = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
+7 -2
View File
@@ -255,12 +255,17 @@ pub struct MqCallContext {
impl MqCallContext { impl MqCallContext {
/// Mint a context for a host invocation. /// Mint a context for a host invocation.
pub(crate) fn new(host_data: *mut c_void) -> Self { ///
/// Host-side execution API: the native host owns the invocation lifetime
/// and passes an opaque pointer the plugin never dereferences.
pub fn new(host_data: *mut c_void) -> Self {
Self { host_data } Self { host_data }
} }
/// Opaque host data pointer carried by this context. /// Opaque host data pointer carried by this context.
pub(crate) fn host_data(&self) -> *mut c_void { ///
/// Host-side execution API; not part of the C layout exposed to plugins.
pub fn host_data(&self) -> *mut c_void {
self.host_data self.host_data
} }
} }
+13 -30
View File
@@ -1,31 +1,23 @@
//! Versioned plugin C ABI v1 bindings, manifest validation and artifact //! Public contract for the versioned plugin C ABI v1.
//! loading (host side).
//! //!
//! This crate is the host-side counterpart of //! This crate is the single normative Rust side of
//! `include/marqdo_plugin_abi_v1.h` (the frozen C ABI) and of the //! `include/marqdo_plugin_abi_v1.h`: the stable `#[repr(C)]` types with layout
//! `marqdo-plugin-sdk` crate (the plugin-developer side). It implements the //! assertions and major/minor negotiation ([`abi`]), the `wire_version` 1
//! blueprint section 10 contract: //! JSON request/response envelope with typed value tags ([`wire`]), and the
//! structured protocol [`PluginError`].
//! //!
//! - stable `#[repr(C)]` Rust mirrors of the C types, with compile-time layout //! It is a contract crate, not a loader. Native loading (`dlopen`), artifact
//! assertions and major/minor negotiation ([`abi`]), //! selection on disk, manifest file validation, worker process management and
//! - `plugin.yaml` parsing and validation ([`manifest`]), //! capability dispatch live in the native host (`marqdo-host::plugin`). The
//! - target-triple artifact selection and sha256 verification ([`artifact`]), //! SDK consumes only this crate. There is no second wire encoding here: the
//! - `wire_version` 1 JSON request/response envelopes with typed value tags //! wire envelope reuses the single [`marqdo_value`] encoding.
//! ([`wire`]),
//! - a native loader/invocation bridge built on `libloading` ([`loader`]),
//! - structured, serializable [`PluginError`]s ([`error`]).
//! //!
//! A C ABI is not a sandbox: native plugins run in-process and require an //! A C ABI is not a sandbox. A host that loads native code must separately make
//! explicit trust decision. This crate only validates and loads what the //! and enforce an explicit trust decision; this crate grants no capability.
//! caller already decided to trust; it never grants capabilities.
pub mod abi; pub mod abi;
pub mod artifact;
pub mod error; pub mod error;
pub mod loader;
pub mod manifest;
pub mod wire; pub mod wire;
pub mod worker;
pub use abi::result as result_code; pub use abi::result as result_code;
pub use abi::{ pub use abi::{
@@ -33,16 +25,7 @@ pub use abi::{
MqOwnedBytes, MqPluginApi, MqPluginEntryV1, MqPluginInvoke, MqRegisterFunctionFn, MqOwnedBytes, MqPluginApi, MqPluginEntryV1, MqPluginInvoke, MqRegisterFunctionFn,
MqRequestCapabilityFn, PluginMetadata, ABI_MAJOR, ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL, MqRequestCapabilityFn, PluginMetadata, ABI_MAJOR, ABI_MINOR, ABI_VERSION_STRING, ENTRY_SYMBOL,
}; };
pub use artifact::{
current_target_triple, is_valid_sha256_hex, sha256_bytes, sha256_file, verify_sha256_file,
HostTarget, TargetTriple,
};
pub use error::{ErrorKind, PluginError}; pub use error::{ErrorKind, PluginError};
pub use loader::{CapabilityHandler, LoadOptions, LoadedPlugin, RegisteredExport};
pub use manifest::{
AbiRequirement, Artifact, Export, PackageVersion, PluginInfo, PluginKind, PluginManifest,
KNOWN_CAPABILITIES,
};
pub use marqdo_value::Value; pub use marqdo_value::Value;
pub use wire::{ pub use wire::{
bool_from_value, int_from_value, text_from_value, to_wire_json, WireContext, WireErrorBody, bool_from_value, int_from_value, text_from_value, to_wire_json, WireContext, WireErrorBody,
+1
View File
@@ -15,6 +15,7 @@ serde_json = { workspace = true }
marqdo-worker-ipc = { workspace = true } marqdo-worker-ipc = { workspace = true }
[dev-dependencies] [dev-dependencies]
marqdo-host-contract = { workspace = true }
marqdo-host = { path = "../marqdo-host" } marqdo-host = { path = "../marqdo-host" }
marqdo-sandbox = { path = "../marqdo-sandbox" } marqdo-sandbox = { path = "../marqdo-sandbox" }
marqdo-value = { path = "../marqdo-value" } marqdo-value = { path = "../marqdo-value" }
@@ -3,12 +3,13 @@
use std::path::Path; use std::path::Path;
use std::process::Command; use std::process::Command;
use marqdo_host::{Capabilities, Host, StdHost}; use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::{ExecutionContext, Host};
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
use marqdo_value::{ErrorCategory, Value}; use marqdo_value::{ErrorCategory, Value};
fn context() -> marqdo_host::ExecutionContext { fn context() -> ExecutionContext {
marqdo_host::ExecutionContext::new("test".to_string(), None) ExecutionContext::new("test".to_string(), None)
} }
fn handle(value: Value) -> marqdo_value::ResourceHandle { fn handle(value: Value) -> marqdo_value::ResourceHandle {
+2 -1
View File
@@ -13,7 +13,7 @@ marqdo-span = { workspace = true }
marqdo-value = { workspace = true } marqdo-value = { workspace = true }
marqdo-ir = { workspace = true } marqdo-ir = { workspace = true }
marqdo-expression = { workspace = true } marqdo-expression = { workspace = true }
marqdo-host = { workspace = true } marqdo-host-contract = { workspace = true }
num-bigint = { workspace = true } num-bigint = { workspace = true }
num-rational = { workspace = true } num-rational = { workspace = true }
num-traits = { workspace = true } num-traits = { workspace = true }
@@ -21,6 +21,7 @@ thiserror = { workspace = true }
[dev-dependencies] [dev-dependencies]
marqdo-host = { workspace = true }
marqdo-frontend = { workspace = true } marqdo-frontend = { workspace = true }
marqdo-sandbox = { workspace = true } marqdo-sandbox = { workspace = true }
tempfile = { workspace = true } tempfile = { workspace = true }
+1 -1
View File
@@ -6,7 +6,7 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use marqdo_host::{HostOp, ResourceRead}; use marqdo_host_contract::{HostOp, ResourceRead};
use marqdo_ir::builtins::Builtin; use marqdo_ir::builtins::Builtin;
use marqdo_ir::Resource; use marqdo_ir::Resource;
use marqdo_span::Span; use marqdo_span::Span;
+1 -1
View File
@@ -3,7 +3,7 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use marqdo_expression::{BinaryOp, Expr, RecordEntry}; use marqdo_expression::{BinaryOp, Expr, RecordEntry};
use marqdo_host::{ use marqdo_host_contract::{
ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead, ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead,
RuntimeObservation, RuntimeObservation,
}; };
+1 -1
View File
@@ -3,7 +3,7 @@
//! The interpreter is Marqdo's own execution engine: expressions, scoping, //! The interpreter is Marqdo's own execution engine: expressions, scoping,
//! calls, branches, loops and returns are evaluated here, never by translating //! calls, branches, loops and returns are evaluated here, never by translating
//! to Python or another language. Every side effect goes through //! to Python or another language. Every side effect goes through
//! [`marqdo_host::Host`]; prose never reaches this layer because it is absent //! [`marqdo_host_contract::Host`]; prose never reaches this layer because it is absent
//! from the IR. //! from the IR.
mod builtins_impl; mod builtins_impl;
+2 -1
View File
@@ -1,6 +1,7 @@
//! End-to-end interpreter tests: Markdown source → frontend IR → execution. //! End-to-end interpreter tests: Markdown source → frontend IR → execution.
use marqdo_host::{Capabilities, Host, StdHost}; use marqdo_host::{Capabilities, StdHost};
use marqdo_host_contract::Host;
use marqdo_ir::{ModuleId, Program}; use marqdo_ir::{ModuleId, Program};
use marqdo_runtime::{run, run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value}; use marqdo_runtime::{run, run_with_limits, EvaluatedArg, MemoryLimits, RuntimeError, Value};
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
+3 -2
View File
@@ -8,9 +8,10 @@ use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use marqdo_host::{ use marqdo_host::{
Capabilities, ObservationConfig, ObservationError, ObservationEvent, ObservationSink, Capabilities, ObservationConfig, ObservationError, ObservationEvent, ObservationSink, StdHost,
ParameterSource, StdHost, ValueState, ValueState,
}; };
use marqdo_host_contract::ParameterSource;
use marqdo_ir::{ModuleId, Program}; use marqdo_ir::{ModuleId, Program};
use marqdo_runtime::run; use marqdo_runtime::run;
use marqdo_sandbox::SandboxMode; use marqdo_sandbox::SandboxMode;
+9 -1
View File
@@ -1,10 +1,18 @@
# Marqdo CLI:语言规范、架构与开发总纲 # Marqdo CLI:语言规范、架构与开发总纲
> **Historical planning input (not current requirements).** This blueprint is an
> archived design baseline, not current architecture or status. The current
> architecture and dependency rules are
> [`architecture/CURRENT.md`](architecture/CURRENT.md) and
> [ADR-0071](adr/0071-engine-host-contract-boundary.md); executed state is
> [`STATUS.md`](STATUS.md). Do not derive a current gate or a crate split from
> this file.
>
> **状态**:架构基线提案 M0.5 / 新仓库实施蓝图(不是已实现功能清单) > **状态**:架构基线提案 M0.5 / 新仓库实施蓝图(不是已实现功能清单)
> **面向**:语言设计者、编译器/运行时开发者、插件开发者、贡献者及自动化编码智能体 > **面向**:语言设计者、编译器/运行时开发者、插件开发者、贡献者及自动化编码智能体
> **日期**:2026-11-20 > **日期**:2026-11-20
> **建议仓库位置**:`docs/DEVELOPMENT_BLUEPRINT.md` > **建议仓库位置**:`docs/DEVELOPMENT_BLUEPRINT.md`
> **优先阅读**:本文件 → `spec/` 形式规范 → `tests/conformance/` 金样 → 相关模块源码 > **优先阅读(归档语境)**:本文件 → `spec/` 形式规范 → `tests/conformance/` 金样 → 相关模块源码。当前入口请改用 `docs/architecture/CURRENT.md`、`docs/architecture/RFC-LANG-0002-unified-semantics.md` 与 `docs/developers/README.md`。
> **约定**:**[D]** 已确定的设计方向;**[P]** 本文提出的可实现细节,须经形式化测试和 ADR 批准后冻结;**[F]** 后期能力,不应阻塞首个独立运行版本。 > **约定**:**[D]** 已确定的设计方向;**[P]** 本文提出的可实现细节,须经形式化测试和 ADR 批准后冻结;**[F]** 后期能力,不应阻塞首个独立运行版本。
> **语言映射状态(2026-11-21,必读)**:本文档原本是 M0.5/M0.6 期的架构蓝图,其中关于 Markdown 程序角色的描述(旧映射:`Strong`=执行、`Emph`=返回、有序列表=分支、无序列表=循环、引用块=调用、首个独立 CodeSpan=签名)**已被废止,仅作为历史设计记录**。现行唯一语言语义权威是 > **语言映射状态(2026-11-21,必读)**:本文档原本是 M0.5/M0.6 期的架构蓝图,其中关于 Markdown 程序角色的描述(旧映射:`Strong`=执行、`Emph`=返回、有序列表=分支、无序列表=循环、引用块=调用、首个独立 CodeSpan=签名)**已被废止,仅作为历史设计记录**。现行唯一语言语义权威是
+53 -49
View File
@@ -75,46 +75,55 @@ The `spec/` tree contains only current contracts; retired specifications are in
Git history and tagged archives. The earlier release records below describe Git history and tagged archives. The earlier release records below describe
their tagged binaries and are not current protocol claims. their tagged binaries and are not current protocol claims.
## 0.11 Explicit stdlib Bundle input — issue #11 Phase A (unreleased) ## 0.12 Engine / Host Contract boundary — issue #13 (unreleased candidate)
Phase A lands the build-input boundary only: the stdlib production sources and This is an **internal architecture candidate**, not a release. The product
the debug source fallback are still in this repository, and Phase B (the version stays `3.0.0-rc.4`; no new tag or release claim is made. Baseline is
ecosystem-assembled Bundle, source removal and `std:` replacement) is **not** `master` at `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`; the PR records the exact
claimed. Executed candidate: candidate SHA and evidence is
`ab6b6b1a23ec064fbc7de943c52befca18142a56`; bundle source commit [`evidence/2026-11-26-issue-13-engine-host-boundary.md`](evidence/2026-11-26-issue-13-engine-host-boundary.md).
`2cbde54602c07f62a62f341400bc9cb4764a93f8`.
* `tools/stdlib/bundle-pin.json` pins `marqdo-stdlib@0.1.0` with tree digest Implemented in the candidate:
`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: - `marqdo-host-contract` owns the only Host trait/HostOp/ExecutionContext/
[`evidence/2026-11-26-issue-11-phase-a.md`](evidence/2026-11-26-issue-11-phase-a.md). ResourceRead and runtime observation facts. `marqdo-runtime` depends on it,
Runtime discovery is unchanged: `MARQDO_STDLIB_DIR` (invalid values still fail never on `marqdo-host` in normal/build edges. `marqdo-host` implements it and
hard), then `stdlib/` next to the executable, then the debug-only source has no reverse dependency on runtime/frontend/IR.
fallback. Phase B is gated on ecosystem issue #2 and the extension replacement - `tests/embedding` is a real independent Cargo workspace/lock consumer that
evidence named by issue #11. builds without the native host, executes the real Markdown→frontend→IR→runtime
path with real fuel/stack/deadline/memory limits and explicit effect
refusals, and matches a real CLI invocation on the same `.mq.md` for `Int` and
structural values.
- `marqdo-plugin-abi` is a contract crate only (C ABI, wire, errors);
manifest/artifact validation, `dlopen` and worker process live in
`marqdo-host::plugin`. `marqdo-plugin-sdk` transitively carries no loader,
worker, host or sandbox dependency.
- `tests/sdk-plugin` builds a third-party plugin with only the public SDK; the
real CLI loads/invokes it with explicit trust/grant and rejects a tampered
artifact digest.
- Dependency direction is enforced from Cargo metadata by
`tools/ci/check_dependency_boundaries.py` (with negative unit cases) and
`cargo test -p marqdo-cli --test architecture_boundaries`.
- The current architecture/developer entry and ADR-0071 record the
**keep-in-workspace** repository decision; no empty candidate repository was
created.
Executed in this environment (Linux x86_64, Rust 1.100): formatting, clippy,
locked workspace tests (**636 passed / 0 failed / 2 ignored**;
baseline `4bbefc9` 633 passed / 0 failed / 2 ignored, so no regression), docs/architecture gates, dependency gate, engine
differential gate and SDK gate PASS. The Windows GNU cross-target compile check
passes; it is not a native Windows runtime claim. Woodpecker PR pipeline #101
for code SHA `9b4f0a0` is **success**, including the `build` step (release
archive from that SHA, archive smoke, frozen external conformance) and the
`minimum-rust` lane; that is same-candidate CI evidence, not a release tag.
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.
## 0.10 Closed public Analysis boundary — issue #10 (RC.4 released) ## 0.10 Closed public Analysis boundary — issue #10 (RC.4 released)
@@ -397,9 +406,6 @@ ownership / core resource kinds), ADR-0063 (foreign F-A). Executed evidence:
recompute both digests with the runtime algorithm and fail on mismatch; smoke 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 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. 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 - **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 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 path; all six core kinds are rejected as a provider name and as a declared kind
@@ -727,11 +733,9 @@ 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 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 host formatter. `tools/pack-stdlib.py` additionally emits a byte-deterministic
offline archive + descriptor as an extraction-ready artifact offline archive + descriptor as an extraction-ready artifact
([evidence](evidence/2026-11-20-stdlib-package.md)). Issue #11 Phase A now ([evidence](evidence/2026-11-20-stdlib-package.md)). The stdlib intentionally
consumes the Bundle through one explicit `--stdlib-dir` and one pinned stays in this repository for now (ADR-0039); extraction is a future option
identity (ADR-0070, §0.11); the production sources still stay in this when size/release cadence requires it, not a pending gate.
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 streams (RFC-CM CM-A06, ADR-0025/0026/0040): opaque host-issued
`Resource` handles with `resource.open/read/write/close`; bytes move only `Resource` handles with `resource.open/read/write/close`; bytes move only
through `Memory`; stdin is read-only over one shared run cursor; stdout and through `Memory`; stdin is read-only over one shared run cursor; stdout and
@@ -746,11 +750,11 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
- Test and documentation migration (review RFC-CM P0/P2): - Test and documentation migration (review RFC-CM P0/P2):
`crates/cli/tests/docs_consistency.rs` pins one current overview, the `crates/cli/tests/docs_consistency.rs` pins one current overview, the
status/index links and SHA-pinned evidence; `crates/cli/tests/architecture_boundaries.rs` status/index links and SHA-pinned evidence; `crates/cli/tests/architecture_boundaries.rs`
pins the workspace graph, `marqdo-runtime -> marqdo-host`, the bundled stdlib pins the workspace graph, `marqdo-runtime -> marqdo-host` (historical at that
digest and the stdio/file/TCP endpoints; `crates/cli/tests/stdlib_product.rs` 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`) 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` resolved from the pinned through `std:` imports over `stdlib/tests/*.mq.md`. `tools/pack-stdlib.py`
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 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: `0d40de7`; later docs-only commits keep code/test bytes identical. Evidence:
[`docs-and-test-migration`](evidence/2026-11-21-docs-and-test-migration.md). [`docs-and-test-migration`](evidence/2026-11-21-docs-and-test-migration.md).
@@ -1,123 +0,0 @@
# 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.
@@ -0,0 +1,156 @@
# ADR-0071 — Engine / Host Contract / Native Host / CLI boundaries
Status: **Accepted** for the pre-stable 3.0 line (2026-11-26).
Supersedes the historical review-RFC position that a Host contract crate is a
second-step, optional move. It does not supersede the language contract
(ADR-0052 / RFC-LANG-0002), the resource/operation ownership rules (ADR-0062),
the foreign F-A boundary (ADR-0063), the single-contract policy (ADR-0068) or
the explicit stdlib Bundle build input (ADR-0070 where landed). It replaces only
the old architecture-gate constraints that asserted `marqdo-runtime ->
marqdo-host` and a frozen crate count.
## Context
Issue #13 audited the tree at `4bbefc9…` and found:
- the runtime linked the native host (`marqdo-host`) even though the interpreter
already accepted `&mut dyn Host`;
- the `Host` trait, `HostOp` and `StdHost` lived in one module, and
`ResourceRead` sat beside real file/TCP/TLS implementations;
- the plugin ABI crate contained the C contract, the wire envelope, manifest
validation, artifact selection, `dlopen` and the worker process, so the
third-party SDK transitively carried execution-side dependencies;
- old architecture gates froze sixteen crate names and the
runtime-to-native-host edge, so the intended boundary could not be tested;
- historical planning documents competed with the current overview as a source
of truth.
The same audit fixed the scope: one language implementation, one contract per
public boundary, no second interpreter, no new runtime protocol, no mandatory
remote repository split, and no empty candidate repositories. Missing
independent-consumer evidence means "keep in the workspace" is the correct
repository decision.
## Decision
### Responsibilities
| Layer | Owns | Must not own |
|---|---|---|
| Engine | Span, Value, expression, the one Markdown profile, IR, frontend mapping/static binding, Runtime evaluation and `Memory`, and the neutral Host contract | concrete OS I/O, sandbox launch, plugin loading, project filesystem, CLI commands |
| `marqdo-host-contract` | `Host` trait, `HostOp`, `ExecutionContext`, `ResourceRead`, `FrameId`, `ParameterSource`, `LoopTransfer`, `RuntimeObservation` | native implementation, grant policy, the public Observation wire encoding, any wire/RPC protocol |
| Native Host (`marqdo-host` and its sandbox/foreign support crates) | capability broker, resources and handles, OS adapters, budgets/deadlines, observation sink, trusted plugin/provider/foreign execution | language parsing/evaluation, a second static binder, CLI projection |
| `marqdo-plugin-abi` | C ABI v1 layout/assertions, wire envelope and protocol errors | `dlopen`, worker/process management, artifact/manifest file execution, capability grants |
| `marqdo-host::plugin` | manifest/artifact validation, native loading, worker process, invocation dispatch | a second ABI or wire definition |
| `marqdo-plugin-sdk` | third-party developer helpers over the public contract | host, loader, CLI, worker execution, sandbox |
| CLI | arguments, single `project_prepare`, command routing, product Analysis/Observation projection, Tool install/dispatch, Host+Runtime assembly | language evaluation, domain algorithms, a second binding path |
### Dependency rules
- `marqdo-runtime -> marqdo-host-contract` only. The engine crates must not reach
`marqdo-host`, sandbox, foreign, plugin ABI/SDK, worker, package, CLI,
`libloading`, `rustls` or other native/domain dependencies on normal or build
edges.
- `marqdo-host-contract -> marqdo-value, marqdo-span` only.
- The native host may implement the contract and consume the public ABI, but it
must not depend back on runtime, frontend, IR or the CLI.
- The CLI is the only composition root allowed to combine engine + native host +
package. `check`/`inspect` never load a native library, start a worker or
access the network.
- `marqdo-plugin-sdk` consumes only `marqdo-plugin-abi`; it must not depend on a
loader, host, worker process, sandbox or CLI.
- There is no second `Host`/`HostOp`, no second Value encoding, no
`EngineValue`/`HostValue`/`WireIR`, no HTTP/RPC/JSON handshake for the
engine-to-host edge and no `legacy` feature. The Rust trait is an internal
compile-time interface inside one codebase.
### Invariants preserved (not moved, not weakened)
- Fuel, stack depth, deadline, output budget and `Memory` limits stay owned and
checked exactly where they were; replacing the host must not remove a check.
The contract carries the calls, not platform-neutral defaults that silently
grant unlimited budgets.
- Capability grants, resource identity/handles, cleanup, provider registration,
strict isolation, plugin trust, foreign supervision and observation privacy
stay owned by the native host and CLI. `check`/`inspect` stay non-executing.
- Static binding remains single: one registry, one `bind_program_calls`, one
`CallBindingTable`; the runtime never re-resolves names.
- Public protocols are unchanged: Analysis revision 3, Observation revision 1,
Tool revision 1, Plugin ABI 1.0, Value Wire 1, Provider v2, lock v4. Moving
Rust modules is not a protocol change.
- Stdlib runtime contract is unchanged. Phase A/B of issue #11/#12 remain a
separate delivery; the CLI does not gain a second Bundle format or a dev
fallback authority.
### Repository decision
The Engine and Native Host stay in this workspace. Issue #13 §9.2 admission is
not met: there is no real external Engine consumer or independent platform
maintainer, and an empty candidate repository would be a prohibited boundary
violation. This ADR records **keep in workspace** as the legal conclusion and
names the reopening conditions in `docs/architecture/CURRENT.md` §7.
The plugin SDK's physical move is a follow-up: the contract is decoupled now,
and the move requires a clean-directory build against a fixed contract revision
(issue #13 S07/S08). No gitlink/submodule or empty `marqdo-cli-*` repository is
created by this ADR.
## Verification
The acceptance gates are executable, not documentary:
- `tools/ci/check_dependency_boundaries.py` reads Cargo metadata for the
workspace and the independent consumer, checks the reviewed crate allowlist and
the forbidden transitive edges, and is itself covered by
`tools/ci/test_dependency_boundaries.py` negative cases.
- `tests/embedding` is a separate workspace and lock file; it executes a real
`.mq.md` through Markdown → frontend → static binding → runtime with a bounded
test host, and rejects fuel/stack/deadline/memory/resource violations.
- `tools/ci/check_engine_boundary.py` builds and runs that consumer, builds the
real CLI, executes the same file and compares terminal Value Wire results, and
checks the runtime build tree.
- `tools/ci/check_plugin_sdk.py` builds the SDK fixture with the public SDK and
loads it through the real CLI with explicit trust/grant, then rejects a
tampered artifact digest.
- `cargo test -p marqdo-cli --test architecture_boundaries` keeps the semantic
gates (single Host trait, plugin contract split, engine-only consumer, reviewed
HostOp/Value/builtin/resource-operation catalogues) and the existing security
and product checks.
- Evidence for the candidate commit lives in
`docs/evidence/2026-11-26-issue-13-engine-host-boundary.md` and
`docs/STATUS.md`. Platform lanes not executed here stay `UNVERIFIED`; no old
release evidence is reused as a new PASS.
## Rejected alternatives
- **Create `marqdo-engine`/`marqdo-host` remote repositories now.** No real
consumer, no ownership/release boundary, prohibited empty candidates; would
also create a cross-repository atomic-semantics tax.
- **Keep the runtime linked to `marqdo-host` and only rename the crate.** Does
not close the dependency edge; an embedded consumer would still link native
TLS, loading and process code.
- **Move the whole `observe` module or CLI projection into the contract.** The
interpreter needs only the emitted facts; the sink, redaction and public
envelope belong to the host/CLI, and moving them would create a second
protocol centre.
- **Leave manifest/artifact in the ABI crate.** The SDK would transitively keep
`serde_yaml`/digest/native-adjacent code and the contract crate would again own
execution-side choices.
- **Add a compatibility re-export of the old `marqdo_host::{Host, ...}` paths.**
Creates a second active path; all in-tree consumers are updated atomically.
- **Loosen the old gates instead of replacing them.** Security, product,
protocol and negative tests are retained; only the frozen crate-name and
runtime-to-native-host assertions are replaced by the responsibility graph.
## Consequences
- An independent consumer can build and compute without the native host or CLI.
- Adding a host capability does not change engine code; adding an engine semantic
change does not change host code.
- The workspace gains one small contract crate and one plugin module move; crate
count is explicitly not a KPI.
- Unfinished ecosystem work (stdlib Phase B, SDK physical repository, regex/
compression migration, foreign F-B, WASM probe, Windows/macOS/strict evidence)
remains open and honestly recorded; none of it is required to close the core
M0–M4 boundary work.
+3 -3
View File
@@ -70,6 +70,6 @@ Files: `0001`–`0050`, plus:
pre-stable public boundary, replaced in place; pre-stable public boundary, replaced in place;
* [0069](0069-public-analysis-boundary.md) — one public Analysis projection for * [0069](0069-public-analysis-boundary.md) — one public Analysis projection for
independent document, lint and knowledge consumers. independent document, lint and knowledge consumers.
* [0070](0070-explicit-stdlib-bundle-build-input.md) — Phase A of the stdlib * [0071](0071-engine-host-contract-boundary.md) — Engine / Host Contract /
extraction: one required `--stdlib-dir` build input, one pinned Bundle Native Host / CLI responsibilities, dependency rules, plugin ABI contract split
identity for tests/perf/release CI; runtime contracts unchanged. and the keep-in-workspace repository decision.
+83 -16
View File
@@ -9,6 +9,51 @@ replace `spec/` or a recorded test log.
- This is the **single current overview**. Do not add a second running "current state" file; - This is the **single current overview**. Do not add a second running "current state" file;
update this file, `docs/STATUS.md` and an evidence file together. update this file, `docs/STATUS.md` and an evidence file together.
## Engine / Host Contract / Native Host boundary (issue #13, ADR-0071)
The language engine is independent of every concrete native platform
implementation. `marqdo-host-contract` owns the only side-effect interface the
runtime knows (`Host`, `HostOp`, `ExecutionContext`, `ResourceRead` and the
runtime observation facts); `marqdo-host` implements it with capabilities,
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.
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
Engine consumer outside the in-repo acceptance fixture, and no independent
platform maintainer. A candidate empty `marqdo-engine`/`marqdo-host` repository
would violate the issue's boundary conditions. The decision and its reopening
conditions are recorded in [ADR-0071](../adr/0071-engine-host-contract-boundary.md).
## Workspace crate responsibility map
This is the reviewed allowlist for workspace members. A new crate must be added
here, in `tools/ci/check_dependency_boundaries.py`, and with its dependency edges
in the same change.
| Crate | Layer | Responsibility |
|---|---|---|
| `marqdo-span` | Engine | UTF-8 position and diagnostic base types |
| `marqdo-value` | Engine | `Value`, `RuntimeError`, the one Value Wire encoding |
| `marqdo-expression` | Engine | Expression grammar |
| `marqdo-markdown` | Engine | The only Markdown profile and AST |
| `marqdo-ir` | Engine | IR, function/binding identity, builtin inventory |
| `marqdo-frontend` | Engine | Document mapping, signatures, static binding |
| `marqdo-runtime` | Engine | Evaluator, control flow and `Memory` |
| `marqdo-host-contract` | Engine boundary | Neutral `Host` trait and runtime observation facts |
| `marqdo-host` | Native Host | Capabilities, resources, OS adapters, plugin loader and trusted execution |
| `marqdo-sandbox` | Native Host support | OS isolation probe and strict launch |
| `marqdo-foreign` | Native Host support | Controlled one-shot foreign kernels (F-A) |
| `marqdo-plugin-abi` | Public contract | C ABI v1 layout, wire envelope and protocol errors |
| `marqdo-plugin-sdk` | Public contract consumer | Third-party plugin development helpers |
| `marqdo-worker-ipc` | Shared plumbing | One bounded worker frame transport |
| `marqdo-provider-worker` | Shipped worker | Provider helper process |
| `marqdo-package` | Product support | Project manifest, lock and dependency resolution |
| `marqdo-cli` | Composition root | Arguments, prepare, commands, product projection |
> **Language contract and implementation.** The language contract is > **Language contract and implementation.** The language contract is
> [RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) (adopted by ADR-0052) and > [RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) (adopted by ADR-0052) and
> `spec/mapping.md`. The frontend, `marqdo-expression`, IR lowering, runtime and > `spec/mapping.md`. The frontend, `marqdo-expression`, IR lowering, runtime and
@@ -140,11 +185,8 @@ Layer rules:
or a third-party plugin path. or a third-party plugin path.
2. The platform layer owns I/O, clocks, entropy, sockets and file handles. It must 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. not own JSON parsing, text formatting or memory allocation policy.
3. The stdlib is `.mq.md` and ships in this repository during Phase A of 3. The stdlib is `.mq.md` and ships in this repository. New ordinary algorithms
issue #11. New ordinary algorithms go to `stdlib/` + tests + docs; they do go to `stdlib/` + tests + docs; they do not become Rust builtins.
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 4. The CLI selects inputs, resolves configuration, assembles the host and routes
human/machine output. It is not a semantic policy centre. human/machine output. It is not a semantic policy centre.
5. Callable Plugin and Resource Provider share one registry/authorization/audit 5. Callable Plugin and Resource Provider share one registry/authorization/audit
@@ -159,11 +201,14 @@ Layer rules:
Current Rust dependency edges (documented, not proposed): Current Rust dependency edges (documented, not proposed):
```text ```text
marqdo-cli -> marqdo-runtime -> marqdo-host marqdo-cli -> marqdo-runtime -> marqdo-host-contract
marqdo-cli -> marqdo-package, marqdo-sandbox, marqdo-frontend, ... marqdo-cli -> marqdo-host, marqdo-package, marqdo-sandbox, marqdo-frontend, ...
marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value
marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox, marqdo-worker-ipc marqdo-host-contract -> marqdo-value, marqdo-span
marqdo-plugin-abi -> marqdo-worker-ipc marqdo-host -> marqdo-host-contract, marqdo-plugin-abi, marqdo-foreign,
marqdo-sandbox, marqdo-worker-ipc
marqdo-plugin-abi -> marqdo-value, serde/serde_json (contract only)
marqdo-plugin-sdk -> marqdo-plugin-abi (contract only)
marqdo-provider-worker -> marqdo-worker-ipc marqdo-provider-worker -> marqdo-worker-ipc
``` ```
@@ -173,10 +218,13 @@ copy of bounded worker framing, deadlines and process teardown
host, the plugin ABI, or a worker binary; sharing plumbing must not share host, the plugin ABI, or a worker binary; sharing plumbing must not share
capabilities. Foreign kernels and CLI Tools stay outside it. capabilities. Foreign kernels and CLI Tools stay outside it.
`marqdo-runtime -> marqdo-host` is the current direction. Do not add a second `marqdo-runtime -> marqdo-host-contract` is the only engine-to-host edge. The
execution backend or a `marqdo-stdlib` crate by implication. A future embedded engine must never link `marqdo-host`, sandbox, foreign, plugin loading or the
runtime or a second backend needs the thin `ExecutionPort` contract described in the CLI in normal/build dependencies. The native host must not depend back on the
review RFC, not a new crate per provider. runtime/frontend/IR. `tools/ci/check_dependency_boundaries.py` enforces the
transitive graph from Cargo metadata; `tests/embedding` proves a real
platform-neutral consumer. Do not add a second execution backend, a per-provider
crate, or a `marqdo-stdlib` crate by implication.
| Public contract | API (`.mq.md`) | State | Tests | | Public contract | API (`.mq.md`) | State | Tests |
|---|---|---|---| |---|---|---|---|
@@ -232,8 +280,9 @@ that a phase is complete.
| Priority | Gap | State | | 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 | **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 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 | Stdlib release is a bundle in this repo; extraction is deferred (ADR-0039) | accepted, keep in repo |
| P0 | Documentation drift between `STATUS.md`, the architecture index and the evidence | being fixed by this migration and the docs gate | | 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 | | P1 | `std:fs/file` read/write/copy, metadata/directory, append/read_at/walk are implemented; watch and binary offset reads remain open | open |
| P1 | No file watch or binary `read_at` | open; future Resource Operation extension | | P1 | No file watch or binary `read_at` | open; future Resource Operation extension |
| P1 | JSON/CSV product parsers are implemented with depth bound and multi-value/multi-row; no incremental streaming parser | open | | P1 | JSON/CSV product parsers are implemented with depth bound and multi-value/multi-row; no incremental streaming parser | open |
@@ -271,7 +320,23 @@ that a phase is complete.
current contract, replace in place, reject retired inputs, no compatibility current contract, replace in place, reject retired inputs, no compatibility
path or version negotiation, and no version bump without a shape change. path or version negotiation, and no version bump without a shape change.
## 7. References ## 7. Repository decision and split admission
| Component | Decision for this round | Reopen condition (issue #13 §9.2) |
|---|---|---|
| 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) |
| 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.
## 8. References
- [Architecture index](README.md) — RFC/ADR/evidence history. - [Architecture index](README.md) — RFC/ADR/evidence history.
- [Protocol convergence policy](PROTOCOL_CONVERGENCE_POLICY.md) — one-contract rules, anti-patterns and review checklist. - [Protocol convergence policy](PROTOCOL_CONVERGENCE_POLICY.md) — one-contract rules, anti-patterns and review checklist.
@@ -291,7 +356,9 @@ that a phase is complete.
- [ADR-0050: host regex extension](../adr/0050-host-regex-extension.md) — accepted project-mode groups/alternation/captures. - [ADR-0050: host regex extension](../adr/0050-host-regex-extension.md) — accepted project-mode groups/alternation/captures.
- [ADR-0052: byte-exact HTTP framing](../adr/0051-byte-exact-http-framing.md) — accepted byte-list HTTP/1.1 parser/builder. - [ADR-0052: byte-exact HTTP framing](../adr/0051-byte-exact-http-framing.md) — accepted byte-list HTTP/1.1 parser/builder.
- [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. - [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) — review input for this migration. - [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.
- [Issue #13 engine/host evidence](../evidence/2026-11-26-issue-13-engine-host-boundary.md) — executed candidate commands and results.
- [RFC-EXT-0001](RFC-EXT-0001.md) — extensibility closure task specification (implementation status tracked here and in STATUS). - [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-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. - [ADR-0055: resource provider CLI v2](../adr/0055-resource-provider-cli-v2.md) — provider v2 manifest/worker CLI closure and trust boundary.
+8 -1
View File
@@ -8,6 +8,12 @@ input and evidence. It is not a second running-status page.
- Public-contract convergence rules and review checklist: - Public-contract convergence rules and review checklist:
[`PROTOCOL_CONVERGENCE_POLICY.md`](PROTOCOL_CONVERGENCE_POLICY.md) [`PROTOCOL_CONVERGENCE_POLICY.md`](PROTOCOL_CONVERGENCE_POLICY.md)
([ADR-0068](../adr/0068-single-current-public-contracts.md)). ([ADR-0068](../adr/0068-single-current-public-contracts.md)).
- **Current internal boundaries:** the Engine / Host Contract / Native Host /
CLI responsibilities, dependency edges, plugin ABI contract split and the
keep-in-workspace repository decision are in
[ADR-0071](../adr/0071-engine-host-contract-boundary.md) and
[`CURRENT.md`](CURRENT.md) §7. Issue #13 closure evidence lives in
[`../evidence/2026-11-26-issue-13-engine-host-boundary.md`](../evidence/2026-11-26-issue-13-engine-host-boundary.md).
- **Current language contract:** - **Current language contract:**
[`RFC-LANG-0002-unified-semantics.md`](RFC-LANG-0002-unified-semantics.md), [`RFC-LANG-0002-unified-semantics.md`](RFC-LANG-0002-unified-semantics.md),
adopted by [ADR-0052](../adr/0052-unified-markdown-semantics.md) and adopted by [ADR-0052](../adr/0052-unified-markdown-semantics.md) and
@@ -23,7 +29,7 @@ input and evidence. It is not a second running-status page.
| Document | Status | What it is | | Document | Status | What it is |
|---|---|---| |---|---|---|
| [Unified semantics RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) | **Adopted and implemented** | Single syntax: heading modes, unified payloads, keyword control flow, breaking migration and acceptance gates. | | [Unified semantics RFC-LANG-0002](RFC-LANG-0002-unified-semantics.md) | **Adopted and implemented** | Single syntax: heading modes, unified payloads, keyword control flow, breaking migration and acceptance gates. |
| [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) | **Review input (historical)** | Responsibility convergence, stdio/file/stream correctness, CLI/Host split and the migration order at the time. Its language examples predate RFC-LANG-0002. | | [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) | **Review input (historical)** | Responsibility convergence, stdio/file/stream correctness, CLI/Host split and the migration order at the time. Its language examples predate RFC-LANG-0002 and its "contract crate only later" position is superseded by ADR-0071. |
| [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Historical: superseded by Observation (ADR-0068)** | Its event vocabulary and privacy model fed the current [Observation](../../spec/observation.md) contract; the Execution Events v1 name/options are retired. | | [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Historical: superseded by Observation (ADR-0068)** | Its event vocabulary and privacy model fed the current [Observation](../../spec/observation.md) contract; the Execution Events v1 name/options are retired. |
| [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. | | [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. |
| [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. | | [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. |
@@ -77,6 +83,7 @@ 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 | | 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 | | 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 | | Stable core inventory and external gate | [0064](../adr/0064-stable-core-extension-boundary.md) | Accepted and wired into Linux CI |
| Engine / Host Contract / Native Host / CLI boundaries | [0071](../adr/0071-engine-host-contract-boundary.md) | Accepted and implemented by issue #13: runtime depends on the neutral contract, native host implements it, plugin ABI is contract-only, keep-in-workspace repository decision |
| Manifest-driven Resource Control | [0065](../adr/0065-resource-control-vnext.md) | Proposed | | Manifest-driven Resource Control | [0065](../adr/0065-resource-control-vnext.md) | Proposed |
| Structured Tasks and Channels | [0066](../adr/0066-structured-tasks-v1.md) | Proposed | | Structured Tasks and Channels | [0066](../adr/0066-structured-tasks-v1.md) | Proposed |
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication | | Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
+7 -18
View File
@@ -14,10 +14,8 @@
The default Docker pipeline runs on push and pull request. A fast `contract` The default Docker pipeline runs on push and pull request. A fast `contract`
lane exercises the public Analysis/Observation contracts through the real CLI 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 independent Python consumers; the full `test` lane runs the Rust gates
and the Windows cross-target compile check; `independent-build` exports the and the Windows cross-target compile check; `build` packages the archive, runs
commit without `stdlib/` and proves both shipped binaries still build and run a the from-archive smoke and the frozen external conformance suite.
language-only program; `build` packages the archive from the pinned stdlib
Bundle, runs the from-archive smoke and the frozen external conformance suite.
```text ```text
contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries): contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries):
@@ -26,31 +24,27 @@ contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries):
analysis_consumer / observation_consumer / validate_protocols analysis_consumer / observation_consumer / validate_protocols
stream==snapshot assertion (tools/ci/verify_observation_stream.py) stream==snapshot assertion (tools/ci/verify_observation_stream.py)
stale-Analysis rejection stale-Analysis rejection
dependency-direction gate (tools/ci/check_dependency_boundaries.py)
test (rust:1.100-bookworm, clippy/rustfmt, Node.js 22, MinGW, both binaries): 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 fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings cargo clippy --workspace --all-targets -- -D warnings
cargo build --locked -p marqdo-provider-worker cargo build --locked -p marqdo-provider-worker
cargo test --workspace --locked cargo test --workspace --locked
docs_consistency / architecture_boundaries / stdlib_product docs_consistency / architecture_boundaries / stdlib_product
stdlib_product again with MARQDO_TEST_STDLIB_BUNDLE + MARQDO_TEST_BUNDLE_PIN check_dependency_boundaries.py (Cargo-metadata responsibility graph)
check_engine_boundary.py (independent consumer build/run + CLI differential)
check_plugin_sdk.py (real third-party SDK plugin via the real CLI)
python3 -m unittest discover -s tools/ci -p "test_*.py" python3 -m unittest discover -s tools/ci -p "test_*.py"
rustup target add x86_64-pc-windows-gnu rustup target add x86_64-pc-windows-gnu
cargo check --workspace --all-targets --target 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): minimum-rust (rust:1.89-bookworm):
cargo check --locked --workspace --all-targets cargo check --locked --workspace --all-targets
build (depends on test, minimum-rust, contract): build (depends on test, minimum-rust, contract):
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
python3 tools/stdlib/bundle.py; package --stdlib-dir stdlib --bundle-pin ... package the deterministic archive for $CI_COMMIT_SHA
from-archive smoke (tools/release/smoke.py) from-archive smoke (tools/release/smoke.py)
frozen external conformance (tools/ci/run_frozen_extensions.sh, 7/7) frozen external conformance (tools/ci/run_frozen_extensions.sh, 7/7)
``` ```
@@ -103,11 +97,6 @@ syntax; Debian bookworm's Node 18 fails those tests.
workspace tests so the provider CLI tests use the real helper, and adds a 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` `cargo check --workspace --all-targets --target x86_64-pc-windows-gnu`
compile gate (native Windows/macOS runtime lanes stay on the GitHub matrix). 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 * The Woodpecker **build** lane and the GitHub **release-candidate** lane build
`marqdo` **and** `marqdo-provider-worker` and package both as siblings; the `marqdo` **and** `marqdo-provider-worker` and package both as siblings; the
provider transport resolves only that sibling (no PATH fallback), so an provider transport resolves only that sibling (no PATH fallback), so an
+18
View File
@@ -25,6 +25,11 @@ Foreign wire v1, Provider manifest v2, lock v4 and markdown profile
## Recommended reading order ## Recommended reading order
0. [Current architecture](../architecture/CURRENT.md) and
[ADR-0071](../adr/0071-engine-host-contract-boundary.md) — the Engine /
Host Contract / Native Host / CLI responsibility map and dependency rules.
Read this before touching a crate boundary; the historical plans are not
current requirements.
1. [quickstart.md](quickstart.md) — install the archive and run the first 1. [quickstart.md](quickstart.md) — install the archive and run the first
project. project.
2. [libraries.md](libraries.md) — publish a pure `.mq.md` library and consume 2. [libraries.md](libraries.md) — publish a pure `.mq.md` library and consume
@@ -47,6 +52,19 @@ contracts are the pages above and `spec/`).
Normative contracts live in [`../../spec/`](../../spec/); this directory is a Normative contracts live in [`../../spec/`](../../spec/); this directory is a
task-oriented map, not a second specification. task-oriented map, not a second specification.
## Internal boundary changes
This page is for third-party consumers. If you change Marqdo CLI itself, the
internal boundary rules are in [ADR-0071](../adr/0071-engine-host-contract-boundary.md)
and [CURRENT.md](../architecture/CURRENT.md) §7. In short: the engine depends
only on `marqdo-host-contract`; the native host implements it; the plugin ABI
crate is a contract (no loader/worker); the CLI is the only assembly point.
Run `python3 tools/ci/check_dependency_boundaries.py`,
`python3 tools/ci/check_engine_boundary.py` and
`python3 tools/ci/check_plugin_sdk.py` with the Rust suits. Do not create an
empty candidate repository for a boundary; a split needs the evidence and a new
ADR.
## Baseline repository ## Baseline repository
The current implementation and release entry point is The current implementation and release entry point is
@@ -1,195 +0,0 @@
# 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,107 @@
# Evidence — issue #13 Engine / Host Contract boundary (candidate)
Date: 2026-11-26 (Asia/Shanghai)
Issue: <https://git.cflmy.cn/cflmy/marqdo-cli/issues/13>
Decision: [ADR-0071](../adr/0071-engine-host-contract-boundary.md)
Branch: `architecture/issue-13-engine-host-boundary`
Baseline: `master` at `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`
Candidate: the merge candidate built from this branch; the PR records the exact
source SHA. This file is not a release approval and does not reuse RC.4 evidence.
## Scope actually landed (M0–M3 core)
| Item | State |
|---|---|
| Neutral `marqdo-host-contract` crate (`Host`, `HostOp`, `ExecutionContext`, `ResourceRead`, `FrameId`, `ParameterSource`, `LoopTransfer`, `RuntimeObservation`) | **implemented** |
| `marqdo-runtime` depends on the contract, not `marqdo-host` | **implemented** (runtime test `marqdo-host` remains a dev-dependency only) |
| `marqdo-host` implements the contract; no reverse dependency on runtime/frontend/IR | **implemented** |
| Independent real consumer `tests/embedding` (own workspace + lock), Markdown→frontend→IR→runtime, bounded test host | **implemented and executed** |
| `marqdo-plugin-abi` reduced to the public contract (C ABI, wire, errors) | **implemented** |
| Loader/worker/manifest/artifact moved to `marqdo-host::plugin` | **implemented** |
| SDK consumes only the contract (no libloading/worker/host) | **implemented** |
| Real SDK plugin built and invoked by the real CLI; tampered digest rejected | **implemented and executed** |
| Dependency-direction gate from Cargo metadata + negative unit cases | **implemented** |
| Current architecture/doc entry, ADR, historical banners, status | **implemented** |
| New remote repository (`marqdo-cli-*`, engine/host) | **deliberately not created** — issue #13 §9.2 admission is not met; keep-in-workspace is recorded in ADR-0071/CURRENT.md §7 |
| Stdlib Bundle Phase B, SDK physical migration, regex/compression migration, foreign F-B | **not in this candidate**; separate issues/decisions, listed in `docs/STATUS.md` |
## Commands and results
All commands were run in this checkout with the repository-local Rust toolchain
(`rustc 1.100.0`, `cargo 1.100.0`) and `--offline` where the environment requires
the warm cache. The candidate source SHA is on the PR; do not copy these results
to a different commit.
| 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** across 74 test binaries (includes `docs_consistency`, `architecture_boundaries`, `stdlib_product`); baseline `4bbefc9` in a detached worktree is **633 passed / 0 failed / 2 ignored** (no regression; the candidate adds three architecture-boundary tests) |
| Architecture boundaries | `cargo test -p marqdo-cli --test architecture_boundaries --locked` | PASS (15) |
| Docs consistency | `cargo test -p marqdo-cli --test docs_consistency --locked` | PASS |
| Dependency gate | `python3 tools/ci/check_dependency_boundaries.py` | PASS |
| Dependency gate negative cases | `python3 -m unittest tools.ci.test_dependency_boundaries` / `python3 -m unittest discover -s tools/ci` | PASS (54 tool tests) |
| Engine independence and differential execution | `python3 tools/ci/check_engine_boundary.py` | PASS |
| Plugin SDK real consumption | `python3 tools/ci/check_plugin_sdk.py` | PASS |
| Existing product/conformance suites | included in workspace run; stdlib product suite additionally run | PASS |
Behavioral facts from the engine gate:
- the independent consumer returns `sum_to(10) = Int(55)` and a structural
`types(7)` map whose terminal Value Wire bytes equal a real CLI `call
--output json` on the same file;
- the consumer rejects real fuel exhaustion, stack-depth exceedance, expired
deadline, out-of-bounds `Memory` access, a host that grants no external effect
(`permission.denied`), and a host with no resource implementation
(`resource.unsupported`);
- `cargo tree -p marqdo-runtime -e normal,build` in the consumer graph has no
`marqdo-host`, sandbox, foreign or libloading/rustls dependency;
- `marqdo-plugin-sdk` normal tree contains only `marqdo-plugin-abi`,
`marqdo-value` and serialization primitives.
Behavioral facts from the SDK gate:
- `tests/sdk-plugin` builds with only `marqdo-plugin-sdk` as a path dependency;
- the real CLI loads it with `--trust-native-plugin` and
`--allow-plugin sdk.demo` and returns `Int 42`;
- a tampered `sha256` in `plugin.yaml` is rejected with an artifact/sha256
diagnostic.
## CI evidence (remote, same code SHA)
Woodpecker PR pipeline **#101** for commit
`9b4f0a08228e9932bf3b0a8c5cf80e0d04626ccb` finished **success** with every step
green: `clone`, `contract`, `test`, `minimum-rust`, `build`. The `build` step
builds the release binaries, packages the deterministic archive for
`$CI_COMMIT_SHA`, runs the from-archive smoke test and the frozen external
conformance suite, so C11/G05 get same-candidate CI evidence rather than an old
release claim. The first pipeline (#100) failed in one unrelated pre-existing
`provider_cli` test with `ETXTBSY` while executing a freshly copied binary; the
same tree passed on straight rerun (#101), so it is recorded as an environment
flake, not a candidate defect.
This evidence file was updated by a docs-only commit after that code SHA; code
and lock bytes are unchanged by it. The PR check list shows the final run.
## Not verified here (honest state)
| Item | State | Reason / owner |
|---|---|---|
| Minimum Rust 1.89 | **UNVERIFIED** locally | only Rust 1.100 is installed in this environment; the Woodpecker `minimum-rust` lane runs `cargo check --locked --workspace --all-targets` on `rust:1.89-bookworm` |
| Windows GNU cross-target compile | **PASS (cross-check only)** | `cargo check --workspace --all-targets --locked --target x86_64-pc-windows-gnu` finished successfully (pre-existing unrelated warnings); native Windows runtime and the GitHub/Woodpecker native lanes remain the actual platform gate |
| Windows/macOS native runtime | **UNVERIFIED** locally | no native runner here; existing GitHub/Woodpecker lanes remain the gate |
| `wasm32-unknown-unknown` Engine probe (E12) | **UNVERIFIED** | target std not installed and no network here; `cargo check -p marqdo-runtime --target wasm32-unknown-unknown` fails with `E0463: can't find crate for core/std`, i.e. a missing target toolchain rather than a forbidden native dependency. E01 is green, so no P0 violation is implied, but this is not a PASS |
| strict OS-isolation lane | **UNVERIFIED** | needs the disposable VM; `strict` remains fail-closed |
| Performance/RSS budget (G06) | **UNVERIFIED** | shared-node measurement is not valid evidence; no performance claim is made |
| Frozen external conformance / release archive (C11/G05) | **CI PASS at code SHA `9b4f0a0`** | Woodpecker pipeline #101 `build` step: release archive from that SHA, archive smoke, frozen external conformance, PASS. This is not a new release tag. |
| SDK physical repository, stdlib Phase B, regex/compression migration | **DEFERRED** | separate issues; see `docs/STATUS.md` |
## Boundary confirmation
- No new top-level CLI command, no `HostOp`/builtin/Value variant, no second
interpreter, no `legacy` feature, no compatibility re-export of removed
`marqdo_host::{Host, HostOp, ...}` paths.
- Public protocols and their revisions are unchanged. This evidence covers an
internal Rust boundary change, not a protocol migration.
- No remote repository was created or modified for this work beyond pushing the
candidate branch and PR; no empty candidate repository exists.
@@ -1,72 +0,0 @@
# 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.
+3 -6
View File
@@ -27,12 +27,9 @@ dominated by emulation and is not comparable with native or KVM.
## Tool ## Tool
`tools/perf/runner.py` (schema `marqdo.perf.v2`) builds one release binary, `tools/perf/runner.py` (schema `marqdo.perf.v2`) builds one release binary,
records its SHA256/Cargo.lock/rustc/source SHA, resolves one pinned stdlib records its SHA256/Cargo.lock/rustc/source SHA, verifies every workload's exact
Bundle (name, version, tree/alias digests, source commit) and passes it to every wire digest **before** timing, then reports warmups/samples, p50, p95, MAD,
workload as `MARQDO_STDLIB_DIR`, verifies every workload's exact wire digest CPU user/sys, peak RSS and the environment manifest. See
**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). [`tools/perf/README.md`](../tools/perf/README.md).
Rules enforced by the tool: Rules enforced by the tool:
+4 -11
View File
@@ -116,8 +116,7 @@ The archive is built deterministically from a clean tree at `SOURCE_SHA`:
version="$(cargo metadata --no-deps --format-version 1 --offline \ 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 -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)" 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) # dist/marqdo-<version>-x86_64-unknown-linux-gnu.tar.gz(+.sha256)
``` ```
@@ -129,15 +128,9 @@ and self-test), `LICENSE-APACHE`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md
artifacts so the examples run without a compiler) and `tests/consumers/`. artifacts so the examples run without a compiler) and `tests/consumers/`.
`RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`, `RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`,
`aliases_digest`, `file_count` and `files`, plus `stdlib.source` (kind, `aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests
repository, commit, path) when `--bundle-pin` is given. `--stdlib-dir` is a with the same canonical algorithm as the runtime and refuses to package a mismatch
required build input and names the unpacked Bundle root; `package.py` verifies with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04).
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. The `protocols.analysis` field identifies the default Analysis major.
`protocols.analysis_versions` lists all majors the archive can emit. `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 The archive smoke exercises a published example and a consumer for each major. The bundled stdlib is a
+1 -1
View File
@@ -91,7 +91,7 @@ wire response: {"wire_version":1,"kind":"response",
``` ```
The integration test The integration test
`crates/marqdo-plugin-abi/tests/loader_unix.rs` compiles this exact `crates/marqdo-host/tests/loader_unix.rs` compiles this exact
`solver.c` with `cc -shared -fPIC`, loads it with `libloading`, and round-trips `solver.c` with `cc -shared -fPIC`, loads it with `libloading`, and round-trips
the request. It duplicates the compilation with the request. It duplicates the compilation with
`-DMQ_SOLVER_REPORT_ABI_MAJOR=2` to prove that a wrong ABI major fails the `-DMQ_SOLVER_REPORT_ABI_MAJOR=2` to prove that a wrong ABI major fails the
View File
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
{"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
+3 -3
View File
@@ -155,7 +155,7 @@ plugin:
sha256: "<64 lowercase hex>" sha256: "<64 lowercase hex>"
``` ```
Validation (`crates/marqdo-plugin-abi/src/manifest.rs::PluginManifest::validate`): Validation (`crates/marqdo-host/src/plugin/manifest.rs::PluginManifest::validate`):
* `name`: dotted segments, each starting with a lowercase ASCII letter and * `name`: dotted segments, each starting with a lowercase ASCII letter and
containing only lowercase letters, digits, `-`/`_`; ≤ 256 bytes; package containing only lowercase letters, digits, `-`/`_`; ≤ 256 bytes; package
@@ -199,7 +199,7 @@ filesystem access (artifact verification is a separate step).
## 6. Loader lifecycle (host side) ## 6. Loader lifecycle (host side)
`crates/marqdo-plugin-abi/src/loader.rs::LoadedPlugin::open_with`: `crates/marqdo-host/src/plugin/loader.rs::LoadedPlugin::open_with`:
1. `manifest.validate()`; 1. `manifest.validate()`;
2. require `kind == native` (otherwise `plugin_kind_not_loadable_in_process`); 2. require `kind == native` (otherwise `plugin_kind_not_loadable_in_process`);
@@ -445,7 +445,7 @@ it (`cc -shared -fPIC -I include`) and rewrites the `sha256` in `plugin.yaml`
`examples/plugin-demo/README.md` walks through the security model, build, `examples/plugin-demo/README.md` walks through the security model, build,
inspect and call flow. inspect and call flow.
The integration test `crates/marqdo-plugin-abi/tests/loader_unix.rs` compiles The integration test `crates/marqdo-host/tests/loader_unix.rs` compiles
this exact `solver.c` with `cc`, loads it with `libloading`, round-trips a wire this exact `solver.c` with `cc`, loads it with `libloading`, round-trips a wire
request, and rebuilds it with `-DMQ_SOLVER_REPORT_ABI_MAJOR=2` to prove that a request, and rebuilds it with `-DMQ_SOLVER_REPORT_ABI_MAJOR=2` to prove that a
wrong ABI major fails the load. It also covers a missing entry symbol, missing wrong ABI major fails the load. It also covers a missing entry symbol, missing
+2 -2
View File
@@ -15,7 +15,7 @@ Normative implementation:
| Observation events (effects included) | `crates/marqdo-host/src/observe.rs`, `crates/cli/src/observation.rs` | | Observation events (effects included) | `crates/marqdo-host/src/observe.rs`, `crates/cli/src/observation.rs` |
| Foreign adapter | `crates/marqdo-host/src/kernels.rs` | | Foreign adapter | `crates/marqdo-host/src/kernels.rs` |
| Foreign child processes | `crates/marqdo-foreign/src/lib.rs` | | Foreign child processes | `crates/marqdo-foreign/src/lib.rs` |
| Plugin loading / in-process plugin calls | `crates/marqdo-host/src/host.rs` (`load_plugin`, `op_plugin_invoke`), `crates/marqdo-plugin-abi/src/loader.rs` | | Plugin loading / in-process plugin calls | `crates/marqdo-host/src/host.rs` (`load_plugin`, `op_plugin_invoke`), `crates/marqdo-host/src/plugin/loader.rs` |
| CLI flags and capability construction | `crates/cli/src/main.rs`, `crates/cli/src/commands.rs` | | CLI flags and capability construction | `crates/cli/src/main.rs`, `crates/cli/src/commands.rs` |
## 1. Modes ## 1. Modes
@@ -331,7 +331,7 @@ inheritance is future work (ADR-0021).
* The only plugin transport implemented in this build is **in-process native * The only plugin transport implemented in this build is **in-process native
loading** (`libloading`) after `manifest.validate()`, exact target-triple loading** (`libloading`) after `manifest.validate()`, exact target-triple
artifact resolution, sha256 verification, ABI negotiation and export artifact resolution, sha256 verification, ABI negotiation and export
metadata cross-checking (`crates/marqdo-plugin-abi/src/loader.rs`). metadata cross-checking (`crates/marqdo-host/src/plugin/loader.rs`).
* Loading requires **three** independent things: * Loading requires **three** independent things:
1. `--plugin <manifest-or-dir>` names the plugin; 1. `--plugin <manifest-or-dir>` names the plugin;
2. `--trust-native-plugin` is an explicit unsafe trust decision; 2. `--trust-native-plugin` is an explicit unsafe trust decision;
+4 -18
View File
@@ -32,6 +32,8 @@ tests/
│ ├── *.mq.md 49 × compile-time hard-error fixtures + *.expected.json │ ├── *.mq.md 49 × compile-time hard-error fixtures + *.expected.json
│ ├── warnings/ 2 × warning-model/control fixtures + *.expected.json │ ├── warnings/ 2 × warning-model/control fixtures + *.expected.json
│ └── runtime/ 20 × runtime-error fixtures + *.expected.json │ └── runtime/ 20 × runtime-error fixtures + *.expected.json
├── embedding/ Independent Engine consumer (own workspace + lock)
├── sdk-plugin/ Third-party plugin built only with the public Rust SDK
└── README.md this file └── README.md this file
``` ```
@@ -50,27 +52,11 @@ Rust harnesses (all in `crates/cli/tests/`):
| `conformance_semantics.rs` | Each semantic fixture compiles through `marqdo_frontend`, is assembled into `marqdo_ir::Program` and executed with `marqdo_runtime` + `marqdo_host::StdHost`; returned wire value and program stdout match. | | `conformance_semantics.rs` | Each semantic fixture compiles through `marqdo_frontend`, is assembled into `marqdo_ir::Program` and executed with `marqdo_runtime` + `marqdo_host::StdHost`; returned wire value and program stdout match. |
| `negative.rs` | Current-syntax diagnostics are **hard errors** (never prose fallbacks): exact sorted `sem.*`/`symbol.*`/`call.*`/`frontmatter.*` code lists, the `sem.inferred_signature` warning model with inert-knowledge controls, and runtime error codes — each asserted in its own suite. | | `negative.rs` | Current-syntax diagnostics are **hard errors** (never prose fallbacks): exact sorted `sem.*`/`symbol.*`/`call.*`/`frontmatter.*` code lists, the `sem.inferred_signature` warning model with inert-knowledge controls, and runtime error codes — each asserted in its own suite. |
| `properties.rs` | Blueprint §14.2 prose invariance: inserting/removing pure narration paragraphs never changes the executable function IR (modulo source spans) and diagnostics stay error-free. | | `properties.rs` | Blueprint §14.2 prose invariance: inserting/removing pure narration paragraphs never changes the executable function IR (modulo source spans) and diagnostics stay error-free. |
| `embedding/` + `tools/ci/check_engine_boundary.py` | Independent Cargo consumer builds without the native host, executes the real Markdown→frontend→IR→runtime path with bounded budgets and refusal cases, and its terminal Value Wire result matches a real CLI invocation on the same file (issue #13 / ADR-0071). |
| `sdk-plugin/` + `tools/ci/check_plugin_sdk.py` | A third-party plugin builds against only the public SDK, is loaded/invoked by the real CLI with explicit trust/grant, and a tampered artifact digest is rejected. |
| `integration_cli.rs` | Real CLI contract: `init`, `check`, `run`, `call`, `inspect`, `fmt`, multi-module imports/cycles, `lock`/`sync --locked`, plugin inspection and explicitly trusted plugin invocation. | | `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. | | `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 ## Running
Use the workspace cargo cache/target as documented in `AGENTS.md`: Use the workspace cargo cache/target as documented in `AGENTS.md`:
+543
View File
@@ -0,0 +1,543 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "caseless"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b6fd507454086c8edfd769ca6ada439193cdb209c7681712ef6275cccbfe5d8"
dependencies = [
"unicode-normalization",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "comrak"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d981d666dca19afb3cc090dc7c381560cb8ba76582dda6e2c14686ff39fd547f"
dependencies = [
"caseless",
"entities",
"finl_unicode",
"memchr-n",
"phf",
"phf_codegen",
"rustc-hash",
"smallvec",
"typed-arena",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "entities"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fearless_simd"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "629c9d6b6f30b5604089e0980f4d924a013aacb1654a6cdf5d3d852224f68651"
[[package]]
name = "fearless_simd_macros"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e91d94c6885390b81782d7ee60fd6583b33907333a8b340de25ccf468353315"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "finl_unicode"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456"
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "marqdo-embedding-consumer"
version = "0.0.0"
dependencies = [
"marqdo-frontend",
"marqdo-host-contract",
"marqdo-ir",
"marqdo-runtime",
"marqdo-span",
"marqdo-value",
"serde_json",
]
[[package]]
name = "marqdo-expression"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-span",
"num-bigint",
"serde",
"unicode-ident",
]
[[package]]
name = "marqdo-frontend"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-expression",
"marqdo-ir",
"marqdo-markdown",
"marqdo-span",
"marqdo-value",
"sha2",
"unicode-ident",
"unicode-normalization",
]
[[package]]
name = "marqdo-host-contract"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-span",
"marqdo-value",
]
[[package]]
name = "marqdo-ir"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-expression",
"marqdo-span",
"serde",
]
[[package]]
name = "marqdo-markdown"
version = "3.0.0-rc.4"
dependencies = [
"comrak",
"marqdo-span",
"serde",
"serde_yaml",
"unicode-normalization",
]
[[package]]
name = "marqdo-runtime"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-expression",
"marqdo-host-contract",
"marqdo-ir",
"marqdo-span",
"marqdo-value",
"num-bigint",
"num-rational",
"num-traits",
"thiserror",
]
[[package]]
name = "marqdo-span"
version = "3.0.0-rc.4"
dependencies = [
"serde",
]
[[package]]
name = "marqdo-value"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-span",
"num-bigint",
"num-traits",
"serde",
"serde_json",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "memchr-n"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f48c6352cc1185740af256ccc396af598d2366bfd90a34f5afe48744bf06a5b5"
dependencies = [
"fearless_simd",
"fearless_simd_macros",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
"serde",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
"serde",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "phf"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
dependencies = [
"phf_shared",
"serde",
]
[[package]]
name = "phf_codegen"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe"
dependencies = [
"phf_generator",
"phf_shared",
]
[[package]]
name = "phf_generator"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"
dependencies = [
"fastrand",
"phf_shared",
]
[[package]]
name = "phf_shared"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89"
dependencies = [
"siphasher",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_yaml"
version = "0.9.34+deprecated"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
dependencies = [
"indexmap",
"itoa",
"ryu",
"serde",
"unsafe-libyaml",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "siphasher"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "typed-arena"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a"
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "marqdo-embedding-consumer"
description = "Independent Engine consumer: Markdown -> Frontend -> IR -> Runtime without the native host"
version = "0.0.0"
edition = "2021"
publish = false
# A separate workspace: this consumer must resolve and build with its own
# dependency graph so workspace feature unification cannot hide a native-host
# dependency of the engine.
[workspace]
[dependencies]
marqdo-frontend = { path = "../../crates/marqdo-frontend" }
marqdo-host-contract = { path = "../../crates/marqdo-host-contract" }
marqdo-ir = { path = "../../crates/marqdo-ir" }
marqdo-runtime = { path = "../../crates/marqdo-runtime" }
marqdo-span = { path = "../../crates/marqdo-span" }
marqdo-value = { path = "../../crates/marqdo-value" }
serde_json = "1"
[[bin]]
name = "embedding-consumer"
path = "src/main.rs"
+21
View File
@@ -0,0 +1,21 @@
# Embedding consumer
This is a real, independent Cargo package, **not** a workspace member. It is
the engine-side acceptance consumer for issue #13 / ADR-0071: it builds and
executes the same `.mq.md` program through the real Markdown → frontend → IR →
runtime path while depending only on the platform-neutral engine crates.
It must never depend on `marqdo-host`, `marqdo-sandbox`, `marqdo-foreign`,
`marqdo-plugin-abi`, the CLI or a native loader. `tools/ci/check_engine_boundary.py`
builds it with `--locked`, verifies its dependency tree and compares its
results with a real CLI invocation on the same program.
The `TestHost` here is a bounded in-memory host for this consumer, not a
published product host: it grants no external effect, and cannot be described
as a sandbox or as equivalent to the CLI's `pure` mode.
Run:
```bash
cargo run --locked --manifest-path tests/embedding/Cargo.toml
```
+51
View File
@@ -0,0 +1,51 @@
# Embedding
## @exec sum_to
`params(n: Int)`
`i = 0`
`total = 0`
`while i <= n`
`total = total + i`
`i = i + 1`
`end`
`return total`
## @exec types
`params(seed: Int)`
`record = {"i": seed, "b": true, "t": "héllo", "l": [1, 2, 3], "n": None}`
`return record`
## @exec recurse
`params(n: Int)`
`if n <= 0`
`return 0`
`end`
`return recurse(n=n - 1)`
## @exec oob
`m = memory.new(1, 1)`
`return m[70000]`
## @exec read_file
`r = resource.open("file", "embedding-probe.txt", ["read"])`
`return r`
+400
View File
@@ -0,0 +1,400 @@
//! Independent Engine consumer for issue #13 / ADR-0071.
//!
//! This binary is a real Cargo package outside the CLI workspace. It executes
//! one Markdown program through the real Frontend, static call binding and
//! Runtime and reports the result through the neutral Host contract. It never
//! depends on the Native Host, the CLI, the sandbox or a plugin loader.
//!
//! Positive cases are compared against a real CLI invocation by
//! `tools/ci/check_engine_boundary.py`. Negative cases use a bounded test host
//! and assert the concrete error category; a no-op limit is not accepted.
use std::time::{Duration, Instant};
use marqdo_frontend::analyze_source;
use marqdo_host_contract::{ExecutionContext, Host, HostOp};
use marqdo_ir::{ModuleId, Program};
use marqdo_runtime::{run_with_limits, EvaluatedArg, MemoryLimits};
use marqdo_span::Span;
use marqdo_value::{ErrorCategory, RuntimeError, Value};
const MODULE_ID: &str = "program.mq.md";
/// A small bounded host. It implements real budgets and refuses every external
/// effect; it is deliberately not a published product host or a sandbox.
struct TestHost {
fuel: u64,
stack_limit: usize,
deadline: Option<Instant>,
output: Vec<u8>,
}
impl TestHost {
fn bounded() -> Self {
Self {
fuel: 5_000_000,
stack_limit: 128,
deadline: Some(Instant::now() + Duration::from_secs(30)),
output: Vec::new(),
}
}
fn with_fuel(mut self, fuel: u64) -> Self {
self.fuel = fuel;
self
}
fn with_stack_limit(mut self, limit: usize) -> Self {
self.stack_limit = limit;
self
}
fn with_expired_deadline(mut self) -> Self {
self.deadline = Some(Instant::now() - Duration::from_secs(1));
self
}
}
impl Host for TestHost {
fn invoke(
&mut self,
op: HostOp,
_args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
format!(
"embedding consumer grants no external effect for `{}`",
op.name()
),
))
}
fn resource_open(
&mut self,
kind: &str,
_descriptor: &str,
_rights: &[String],
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
format!("embedding consumer grants no `{kind}` resource"),
))
}
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError> {
if amount > self.fuel {
self.fuel = 0;
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
"embedding consumer evaluation fuel exhausted",
));
}
self.fuel -= amount;
Ok(())
}
fn check_stack(&self, depth: usize, span: Option<Span>) -> Result<(), RuntimeError> {
if depth > self.stack_limit {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
format!(
"embedding consumer stack limit ({}) exceeded",
self.stack_limit
),
));
}
Ok(())
}
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError> {
if let Some(deadline) = self.deadline {
if Instant::now() >= deadline {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
"embedding consumer wall-clock deadline exceeded",
));
}
}
Ok(())
}
fn take_output(&mut self) -> Vec<u8> {
std::mem::take(&mut self.output)
}
}
/// A host with no resource implementation at all: it inherits the trait
/// defaults, which must fail explicitly with `ResourceUnsupported`.
struct InertHost {
fuel: u64,
}
impl Host for InertHost {
fn invoke(
&mut self,
op: HostOp,
_args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("inert host does not implement `{}`", op.name()),
))
}
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError> {
if amount > self.fuel {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
span,
"inert host fuel exhausted",
));
}
self.fuel -= amount;
Ok(())
}
fn check_stack(&self, _depth: usize, _span: Option<Span>) -> Result<(), RuntimeError> {
Ok(())
}
fn check_deadline(&self, _span: Option<Span>) -> Result<(), RuntimeError> {
Ok(())
}
fn take_output(&mut self) -> Vec<u8> {
Vec::new()
}
}
fn build_program(source: &str) -> Program {
let analysis = analyze_source(MODULE_ID, source);
assert!(
!analysis.has_errors(),
"frontend rejected the embedding program: {:#?}",
analysis.diagnostics
);
let module_id = ModuleId::from(MODULE_ID);
let mut program = Program {
main_module: Some(module_id),
..Program::default()
};
program.insert(analysis.module);
let registry = program.callable_registry();
let bound = marqdo_frontend::calls::bind_program_calls(&program, &registry);
assert!(
bound.diagnostics.is_empty(),
"static call binding rejected the embedding program: {:#?}",
bound.diagnostics
);
program.set_call_bindings(bound.bindings);
program
}
fn named_args(args: &[(&str, Value)]) -> Vec<EvaluatedArg> {
args.iter()
.map(|(name, value)| EvaluatedArg::named(*name, value.clone(), Span::default()))
.collect()
}
fn run_case(
program: &Program,
host: &mut dyn Host,
function: &str,
args: &[(&str, Value)],
limits: MemoryLimits,
) -> Result<Value, RuntimeError> {
run_with_limits(
program,
host,
&ModuleId::from(MODULE_ID),
function,
named_args(args),
limits,
)
.map(|outcome| outcome.value)
}
fn report_value(name: &str, value: &Value) -> Result<(), String> {
let wire = marqdo_value::to_wire(value);
let encoded = serde_json::to_string(&wire).map_err(|error| error.to_string())?;
println!("result {name} {encoded}");
Ok(())
}
fn expect_error(name: &str, result: Result<Value, RuntimeError>, expected: ErrorCategory) {
match result {
Ok(value) => fail(&format!(
"{name}: expected error {:?}, ran successfully with {value:?}",
expected
)),
Err(error) => {
if error.category != expected {
fail(&format!(
"{name}: expected error {:?}, got {:?} ({})",
expected, error.category, error.message
));
}
println!("error {name} {}", error.code());
}
}
}
fn fail(message: &str) -> ! {
eprintln!("FAIL: {message}");
std::process::exit(1);
}
fn main() {
if let Err(message) = execute() {
fail(&message);
}
println!("PASS embedding-consumer");
}
fn execute() -> Result<(), String> {
let source = include_str!("../program.mq.md");
let program = build_program(source);
// Positive: Int loop result.
let mut host = TestHost::bounded();
let sum = run_case(
&program,
&mut host,
"sum_to",
&[("n", Value::int(10))],
MemoryLimits::default(),
)
.map_err(|error| format!("sum_to failed: {}", error.message))?;
if sum != Value::int(55) {
return Err(format!("sum_to(10) = {sum:?}, expected Int(55)"));
}
report_value("sum_to", &sum)?;
// Positive: structural values use the single Value Wire encoder.
let mut host = TestHost::bounded();
let record = run_case(
&program,
&mut host,
"types",
&[("seed", Value::int(7))],
MemoryLimits::default(),
)
.map_err(|error| format!("types failed: {}", error.message))?;
report_value("types", &record)?;
// Negative: real fuel exhaustion.
let mut host = TestHost::bounded().with_fuel(4);
expect_error(
"fuel",
run_case(
&program,
&mut host,
"sum_to",
&[("n", Value::int(10))],
MemoryLimits::default(),
),
ErrorCategory::ResourceExhausted,
);
// Negative: real stack-depth limit.
let mut host = TestHost::bounded().with_stack_limit(2);
expect_error(
"stack",
run_case(
&program,
&mut host,
"recurse",
&[("n", Value::int(10))],
MemoryLimits::default(),
),
ErrorCategory::ResourceExhausted,
);
// Negative: real wall-clock deadline.
let mut host = TestHost::bounded().with_expired_deadline();
expect_error(
"deadline",
run_case(
&program,
&mut host,
"sum_to",
&[("n", Value::int(10))],
MemoryLimits::default(),
),
ErrorCategory::ResourceExhausted,
);
// Negative: addressable-memory bounds are enforced by the runtime.
let mut host = TestHost::bounded();
match run_case(&program, &mut host, "oob", &[], MemoryLimits::default()) {
Ok(value) => return Err(format!("oob: expected a memory error, got {value:?}")),
Err(error) => {
if !matches!(
error.category,
ErrorCategory::IndexOutOfBounds | ErrorCategory::MemoryFault
) {
return Err(format!(
"oob: expected a memory bound error, got {:?} ({})",
error.category, error.message
));
}
println!("error oob {}", error.code());
}
}
// Negative: a host that grants no external effect refuses explicitly.
let mut host = TestHost::bounded();
expect_error(
"file_denied",
run_case(
&program,
&mut host,
"read_file",
&[],
MemoryLimits::default(),
),
ErrorCategory::PermissionDenied,
);
// Negative: a host with no resource implementation reports Unsupported,
// never a prose fallback or a silent success.
let mut host = InertHost { fuel: 1_000_000 };
expect_error(
"file_unsupported",
run_case(
&program,
&mut host,
"read_file",
&[],
MemoryLimits::default(),
),
ErrorCategory::ResourceUnsupported,
);
// Sanity: budget fields are not a no-op and remain run-scoped.
let mut host = TestHost::bounded();
let fuel_before = host.fuel;
let _ = run_case(
&program,
&mut host,
"sum_to",
&[("n", Value::int(3))],
MemoryLimits::default(),
)
.map_err(|error| format!("budget sanity run failed: {}", error.message))?;
if host.fuel >= fuel_before {
return Err("fuel budget did not decrease during execution".to_string());
}
Ok(())
}
-12
View File
@@ -1,12 +0,0 @@
# 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 值`
+198
View File
@@ -0,0 +1,198 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "marqdo-plugin-abi"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-value",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "marqdo-plugin-sdk"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-plugin-abi",
"serde",
"serde_json",
]
[[package]]
name = "marqdo-sdk-plugin-fixture"
version = "0.1.0"
dependencies = [
"marqdo-plugin-sdk",
]
[[package]]
name = "marqdo-span"
version = "3.0.0-rc.4"
dependencies = [
"serde",
]
[[package]]
name = "marqdo-value"
version = "3.0.0-rc.4"
dependencies = [
"marqdo-span",
"num-bigint",
"num-traits",
"serde",
"serde_json",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
"serde",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "marqdo-sdk-plugin-fixture"
version = "0.1.0"
edition = "2021"
publish = false
# Independent workspace: this fixture must build with only the public SDK
# artifacts, exactly as a third-party plugin would.
[workspace]
[lib]
crate-type = ["cdylib"]
path = "src/lib.rs"
[dependencies]
marqdo-plugin-sdk = { path = "../../crates/marqdo-plugin-sdk" }
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more